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,734
hello guys welcome back to Tech dose and in this video we will see the decode Zod permutation problem which is from lead code number 1734 and this is from math algorithms the prerequisite for watching this video is to watch my video on finding zor in a range of numbers so the link for this video will be present in the description below you can go there and watch this even if you haven't watched this you can still continue with this video if we recap about how zor works then once or one will be zero zeros or zero will be zero ones or zero is one and zeros or one is one so if you have even number of ones then it will be zero and if you have odd number of ones then your result will be one this is how the zor operator works I would like to announce about our DSA live training program which will guarantee understanding of every programming concept it makes you interview ready in just three months and it will maximize your offers so that you get the best possible pay and in the best possible company you can all the sessions will be live interactive sessions so you will get the feel of a live class and you can ask all your doubts throughout the class in order to get more details please WhatsApp us on this given number let us now look at the problem statement in this problem there is an integer array permutation which is the permutation of first and positive integers where n is always odd it was encoded into another integer array encoded of length n minus 1 such that encoded at I is equals to permutation at I zor of permutation of I Plus 1. for example if the permutation array was one three two then our encoded array will be 2 comma 1. this 2 was formed by doing ones or three which is the first two terms first two adjacent terms and this one was found by doing three zor2 which is the next two terms right given the encoded array we have to find out the original array so from the encoded array we need to find the permutation array it is guaranteed that the answer exists and is unique now let us look at the problem constraints are always very important in this case it is said that n will be less than 10 to the power 5 n will always be odd so our permutation array will always be odd and the encoded array length will be n minus 1 which will always be even let us now look at some examples in order to get a better understanding now given the encoded array our goal is to find the output array that means our goal is to find the permutation array from the given encoded array now let's say the encoded array is 3 comma 2 how was this formed if we assume that the permutation array is ABC that is what I am assuming because I don't know what the elements are according to the problem statement if the permutation array is of size 3 then it will contain the first three natural numbers that is one two three in certain order it can be ordered or it may be unordered we don't know about it therefore we cannot write one two three we have to write ABC right so if the permutation array is ABC then the encoded array can be derived as the first element of the encoded array will be Azor B and the second element of the encoded array will be visor C this is how we can Define the encoded array now in this case since the encoded array is given this three means you are given the value of is or B and this 2 means you are given the value of bees or C so given is or B and B's or C can you uniquely find all the values of ABC that is the problem statement so some of the observations which we can derive from the problem statement is the permutation array is an unordered array with all unique elements from 1 to n the size of the permutation array will always be equals to 1 plus the size of the encoded array and since n is always odd therefore the size of the permutation array will be odd all the time and the size of the encoded array will be even all the time now let us solve an example in order to understand how we will approach this problem so let's take a longer problem statement in this case the encoded array is 6546 now let the permutation array have five elements because if the encoded size is 4 the permutation size will always be 5 which is n right so let's say all the elements are a b c d e now in this case this 6 will be equals to A is or B this 5 will be equals to bizarre C and this 4 will be equals to c z or D the 6 will be equals to desire e that is what I have listed here if you can see I have listed it here now this is the information which is provided to us and we know that the permutation array will be in the range of 1 to 5. certain ordering of numbers from 1 to 5 will form the permutation array that is known to us given these two informations we are required to find all the unique elements a to e in that exact same order whatever it was given in the permutation array now this can easily be done if you know the zor property what is the zor property says that if you take a number let's say a number n and if you zore it with the same number and then you will always get the answer as 0. so if you take A's or NS or n then your answer will be a that is if an element occurs even number of times that will get canceled out in the similar way let's say that you have this piece of information which says that DS or E is equals to 6. now let's say that you know the value of e is 3 we are just assuming that you know the value of e is 3 if you know this then we can sort this item zorit with e on both side and your answer will not change now what happens is this two e's will get canceled out and you will be left with a d and on the other hand on the right side you will have six zor three now you know the answer for this right the 6 is 1 0 and 3 will be 0 1 which will give you an output of 1 0 1 which will be equals to 5 isn't it so your D value is equals to 5 this is how if you know at least one unique element then we can easily derive the rest of the element I had assumed that I know the value of e so I was able to derive the value of D now if I know D in the similar way I can derive C and if I know c i can derive B and if I know B I can derive a so I can derive all the rest of the elements having known at least one unique element so the important question here is how to find out the first unique element like let's say how to find out this e let's take an example if you have two set of values like let's say you know A's or B's or C and if you know is or B then we can zort them both and these pairs the same pairs will get canceled out and you will be left with a value of C in the similar way in our given problem statement if I know is or B's or C's or D's or e and if I know is or B's or C's or D if I sort them together then I'll get the value of e right because all of the others are occurring in pairs now if you look at it what will be the zor of a b c d and e actually this is certain arrangement of numbers from 1 to 5 and they are all unique numbers so it doesn't matter what is the ordering but if you are finding the zor in the range of 1 to 5 it will always be the same okay so you can easily use a for Loop in order to find zor in range of one to five you can get it and similarly if you want to get the value of a b c d now in this case you cannot write that it will be zor in the range of 1 to 4 because you don't know if e is actually 5. now in order to get to this value you have to actually do zor of all the even jumps of values now why do you do only the even jumps or values this is because if you are zorring all these numbers one after another then it will be A's or B and then zor it with B's or C then zoret with c z or D and then zor it with d zor e in this case these two B's are common C's are common these are common so you will be left with only is or E value and I do not want is or e but instead I want A's or B's or C's or D so if you want that you have to avoid the common elements so how can you do that if you make alternate size jump that is the zeroth Jump Then second Jump Then fourth jump and so on then you will be avoiding all the common elements like if you do A's or B and zor it with c z or D then you will get this value A's or B's or C or B so this is nothing but the zorov 6 with 4 which is given year 6 with 4 right all the even jump element 0 or 10 second and fourth and so on so like this you will get this value now once you have found zor in the range of 1 to 5 easily by using for Loop in order of n then you will get the answer as 1 I have already written this and on the other hand if you do 0 of 6 with 4 like 6 is 1 0 and 4 is 1 0 then you will get two this is equals to 2 and hence I have written here two and if you do the zor of this you will get three as an answer so we have derived three and I had already explained if you get a value then how to derive all the rest of the values so it will be very easy to derive the rest of the values if you move backward do the back calculation in order of end time okay so the time complexity of this entire approach is order of n now you are expected to do better in findings or in the range of 1 to n so instead of doing an order of n approach you are expected to do it by order of one approach and it and this is also very easy this constant time approach has been explained in a video zor in a Range so the link will be in the description below you can always go there and watch let us now look at the code this part is actually how to find zor in the range of 1 to n in order of one time so this is explained in my video on sorry in a Range now having known this let us now look at the actual part of this problem so in this problem we were given the encoded array and what we can do is we can find the size that is the value of N and then we have to make alternate jumps that is the zeroth index jump then the second index and then the fourth index and so on which was actually this value this second parameter this value okay and in order to get this you have to get zor in the range of 1 to n so the second value is zor in the range of 1 to n okay according to the previous API so once you have got those two values you have to Zorb those two values together in order to get the unique element and once you have got the unique element that should always be included in your answer which is the permutation array and apart from that you will have to do back calculation like if you know D or E is equals to something let's say 6 and if you got to know e which is the element here and let's say this is 3 then you will do these are e Zord it with the same element on both the sides and these two will get canceled out so D will be equals to 6 or E which is equals to 3 and that is how you get the answer and similarly you do the back calculation and keep including all the elements into your permutation array which is the answer array in this case and finally just return the answer array so this is the entire solution for decode Zord permutation I hope this video was helpful please like the video and subscribe to our channel in order to watch more of this programming videos see you guys in the next video thank you
Decode XORed Permutation
bank-account-summary-ii
There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`. Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique. **Example 1:** **Input:** encoded = \[3,1\] **Output:** \[1,2,3\] **Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\] **Example 2:** **Input:** encoded = \[6,5,4,6\] **Output:** \[2,4,1,5,3\] **Constraints:** * `3 <= n < 105` * `n` is odd. * `encoded.length == n - 1`
null
Database
Easy
null
77
hi everyone welcome to the episode number 11. now before we move ahead i just want to give you a quick advice i have been looking at a lot of comments sometimes you find a problem to be difficult okay that doesn't mean that you are not going to learn it just watch the video if you are not able to watch it in 1.5 x slow down the speed to watch it in 1.5 x slow down the speed to watch it in 1.5 x slow down the speed watch it in 1x okay try to understand each and everything that's been going on i am drawing the recursion tree you also try to draw the recursion dream okay then you will be able to understand it much better and i guarantee if you watch the lecture nicely 100 percent you will be able to understand the concept why because i'm not skipping anything i will make sure that i'm not skipping anything so you will get the complete information it is just that you don't have to hurry up okay for most of the people they are it's being so smooth till now but for few i was reading the comments section i found that they were struggling in like maybe a medium level recursion question so you need to basically take a pen and paper draw the recursion tree try to code it by yourself and you will be able to understand it that is guaranteed okay one more advice is whosoever is following this series after each video try to summarize whatever you have learned in this video okay and put it in the comment section so whenever the next time you will come to this video you will look at the summary and you will be able to understand that okay these were the points which i noticed when i studied this lecture one month ago okay you will be doing a revision right so when you will be doing a revision these notes will be very helpful for you all so make sure that you summarize the lecture and put it in the comment section it's a very good habit and if you follow this till the end you will be able to master recursion okay now in this lecture we'll be looking at combination so it's a very famous again a very famous question combination so uh there's a prerequisite for this lecture also the prerequisite for all the lectures are given in the comment section sorry not in the comment section in the description you will find the prerequisites list of prerequisites in the description just go and watch it if you have not watched it if you remember if you have watched the lectures then you don't have to watch them you can continue with this okay so the prerequisite for combinations is subset okay uh in the lecture number seven we generated all the subset in the lecture number ten we generated the unique subset just go and watch those lectures you will be able to comfortably understand this particular lecture okay so we are talking about combinations i hope you remember permutation and combination we studied this in our high school and there was certain formula for permutation and combination so in this question we will be given certain numbers okay we will be given certain numbers or maybe we will be given a range so let us say the range which is given to us is 4 okay so this range denotes that we can pick up numbers from one to four so the possible numbers which we can pick or which we can select are one two three and four okay so this was the range which is given to us and that's why we will be able to select numbers from 1 to n 1 to 4 okay now how many numbers we want to select k numbers let's say k is equal to 2 okay so you will be given two things one the upper range which will denote that you have all the options from one till that range to select from okay second the number of elements that you want to select so now uh out of one two three four you want to select two elements okay so one of the possibility could be selecting one comma two one of the possibility could be selecting um one comma three one possibility selecting one comma four then another possibility is to select two comma three then two comma four then another possibility is three comma four so these are the six possibilities right these are the six combinations okay all right so we need to generate this so basically we can consider this as we want to generate the subset of size two we want to generate a subset of size two okay all right so we have already seen that how we generate subsets so for each element we have two options either to consider this uh into our subset or to ignore it okay we can consider the particular ith element in the subset or we can skip that element these are the two options that we have for every element right all right so now again let us draw the recursion tree uh we will see certain improvements that we can do because while generating subset we will gen we were generating subset of all these sizes right we were generating a subset of size 0 and we were generating a subset of size n as well right we were generating all the possible subsets but here there's a boundation the size of subset should be two so when there's a boundation we can improve the solution a little bit right so for example let us say i already have two elements in the subset i will not go beyond that i will just stop at that particular point okay there are certain improvements that we can see while drawing the recursion tree so let me go and draw the recursion tree i will start with again i equal to 0 with an empty subset now when i is equal to 0 i'm talking about this particular element 1 so two options one option is to consider it one option is to skip it then again uh here i is equal to two right sorry i is equal to one so when i is equal to i am talking about this 2 i can ignore it i can consider it so let us say i am considering this 2 so i will get 1 comma 2 if i am ignoring it i can i will be getting 1 here also let us say if i am considering it i will be getting 2 if i am ignoring it i will be getting empty i is equal to 2 here so i am talking about this particular 3. now from this particular branch from this particular node i will not go beyond why because the size of subset is already two right okay so i will not go beyond this i will stop at this particular point for this particular node then let's talk about this node so here again i have two options one option is to consider the ith element which is three so one comma three or to ignore three if i ignore three it will remain one then here also two options one option is to consider it two comma three one option is to ignore it will remain two here also two options one option to consider it will be three one option to ignore it will still be empty okay then i will be equal to 3 here all right when i is equal to 3 we are talking about this 4 so we will not go beyond this particular node then here again i have two options one option is to consider there is one comma four one option to ignore it will remain one and for this particular node i will not go beyond for this particular node again i have two options one option to consider four one option to skip four here also two options one option to consider four three comma four one option to skip four it will be three here also two options one option to consider four it will be four one option to skip four it will be empty so i have one comma two i have one comma three i have one comma four i have two comma three two comma four three comma four so in total six combinations i have so that's how i will be do i will be solving this problem so what are going to be the base conditions here the base conditions in the subset problem was when i reaches till the end when i reaches the size of the array that was this only stopping condition when we were generating subsets because we were free to generate subsets of all the possible sizes but here the base conditions are slightly going to change so we will also consider the size of the subset as the base condition one base condition obviously will be i the uh the ith element okay that will remain the base condition then one more base condition will be added and that's that base condition will be the size of the subset so if the size of the subset is equal to the given k we are not going to go beyond that we will return from there we will save the answer and return from there okay this is going to be the another base condition so two base condition we have already seen now there's one more improvement that we can do here so here what we are doing we are trying to generate a subset of size 2 right and we are avoiding ourself to go in the direction where the size of subset is exceeding to and that is saving us some time okay there's another improvement that we can do just pause the video think of it what else can we do is there any way we can avoid going to these particular nodes where the size of subset is zero or one we can even avoid it right we can avoid it from here itself then why are you even going to that side if you are going to that side you will not be getting the subsets of size 2. so you can even avoid going to these sides right so for that there should be another condition just think of it maybe you can pause the video take a pen and paper try to think of the approach and then you can code it along with me okay so now let us jump to the coding part there itself i will show you what condition can be put basically what is the third base condition that i can put to even improve the complexity okay by putting these base conditions we are just improving the complexities right we can even put only one base condition that is of i when i let's say when we were generating subsets right we had only one base condition when i reached the end then we were stopping right in that case we ended up generating all the possible subsets right 2 raised to the power n but here we don't need all the possible subsets but our answer lie within all the possible subsets only so that's why we can generate all the possible subsets for sure we let okay i will show you with the help of the code itself so yeah here the here's the code so we are given n as the upper bond as i told you and we have numbers from 1 to n okay and we need to generate the subset of size k all right so let us start solving this first of all i will be creating a helper function void help in this i am taking i the side denotes the current number on which i am currently standing on then i will have the upper bound n then i will have k then i will have subset vector of int subset then i shall also have a vector fin answer if you remember these steps then it's fine if you don't remember just go to the lecture number seven then see what all things did we discussed there so everything has been discussed we are writing exactly the same solution subset okay so for every element i have two options one option is to consider this to take this element so take the ith element okay if i'm taking the ith element i should put it inside the subset dot push back the ith element okay and then ask recursion to do the remaining task what is the remaining task from i plus 1 do the remaining task n comma uh now how many elements do i need now i need k minus 1 elements right because one element has already been taken so i need k minus 1 elements that's why i'm passing k minus 1 here okay so k is the total number of elements that i want in the subset right so initially it was given to me as k now i picked up one of the element here i am selecting one of the element right that's why it is k minus 1. i will ask recursion to do the remaining task from i plus 1 and i will also pass k minus 1 because one element i have already selected now recursion i have to do the remaining task with only k minus 1 elements recursion only have to select k minus l k minus 1 elements right that's why i'm passing k minus 1 over here then subset comma answer okay now ignore or skip the ith element if i want to skip the ith element first of all i will have to pop it out because i have already inserted it in the line number four so i need to pop it out pop back so i'm popping this out now i am not considering the ith element i will ask recursion to the remaining task from i plus 1 but again i will be passing k because i am not selecting any element right so recursion have to do the remaining task and recursion have to select k elements all right subset answer so this is it now the base condition would be i'm just putting one of the base condition as of now later on we will include two more base conditions that we talked about so first of all if i is greater than equal to n not equal to basically equal to is considered right equal to is acceptable so only if i is greater than n then only we are going to stop we are going to return but before returning we should also save the subsets which are of size k right we should also save the subset which are of the size k is given to us here right or we can say because we are reducing k right we keep reducing k so we should also save the subset if k is equal to zero so because we are every time we are picking up an element we are reducing k so k will become zero at the end right k will become zero it will go to negative value as well k will go to negative side as well but we do we have to ignore the negative side why will it go to the negative side because we have selected more number of elements than what the question wants us to select right let us say the question wants to select four elements right and if we selected five elements because there's no restriction as to how many elements i want to select right there is no restriction so that's why i will end up generating all the possible subsets and that subset could be smaller than what we want or it could be larger than what we want when the subset is smaller than what we want this k will be positive when the subset is larger than what we want this k will be negative and if the subset is exactly what we want the size of subset is exactly what we want then this k will be equal to zero that's why i'm saving the answer here answer dot push back the subset okay this will generate the answers right then i will return from here now let me create a vector of int subset and a vector of end answer okay and let me call this function help initially passing i as 1 because we can consider all the elements from 1 to n then k then subset then answer and that's it after this we shall return the answer from here let me see how they want the output to be so input format is this output for each test case print all the possible combinations in each line let us run this let us see if we are getting correct answer yes we are getting correct answer let me submit this hopefully we will be able to submit this although we have not improved the solution this solution is 2 raised to the power n because we are constructing the entire recursion tree we are going from every node we are going to the deepest level okay but as i told you there could be a slight improvement that we can do what is that slight improvement so let us say i have already selected k number of elements okay so i can put a condition here again put a condition over here if k is equal to 0 then stop no need to go further return from here save the answer return from here so if k is equal to 0 just save your answer over here and return bye okay now this will save us from having subsets of larger sizes okay this will save us from having subsets of larger sizes done when i is greater than n when i is going beyond the boundaries then simply return now you don't have to save the answer because you have already saved the answer at the first base condition all right so this is a slight improvement that we did over here we basically saved ourselves from going to the side where the size of the subsets were increasing because we don't need to go to that side okay we don't need to go to that side there's another improvement that we can do sometimes it might be possible that i keep skipping elements i keep on skipping elements and let's say i have a subset of a certain size and i know that i have already i have only few elements remaining now even if i consider all those elements inside still i will not be able to generate the required subset okay so for example let us again go to the board for example let us say i want to generate a subset this k is given as 10 this case given as 10 to us i want to generate subsets of size 10 right now let's say 20 elements are given to me i kept on skipping elements one by one i kept on skipping elements and i reached to let's say uh let's say 11 okay i reach to 11. now i have to take a decision whether i should take 11 or not take it okay so here i will be only able to take 11. i have to take 11 there's no way i can skip it if i skip 11 after 11 what will be there 12 till 20 so only 9 elements will be there 12 till 20 12 13 14 15 16 17 18 19 20 9 elements will be there so if i skip 11 even if i pick all the elements after 11 i will still be not able to generate a subset of size 10 that's why i cannot go in that direction okay so let's say if i'm standing at 11 until now i have not picked up anything okay till now i have not picked up anything all right so i will have to select 11. there is no other choice okay normally what all choices do i have one choice is to skip 11 one choice is to select 11 right so if i select 11 i can go in one direction if i skip 11 i will go in another direction but here the another direction of skipping 11 is not allowed why because our subset that we have generated till now is very small and even if i skip 11 and even if i added all the elements which are after 11 i will not be able to generate the required size subset that's why i should stop going to that direction and it will give us a very good advantage this tree these kind of things will be removed from here okay like skipping uh here and skipping over here these kind of things will be removed and it will still save us a lot of time so basically we did two improvements one improvement don't exceed the size k okay don't take more than k number of elements in the subset this was the one direction okay other direction was don't take so less elements in the subset so we saved we basically uh what do we say bounded it we bounded our solution these are called the boundations so now instead of 2 raised to the power n it will be much less than 2 raised to the power n because the tree will be thinner okay the tree will be shorter it will be compact number of nodes will be less in the tree this is how you improve the solutions and this is how you discuss it in the interviews right so what did you do one thing you did not allow more number of elements than the required element second thing you did not allow very less number of elements than the required elements right that's why you bounded the solution that's why the number of nodes reduce that's why the time complex complexity i would not say is it reduced because in the worst case the complexity could be 2 raised to the power n but the time is reduced the run time is reduced okay you will see it will help us in the runtime the solution will be much faster although the complexity wise it will be same because complexity is in the worst case right but in terms of time it will be much better then uh yeah talking about the uh time complexity it will be 2 raised to the power n worst case but talking about the space complexity the height of the tree will be equal to n right that will be the space complexity required so big of n space complexity time complexity is 2 raised to the power n and if you talk about the space complexity of the answer that we are returning we are also written in an answer right that's a very huge thing it contains basically all the combinations so we have to talk it we have to talk about it separately to the interviewer okay so to the interviewer you will say that okay recursion is giving us this much space complexity and the answer that we generated is giving us this much space complexity so the total space complexity is the addition of both that's what you have to explain to the interviewer you have to explain it separately okay all right so now we have a better understanding of how we can avoid going to the size where the size of the going to the side where the size of the subset is increasing so much so we have already added that condition now talking about the other condition where the size of the subset is very less and we cannot afford skipping the element right so for that uh k is the required remaining elements right k is the required elements that we want okay and n minus i plus 1 will give us the remaining elements these are the required elements so just in case the remaining elements are less than the required elements in this case we should return it basically means that we are in the wrong direction okay we are in the wrong direction now the remaining elements are smaller than the required elements so we are definitely in the wrong direction we should return from here there is no point going any further down in this direction we are absolutely in the wrong direction remaining elements are less than required elements so return so that's what i am going to include over here one more condition if the remaining elements k sorry if the required element k are greater than the remaining element which remaining elements are n minus i minus 1 so in that case sorry plus 1 in that case return right so let us see if it gives us the correct answer yeah it is giving us the correct answer let us submit this and it got accepted so these are the improvements that we can do in the recursion problems and the backtracking problems these are certain kind of improvements that we can do okay so if you just think peacefully these improvements are very easy to do right these are very basic things okay first of all what did we do in this lecture we basically tried to generate all the possible subsets now we don't want all the possible subsets that's why we bounded over solution we bounded it from the left side and from the right side basically we basically stopped it from going to the direction when the size of the subset is so large and we stopped it from going to the direction when size of the subset is so small that's how we improved it right so this is it uh make sure that you take a pen and paper please try to dry run by yourself write down the entire solution then only you will be able to digest all these things and once you digest all these things right everything in recursion everything in dynamic programming will become very simple for you guys so please give it time give it proper time to digest take a pen and paper not only for this lecture even if you are not able to understand the previous lectures make sure that you do the same thing summary try to understand the lecture write the summary take a pen and paper try to learn thing okay try to draw the recursion tree by yourself this is how we learn all right so let us meet in the next episode we will be doing another problem uh that will be combination some let me show you the problem statement or you can find the link in the description you will find link in the description as a homework problem so you can try it by yourself in the next lecture we will try to solve it together okay bye take care
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
56
hey there welcome back to this video now we're going to solve according to the problem mars intervals we're given an area of intervals where intervals i equals to start i and end i our job is to merge all overlapping intervals and we have to return an array of the non-overlapping intervals that cover non-overlapping intervals that cover non-overlapping intervals that cover all the intervals in the input this is the problem statement for example if you are given these intervals as input then we have to return these intervals why is that for this and these intervals we see here we see the value three and here we see value two three is greater than two so these two intervals are overlapping so we have to merge them if we merge them we have to remove this two and this three and we have to add like so one six then we see six is less than eight so this and this intervals are not overlapping each other okay then we have here 10 and 15 10 is less than 15 so these two intervals are not overlapping so we can add the intervals to this list and we have to return this array and here we removed all the overlapping intervals and this array contains no overlapping intervals now how we can solve this problem let's suppose that we're given these intervals first what we'll do we'll sort the intervals by the first value or by the starting value okay if we sort them by starting value then this interval will be like this now what we will do we will create a linked list and we'll insert the first interval to the linked list then we'll get the end value from the last node in our linked list and that is three and then we'll compare that with these two and we see three is greater than two so what we will do we will replace this three with this value six then the linked list will be represented like this okay we have one six now we are at this interval and here we see 8 and 10 and the last value we get from the last node is 6 is less than 8. so we can insert this interval to this linked list okay then our current interval is this interval and let's get the last value from the last node from the linked list and that is 10 and we see that 10 is less than 15 so we can insert this interval to the linked list so the linked list will be represented like this and we're done the notes in this linked list contains the interval in the linked list we have no overlapping intervals okay now what we'll do we'll convert this linked list into an array then we'll return that array so if we convert this link list into an array then we'll get this array and we'll return this array and this is how we can solve this problem this is the intuition to this problem and i attached the source code to this video check the link in the description for sorting the array it will take speed of n log n time complexity and for merging the interval it will takes bigger of in time complexity so our overall time complexity is bigger of n log n and it will takes big off in space complexity to construct the linked list and our non-overlapping linked list and our non-overlapping linked list and our non-overlapping intervals all right guys this is my solution to this problem thanks for watching i'll see you in the next video oh if you haven't subscribed to the channel please subscribe to the channel like this video share this video i'll see you in the next one
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
310
hey everybody this is larry this is day 16 of the sim december lego day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom i've been a little bit or a lot tired the last couple of days just dealing with uh a giant mice or a giant mouse or a small rat that has that was inside my apartment uh unfortunately but i did get it out uh maybe there's a story there you could i don't know i've been posting about it on instagram so i don't know you want to hear sorry there so i've been way uh much not sleep like i've been up for like 30 40 hours or something like that so but that's it i just took a nap so i feel a little refreshed not that tired but uh not that great but not that tired so we'll see how that goes anyway hope y'all excited about that story but today's forum is 310 minimum height trees it's okay uh tree is under a graph where they'll go okay we know a tree is i think so minimum height trees so um we turn those for minimum height okay uh first thing i would do is look at n and n means that we cannot choose n square so the naive version would be the n square right just for every node make it a root and then see how it goes and then that means that we have to think about this in a smaller way um but you can i really yeah i mean i think you can still i think you can do this in to that first search um or reference search i guess doesn't really matter um because then you would have visited every edge um you have visited every edge in both direction maybe three that for search well between you start from any node so what i would maybe consider doing is start on any node get to a leave and then on that leave go one way and then maybe the other way so that's my upper bound right i don't know if i can do better than that but in terms of the number of passes but that's my current working theory though i don't know if that's true let's see but i think you can in either case um yeah in other case you can do a uh essentially a memorization on this well that seems a little bit tricky maybe not i don't know um maybe there's a small way of doing it i'm blanking out right now from the lack of sleep but what i was going to do is that basically um okay let me restart a little bit so the formulation on my head is that i'm trying to do a depth research because the um another way of saying this problem is that find the note in which the distance to all the notes are minimized maybe i guess yeah okay maybe i guess it does say that right um so in that case you um for example here recommend this uh tree you can say that you know we go we do a recursion right like three going to zero how what is the um uh what is the uh um the farthest path going that way and then three going to one what's the first path going down dot and all these things you could memorize um and then that should be good uh and the naive and naive um a naive resolution of that um time complexity try to figure out its time is that well you know it could be n square right maybe but it is not right because they're only n edges so and for each so for each edge we only have two di um well the only the n minus one edges because it's a tree and because there's a tree with n minor one n minus one edges and each edge you can only go two directions right in this like up or down for example roughly speaking right and so in that case each if you do a um evaluation of um a position you own everything is cached except for or like you can catch everything and there are only like two times n roughly speaking amount of work um so that'll be linear time and that's what we're gonna do um but i just wanted to go over how i would think about this right um yeah okay so let's get started um i talked a lot about this form uh hopefully that makes sense but basically the tldr um i don't know we're here and i am watching i'm doing this live so if it's a little bit slow and you're still here then congrats but if you now find a little bit slow you can fast forward a little bit because there'll be a lot of typing from now on uh we're watching 2x anyway what's your fastest speed okay let's go uh first i'm going to change this little end to big end just a personal notation and then i'm going to redefine let's just say let's just call these yi so then so that i can actually use edges um for my graph i'm going to make it an adjacency list and then this is just for u v whoops in ye edges of u that append v and of course this is bi-directional i and of course this is bi-directional i and of course this is bi-directional i would imagine though imaginable uh i imagine uh bi-directional uh bi-directional uh bi-directional um you know this is so i do this right um and then now we just have to get the answer for let's see right oops all right finger in one place we have four i in range of n so let's say uh and a couple ways you can represent this i guess but let's say you have an answer is you go um let's just say we have min answer right i mean answer min i mean let's see go to um so the yeah i mean let's just say two times n it doesn't really matter what it is as long as it's bigger than a positive answer and of course an upper bound of the answer is going to be n minus one because that's the number of edges if you have a linked list for example that would be your k uh biggest thing though maybe it's n or n minus one but whatever right so this is bigger than that's fine so we have something like you know um i'm just going to calculate or maybe find min maybe something like that and then that's pretty much it right that'll be my idea nope because we have to return the notes of all those things so then now after we do this we can do another pass where you know uh if uh find min of i is equal to min we just append i right yeah okay and then that's it right so that's this is so far uh let's say we have a magical formula that calculates the height given i um then that would be the formula that he read that would be the thing that we get right and then we just get the answer from that you can write it in shorter but i just wanted to be uh i just wanted to make it understandable right so yeah um yeah and then now we have to calculate the do the calculation basically um yeah and then now here we go calculate i uh index maybe just a little bit queries so what is the so what is so now we have to figure out a way what is the uh the minimum height tweak given this is the index well the minimum height tree given this index is that four um yeah so we call height is equal to again this is just a big infinity knight like number um domain doesn't work for one note so maybe we have to be a little bit no i mean what does one know maybe we need a better answer for this for one note but i guess it doesn't really matter because you're not returning the height um yeah i guess so and we i guess we assume that this is connected so i guess maybe that's okay um i don't know how i feel about the minimum height here um at least for the default case so well we'll see we'll play around with this for a little bit but um yeah but and now this is for read in edges of index meaning all the edges is connected to a height is equal to the min of height or um let's just say um get height maybe of uh of index of we um given that the parent is indexed right um so yeah so then now at the end by the end we return to height though we have to okay so if okay fine we will just do something like if length of edges of index is equal to zero then we just return one for the height which one is the height i always oh yeah so then this would be two so then here um yeah we get the height of that plus one being that you have to consider the actual the edge it's the height the number of edges or the number of nodes i always forget actually uh the number of edges okay so then in this case yeah okay fine this we use one edge and we by going to v so let's get the height here okay so then here we do something like this where we have the vertex the parent and that's pretty much the answer and then we do a return of what i say like that okay so here um again we defined this recursively so if um i guess this is never true actually oh well this is only true if there's literally no nodes um but i guess that's fine because we have different base cases to get height so now we can do something like um so what is the base case so base case is if this is a leaf um hmm oh no sorry i think i did this wrong sorry friends um now uh okay i think i confused myself a little bit with min because we're trying to i for my head it was just trying to get to minimum height but actually the actual definition of the height is actually the max height right and what i mean by that is that given this is um given the root is three for example you take the max of all the children which is zero one two four i'm cooking here so it doesn't highlight for some reason oh there we go um so it takes the max of them as the height right so yes i think this is actually correct so then now we don't have to worry about this base case as much um and the height for one node is gonna be zero so that's prettier um because yeah um and then actually now that i think about it now from this um no it's fine um maybe i'll make it more explicit this way um okay so then now we do the same thing right the height is zero for we in edges of whoops uh let's just say this is current for we incur i don't the reason why i use v is because i have this is u and this is v but i'm not consistent about it's a little bad but okay so then height is equal to the max of height get height uh to do v current plus one this is not right or this is not enough um but yeah let me actually write a little bit uh explaining what we're doing because we my naming for these things are terrible um also i use calculator when i use min find min here so okay so um and that's not true right we're just finding the height so let's just do calculate okay fine naming things is hard so okay this gets the height of the tree with it with index and then here get height is going to be um get height is going to be what is get height going to be um get given the current node and the parent direction it came from calculate the length of the longest path to a leaf right okay so that's good and then now this is so then we have to of course factor in that in this case we don't um the assumption here is that we don't care about the direction that we came from um we just care about going downwards right so in this case um we just have to make sure that we is not parent right and i think that should be sufficient um yeah and this should give us the answer though performance wise we'll talk about it in a sec let's run it real quick just to see if it works um okay the object not whoops find men oh larry copy and paste of course this is only a browser type thing because in vs code or something um you know you can there's a refract one so this is accepted for or these this is accepted for the example cases but this is gonna be too slow right as we said because um because there are n nodes and for each node we do essentially a depth first search of the tree and the depth first search of the tree is going to be o of n time and so therefore this n elevation of n time so we get n squared so what can we do i mean i kind of already talked about it so this should not be a spoiler um but if you can always um uh you know to pause a little bit to figure out what the explanation is and see if you can figure out yourself um what how to get this to linear time um and okay so i'll give you a second to pause let's say you resumed here um okay so the answer is by memorization um so the thing that you memorize by is actually this input right so here um so let's do a naive interpretation of this right so what is the naive interpretation of this or not naive evaluation of the complexity right naive complex analysis so current could be zero to n parent can be suited to n so this means that possible inputs is equal to o of uh or over you know n squared right roughly speaking of n squared so that would be your naive way to think about it however like we said one thing that we said is that this is a tree right and because this is a tree to actually this is not true or not tightly true the actual possible input it's it uh is o of n we kind of talked about this and the reason why this is because um because this is a tree each input represents an edge on the tree and there are only of n um edges right i mean in fact only n minus one edges um and in this case we can only go up and down the same edge as we talked about so the only over o of two to the n uh number of possible inputs which is also o of n number of inputs and in that case um then we can do we can um we can do memorization to reduce this because this thing costs o of end time roughly maybe but in the worst case but amortized you can reduce this to over one by memorization um so the same thing that we're going to do from for other type of dynamic programming memorization things um what we're going to do you know it's a little bit different but same idea right so we're going to write so if you do the same thing that i usually do in other videos when i teach i would write something like has cash is you go to this thing uh let's just say force times and for to do right so then n by n or wave to kind of capture this um and then uh actual cache um is you go to i don't know none say because we'll populate it so we have something like this right and then we would write something like if has cash of current paren uh return um return uh whatchamacallit oh yeah return cash of current parent and then so forth right but of course if you uh see this you're gonna realize that well this is n by n right so how do we fix this the fact i mean the fix is easier it's just using something that has a uh a straightforward lookup i mean this i don't usually talk about map complexity on this to be honest um and or i usually assume that this is all one uh when i do lookups but in this case i guess technically maybe it's log n um and that would actually make this um n log n algorithm if the hash lookup is um log n but again let's assume that at um map lookup is all one and caches of one to keep it simple in that case um possible inputs again is of n each input is over one time and of one space then in that case total time is over n and total space is of n um of course you have to um and there are many ways you can do this you can you know do a hash of the current and parent or something like that and then look it up in a hash table um for example in this case you know that the biggest number is going to be um n for each of these two things so you can convert this to a base and number um like by just doing current times n plus parent or something like that or maybe times n plus one i don't know you do the math to double check uh but for now i'm just going to convert it to a tuple um and that would be good enough um actually the way that i would write it is also um yeah and then we set it here as well and yeah and that's pretty much it um let me run it real quick so that when it's wrong i can embarrass myself a little bit um no this looks good um and the one edge case that i would have tested is this n minus oh sorry n g goes to one case um and that looks good so yeah let's give it a submit apparently previously i have gotten a wrong answer and this time yes i did better than the old larry sucker oh larry um but yeah um 1625 um but yeah like i said this is gonna be linear time linear space and this that is what i have with this one um okay let's do a review of how i did in the past twice i actually don't remember this one to be honest so let's see how different i did it um okay so i did do it with the diameter of a tree out way of doing it um which is also fine to be honest um yeah i mean this um yeah this is one of the ways that we kind of talked about with the two um two searches um yeah this is the diameter of a tree so i don't know uh it's a little bit awkward let's see i'm not gonna go into that much it's a little bit of a trivia about the diameter of a tree but i today i'm not gonna go over let's see what happened i did it the first time oh i did it with the diamond over tree that time too that's interesting okay um yeah but this time i did it with dp um i guess yeah i guess technically here i did not do it with dp i just kind of do it with this dynamic recommend so i'm glad that i kind of did it another way this time and especially this way we kind of able to talk about how to analyze the number of inputs for dynamic programming so hopefully this is helpful uh let me know what you think let me know how you did uh which way you did it um hit the like button hit the subscribe button join me on discord um hope you all have a it's i guess thursday now soon i hope you stay good stay healthy to good mental health um take care of yourself take care of others if you can i'll see you later and bye
Minimum Height Trees
minimum-height-trees
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs). Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**. The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf. **Example 1:** **Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\] **Output:** \[1\] **Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. **Example 2:** **Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\] **Output:** \[3,4\] **Constraints:** * `1 <= n <= 2 * 104` * `edges.length == n - 1` * `0 <= ai, bi < n` * `ai != bi` * All the pairs `(ai, bi)` are distinct. * The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
How many MHTs can a graph have at most?
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,210
843
this problem is called guess the word and let's understand so we have a string array of strings or words so word one word two and these are unique words so same word will not be repeated so these are all unique and all the words each of these words is six letters long so this is true for all the words in this words array you have also one helper object master which gives you an API guess so you can call master dot guess and you can pass any word to it of that length same length 6. and it will return two things either it will return -1 so if you call this guess for return -1 so if you call this guess for return -1 so if you call this guess for any word that is not in this list then it will return -1 it will return -1 it will return -1 or if it's in the list it will return count is the number of matches with a particular word so out of these words one of the words is called a secret word so we have a secret word uh among one of these words we don't know which word is a secret word but when you call this guess function it will return the number of letters which match so you call guess for some word let's say word three and let's say word two was the secret word we don't know that so what it will do so word two is also six letters long word three is also six letters long so it will do character by character match not just the value character but also the position so let's say this matches and one of the characters at Fourth position matches and one of the characters at fifth position matches among these w 2 or the secret word and the word that we called W3 so in this case it will return three if none of the characters match it will return 0 but if this W3 is not in the list itself then it will return -1 then it will return -1 then it will return -1 and uh you have to find the secret word but you can only call this guess limited number of times so there is some limit allowed guesses which we do not know so there will be some limit for each of the test cases and you have to figure out the uh secret word within that limit so for example let's say we have this list all of them are six letters long you can check and let's say the first word this is secret word in this case this is not known to us this is hidden which is what we are trying to find also this parameter we do not know what will be for each of the test cases so let's see a sequence of calls to guess and what the value is returned so let's say we call master.s for a master.s for a master.s for a so you see that this is not in the list so it will return minus 1. if you call with let's say this first word then it's exactly the secret word so if you do character by character match all the six characters match so it returns 6. so maximum value this guess function can return is 6. so minus one two six if you call on this a c k z it returns 6 then let's see this value c b a z and the secret word let me write it here so if you see this sixth position matches fifth position matches this does not match again there is a match so in total for this call there were three matches so it returns three similarly you can verify for this call two characters will match then a b c z uh four characters match that is a then last two that is three and one of these C values matches so four so uh how we will Design our approach how we will approach it so that we take less number of calls to master dot guess of course if you call for each of the words then ultimately one of these will be secret word but you may exhaust that limit so we cannot do that Brute Force we have to do better so what is the approach is that this is our words so there is a words list it has different words W1 W 2 W 3 W 4 there can be many more uh and there is secret word let's say W3 this is secret word so we can randomly pick one of these words so first step would be pick random word W from words so it will be one of these so the way to do that would be to generate a random number from 0 to number of words N minus 1 and then get the word and add index and then so w is the word that we picked randomly then do a match on uh sorry we can call this master don't guess on W so it will return some value let's say it returns match is the variable and it holds some value from minus actually it will not be minus one since we are only picking from the list so it should return some value from 0 to 6. both inclusive so this is the second step and then the third step is that if match is six then we found the secret word then that means w was the secret word so we return from this function no need to make further calls to guess because we don't want to waste this calls so we return from here but if the other case will be that match is less than 6. and that is the fourth case so let's say match was some value m or let's take a specific example let's say the match was 2. it cannot be more than five because if it's 6 we will return so let's say two characters match for this given word w so now we know that whatever is the secret word among these words two characters exactly match with value and position with this word w so what we will do we can eliminate all the other words so first we will do a match of W with W1 so we can write a match function which does character by character match so match W with W1 if it's exactly equal to 2 then we include this W1 to the list of candidate words candidate secret words include W1 to it again call match for the blue bit W2 let's say this time the match so let's say this time the match was 2 so we included now the match is let's say three so we will not include it because we know that whatever is the secret word only two characters match similarly do for uh match with w three W four so whatever for whatever word the there was exactly two characters matching in value and position we include in the candidates so now we have a new candidate list so initially all the words were candidate words for secret word but after one call we reduced it so this is the new candidates again call it randomly so uh this character itself will not be included so whatever it was called earlier because um word by word match between W and W will be six so automatically this will not be included in the next candidate so this is now filtered out so now again make the call so let's say this time the match was four so among these again scan so for whatever word we made the call we will check how many characters matches with all the words in this candidate list so for whatever word the match was not 4 we remove them from the candidate list so again it will reduce or ultimately either the list will become empty or the secret word will remain or it will return prematurely when we randomly picked the secret word by chance then it will return from there itself so uh let's run through it so initially we call guess so initially all the words are candidate words now we call on let's say this word randomly e i o w z and the guess function returns uh if you do Z and Z match so two position W does not match o i e that does not match so it returns two now we scan this so we call for this we match between these two first two characters match so we include a c k z in the candidate list then we come here we do a match between these two z is 2 w a again so we include this in the list as well then if we do match with this return value will be 6 so we will not include then we do a match here so again there's a match of two so now this is the new candidate let's say randomly we pick this value so it will return if you do z C does not match this C matches this B does not match then a matches so again we made a guess with a b c in gen Z and it returned four now do a match of this word with all the other words and see whether there is a match of four characters so these two there will be match of four so we will include in the candidate list these two C does not match b e does not match a does not match so it returns two so we will again not include it so now the candidate list has just one word if we call guess again on this it will return 6 so we are done so this is how we will do so ah let us write the code for this so this is a lead code hard problem and so uh don't bother if you don't get it in first attempt and it has been asked many times in Google interviews so first what we will do we will Generate random numbers so we can see the random number with current system time you can also have some other strategy like you always pick some middle value or first value but it's better to have a random uh so let's have the list of candidates let's define it candidates so we include all the words in the candidates list initially so now all the words are part of candidate then what we do while candidate is not empty so we will pick one of the words randomly so we have to pick a number between 0 and what's dot size or candidate dot size so this candidate size will change every time so we will take size of that minus 1. is one of the random numbers and then we index on this value so we will take modulo candidates dot size so it will return a value between 0 and candidate Note size minus 1. now we have this word and we have to find how many characters match with the secret word so we will call master dot guess and we will pass this word then what we have to do uh we will compare it with all the other words in the candidate if so we have to also Define a match function so we will be calling that match function now let's call it FInd matches then we have a string word one over two initially count is zero then we know that these words are of length six you can also have W1 dot size but we know the length so we can directly use six if W1 I is equal to W 2 I then character at this position matches so we increment count and finally return count now we will make call to this function find matches with w and whatever was this candidate word for which we called the guess so if this gives exactly number of matches whatever was written by guess then this is a candidate for uh this uh secret word so this candidate will be updated so either we can remove it or it's a vector so better create a new temporary vector and which will be the new candidate Vector so we will assign it back to candidates so we can push it to temp this temp will become the new candidate and then so which will be of lower size ah so we did not add that check for six let's add it so once we make the call we can check here if match is equal to 6. then no need to make further calls we can return and that's it let's try so it will be Vector of string because it's holding the words so the output is you get the secret word correctly let's submit to check if all the test cases pass and the solution is accepted and if you see it's faster than 100 percent of the submissions
Guess the Word
binary-trees-with-factors
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: * `-1` if `word` is not from `words`, or * an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter `allowedGuesses` for each test case where `allowedGuesses` is the maximum number of times you can call `Master.guess(word)`. For each test case, you should call `Master.guess` with the secret word without exceeding the maximum number of allowed guesses. You will get: * **`"Either you took too many guesses, or you did not find the secret word. "`** if you called `Master.guess` more than `allowedGuesses` times or if you did not call `Master.guess` with the secret word, or * **`"You guessed the secret word correctly. "`** if you called `Master.guess` with the secret word with the number of calls to `Master.guess` less than or equal to `allowedGuesses`. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method). **Example 1:** **Input:** secret = "acckzz ", words = \[ "acckzz ", "ccbazz ", "eiowzz ", "abcczz "\], allowedGuesses = 10 **Output:** You guessed the secret word correctly. **Explanation:** master.guess( "aaaaaa ") returns -1, because "aaaaaa " is not in wordlist. master.guess( "acckzz ") returns 6, because "acckzz " is secret and has all 6 matches. master.guess( "ccbazz ") returns 3, because "ccbazz " has 3 matches. master.guess( "eiowzz ") returns 2, because "eiowzz " has 2 matches. master.guess( "abcczz ") returns 4, because "abcczz " has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. **Example 2:** **Input:** secret = "hamada ", words = \[ "hamada ", "khaled "\], allowedGuesses = 10 **Output:** You guessed the secret word correctly. **Explanation:** Since there are two words, you can guess both. **Constraints:** * `1 <= words.length <= 100` * `words[i].length == 6` * `words[i]` consist of lowercase English letters. * All the strings of `wordlist` are **unique**. * `secret` exists in `words`. * `10 <= allowedGuesses <= 30`
null
Array,Hash Table,Dynamic Programming
Medium
null
1,579
hello guys welcome to deep codes and in today's video we will discuss liquid question 1579 that says remove max number of edges to keep graph fully traversable so guys this question is somewhat of a medium level where if you get the intuition right then it is an easier for you to write the code and approach to the solution so the intuition part is very much important here uh rather than the coding part now let's begin with the question understanding so here you are given two percent Alice and Bob and you are given n nodes along with that three different types of edges so a type 1 Edge is The Edge where only early skin travels a type 2 Edge where only Bob can travels in type 3 Edge where both arrays and bobbin travels and the edges are given in this firmware first parameters that type in the second two parameters are the source and the destination node okay here the statement states that a graph is fully traversed by Alison Bob is starting from any node they can reach to all other node so for from any node if they start and then if they can reach to all other nodes then we can say a graph is fully traversed by both a listen Bob and here we need to return maximum number of edges that can remove right that we can remove and after also after removing these edges the graph must be fully traversed by both the list and Bob and if there is a situation that a lesson what kind of travel troubles the whole graph then written minus one okay see guys Towers the whole graph our graph is fully Traverse that means that all the components or all the nodes of a graph are connected there must be edges between all the notes right then only you can travel all the nodes from one node right from one starting node you can Traverse all the nodes so that the simple meaning of this and yeah we need to return the maximum number of edges that we can remove okay got this so guys now taking a look at the first example let's first take a look if a bobcat Travers in a current graph or not ah let us say let us take a look first for Alice right Alice so see their red means type 1 H green means type 2 Edge and Bloom is type 3H okay so all the red edges are type 1 that is can be traversed by Alice and all the blue R can be also Traverse batteries because they are of type 3. so from here Alice can travel so this node from here it can travel through this node because this is a type 3H and from here it can travel so this node so starting from here a list can travel to all other nodes of a graph so we can say yeah the graph is fully traversable for Alice now if you take a look for a bob let me change the color so let's say Bob starts from here since there is a edge bobcane travels from here to here this is a Type 3 Edge and from here Bob can travels to this node as you can see there is also one type CH So currently the graph is fully traversable for Bob also so both Alice and Bob can travels in a current graph okay got this now we need to find if there are some edges that we can remove such that i1 after removing those edges both the list and Bob can travel okay so let's take an example of this Edge if suppose this isn't there is no edge here from one two three so initially this was a edge for a list only type one Edge so can Alice Towers through this node from this node yeah Alice can transform here to here and then from here to here right so removing this Edge will won't affect the connectivity of the graph right so yeah we can definitely remove this image further we can also remove this Edge right this red one Edge at least H because there is already a Type 3 Edge right from here to here one node one to node two so we can remove this H apart from that we cannot remove any of the other as you see if you remove this Edge then from node to a list can never be able to Traverse node 4 right so yeah only this Edge and this Edge can be removed so that's why we have two as our answer where we are removing the Edge from Node 1 to node two so this is this Edge and uh node one to node frame that is this Edge right here now if you look at the second example so here let's say at least want to travel Alice is let's say here so Alice can Traverse from uh this is the type 3 so it can uh so here it can Traverse to a list can travels to here then here because there is one edge of type 1. so now if Bob want to Traverse then Bob can Traverse let's say Bob starts from here then blockade travels to here right because this is a Type 3 Edge from here travels through here also from here Bob can travels to this node So currently a lesson bobcane travels from one node to all other nodes right so the graph is connected now is there any way that we can remove some of the edges and even after that the graph can be remain connected see guys if you take a look that this is a Type 3 Edge and this is a Type 3 Edge now there are no other parallel edges along with this type 3 Edge right so if there would be any Edge for the Bob let's say from two to three then this would be redundant H because that is already a Type 3 as well both Alice can and Bob can travels so parallel to that edge there is no other edges so there are no redundant edges here correct so there are no such radianted edges so we written zero as our answer because if you remove any one of the edges from this graph then the connectivity of a graph won't remain right the graph would be splitted into two components so that's why we cannot remove any Edge from this graph now if you take a look at the third example so let's Traverse for earliest so from here Alice can Traverse through this node then this note release is trousing Alice but after this Alice cannot Traverse this known because there is no Edge for Alice there is no type 1 or type 3 h and similarly if you take a look for a bob cat towers from there to here and this is the type 3 so walk it round still here but Bob cannot travels through this room so the graph that is already given to us is itself not connected right it's itself not connected and that's why we return -1 as our answer right we don't return -1 as our answer right we don't return -1 as our answer right we don't have to remove any edges because the graph that is already given to us is itself not connected right unless and walk they both cannot travel to all the other nodes right so yeah guys till now I hope you have some understanding of the question that uh what is fully traversing a graph is known and how Alison Bob can travels to all of the nodes right now talking about the approach so what can be one approach so one approach is remove one Edge at the time and check for connectivity so let's say you are given as you said m like H1 that's a 10 HSC organ in a graph let's say n equal to 8 and for that you are given 10 inches now one way is to do is what you can do remove the current date let's say current Edge Azure file remove this is the first step in the Second Step check for connectivity check for at least and Bob connectivity check for Alice and Bob connectivity so we can perform these two steps and determine which edges we can remove right but uh this is isn't an efficient approach because there can be total 10 to the power uh Phi number of edges and for checking each Edge we take we go find time so that is nothing but 10 to the power 5 so this is greater than 10 to the power 9 so that's why here this approach will give you time limit X data right this will give you triggering now what another way we can do is we can reverse this thing so here we were removing one Edge at a time and then checking for connectivity and here what you can do is in the diverse way we can add edge add necessary Edge and Main graph right this is simply the reverse approach of this here we were removing one inside a time and instead of that what we can do is we can add the necessary Edge and make a graph dynamically see the word I am using here is necessary H so we will focus on what is the necessary Edge that we need to add okay but uh how you can perform this so we can easily Perform This by using DSU that is this is Union or Union fine algorithm okay Union fine data structure not an algorithm this is a data structure so with the help of DSU data structure we can create a graph dynamically by adding one Edge at a time by increasing the connectivity among the nodes of a graph and that's why we can make a graph dynamically okay now for the next thing see we have to check connectivity or you can say fully traversable for a lease and four ball right let's see the if let's say if a graph is fully connected for release but that doesn't mean the graph is fully connected for both and vice versa so we have to check connectivity for a lease as well as work so can't we create one separate graph right so let's say uh DSU for Alice and DSU for walk so one graph for release and one graph for both so we can do this because we are creating the graph here in this approach we are creating the graph so since we are creating the graph we should create a separate graph for Alice as well as box so that it would be easy to determine the connectivity it will be easy to determine the connectivity right because there can be case where uh the graph is fully traversable for Alice and not for both and for such a case if we have a separate graph then we can determine it easily right okay clear theorem now further as I told you we will add necessary Edge so to identify whether the current Edge do we have to add or not so for that what we will do see if you are given one some notes like N1 and N2 and you are using DSU distance at Union data structure then how you can tell whether we do we need to add an edge between Nolan and N2 how you can tell whether the two nodes are connected or not say here in DSU we have some we have one function let us find parents so if you do like this DSU this is object of this data structure and you take find parent of N1 equals to TSU dot find parent of N2 so let's see if the final of N1 that means it Returns the parent of anal let's say it is X let's say this is y this is X and Y the parents and if in the condition if x equals 2 y if this condition is true that means the both the components N1 and N2 is connected this is they are connected right got it if two nodes have same parents then we can say they are connected and at that point if they are connected and then we don't Edge we won't add that as we simply add the edge right we simply do what we will simply do DSU dot make Union and one and N to write we do simply do this that is at the current Edge this is at the current Edge and we don't at the edge if that parents are already same means they are already connected because this clear delium now further we have to focus on minimize total edges minimize total Edge that is nothing but equal to remove maximum possible edges right so since we are creating a graph from scratch then we would try to use the minimum number of H is possible right and that would be nothing but equal to maximum edges that can be removed okay so to do this what we would do is we could prioritize type 3H right type three edges we can prioritize them because uh this type 3 Edge would be a path for both Alice and both right and if we prioritize this then any H parallel to type 3 H can be removed right because this type three h can be used by both Alice and both so what we would do is we would prioritize type c h that means first we will build a graph with the help of type 3H then after that we will add edges for Alice and Bob only edges that are necessary okay clear till here now let's take this example and let us try to create a graph okay here let me take a graph for a lease and here let me take a graph for pop now first identify water uh water edges are of type 3 so this is the type 3H this is the type 3 Edge okay these two are only type three h now let's create a graph from a node one see there are four nodes and is A4 equal to four so let me draw four nodes okay and here also let me draw four notes now here there is an edge from Node 1 to node 2 that is of type 3 so let's add the edge here from Node 1 to node two there is a h from two to three at this Edge two to three see before adding this we also check whether there is already an edge or not okay we will check so but there was no access so we simply added so guys after this there is one type one Edge so from node one to node three now you will check if node 3 is connected to node one so for that what you can do is you can make a call for find parent in the DS you will check like this find parent of Node 1 and find parent of node three and if you do that you will find that both Node 1 and node has same pattern and also you can see that you can from node one you can travel smoothly via node two right there is a path from Node 1 to node 3 for wire node two so yeah this is a redundant age and we will count this as a redundant age okay now moving ahead there is again one edge of a type one from two to four now you will check the parent of two and parent of four they both are different because they are not connected as you can see there is no way you can go from node 2 to node four so yeah that's why we have to add an edge here so this is not a redundantage right now there is one another edge of a type one from Node 1 to node two that is from here to here but that is an obviously a redundant Edge because they both are connected so this is again redundant this was also redundant now this is a type 2 H that is what above from a node 3 to node 4. from here to here and you will check that there is no path from node Train by which you can Traverse node 4 so we will make an issue okay so at the end this way you will construct two graphs one for at least one from for work and by adding only the necessary edges right this way we will add only the necessary energies and remove the read and edges right so here there were two redundant edges that we can see and you have been written two as our answer now guys following the same approach we will write the code here see this DSU data structure core snippet would remain same it is I haven't made any changes in this DSU code snippet so now what I am doing here is I am creating two graphs one for Alice and one for Bob okay and I have taken three variables redundant edges total number of freedom and edges in the Alice and total edges in the bomb right now here as I have told you earlier that we will prioritize type 3H or the edge that can be traversed by both early symbol so we will check if an edge is of type 3 then I took the nodes node one and node two that is u n v and I check if uh unv do both have the same parent for our Elise and or do both have the same parent formal if they don't have that means this condition their parents are different for either Alice or Bob in that case we were at we will have to add this Edge means there is no that is not an edge from node one to node two in Alice or a in Bob in many one of the graph then in that case we would make Union in the both right we would add that edge in both and we would increment the count of edges in this Alice graph and the edges in the background I will tell you later and why do we need that and in the else condition if we don't have to add this Edge then what we will do we will simply increment the count of read and read inches that means we have removed that engine and after that this for Loop here we are adding the edges that are specific to earliest and that is specific to ball right of a type 1 and a type 2. if the eyes is a type 1 and that is the parent of Node 1 and node 2 are different in that case at that edge and increment account for Alice edges else condition increment account for redundant energy same thing for Bob and at the end we check see here we are only adding necessary edges and for a graph with n components how many necessary Edge you require n minus one edges are required here right these are the minimum number of edges required if a graph has n number of nodes now here we check if how many edges are there in early graph and how many edges are there in the buffer they must be at n minus 1 because we are adding minimum number of edges and the minimum number of edges is nothing but n minus one edges so they both have n minus of one H's if then we return this count redundant H as we written minus 1 because if there are Edge is less than n minus 1 that means the graph is not connected not fully connected you can see and in that condition or in that situation we will return minus one so you have to keep a track that whether all the nodes of a graph is connected or not we kept our track of how many edges are there in the earliest graph and how many edges we have added the Bob graph and yeah that's why we are using this condition now talking about the time and space complexity see here the time complexity if all this equation is we go of n plus Alpha types of n so this alpha n is nothing but a Time taken by this make Union function so this is a recursive uh function if that means this function will call fine parent and fine parent is itself for equals a function so that will take some time but not much and yeah space complexity is also big open that will be used by this NH data structure here internally we are using two vectors of a size n right size n so yeah that's for the time and space complexity so yeah guys that's all for this video if you guys have any doubts then do let me know in the comment section make sure to like this video And subscribe to our Channel thank you
Remove Max Number of Edges to Keep Graph Fully Traversable
active-users
Alice and Bob have an undirected graph of `n` nodes and three types of edges: * Type 1: Can be traversed by Alice only. * Type 2: Can be traversed by Bob only. * Type 3: Can be traversed by both Alice and Bob. Given an array `edges` where `edges[i] = [typei, ui, vi]` represents a bidirectional edge of type `typei` between nodes `ui` and `vi`, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return _the maximum number of edges you can remove, or return_ `-1` _if Alice and Bob cannot fully traverse the graph._ **Example 1:** **Input:** n = 4, edges = \[\[3,1,2\],\[3,2,3\],\[1,1,3\],\[1,2,4\],\[1,1,2\],\[2,3,4\]\] **Output:** 2 **Explanation:** If we remove the 2 edges \[1,1,2\] and \[1,1,3\]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. **Example 2:** **Input:** n = 4, edges = \[\[3,1,2\],\[3,2,3\],\[1,1,4\],\[2,1,4\]\] **Output:** 0 **Explanation:** Notice that removing any edge will not make the graph fully traversable by Alice and Bob. **Example 3:** **Input:** n = 4, edges = \[\[3,2,3\],\[1,1,2\],\[2,3,4\]\] **Output:** -1 **Explanation:** In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. **Constraints:** * `1 <= n <= 105` * `1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)` * `edges[i].length == 3` * `1 <= typei <= 3` * `1 <= ui < vi <= n` * All tuples `(typei, ui, vi)` are distinct.
null
Database
Medium
null
654
That Welcome Back Friends Today We Are Going To Solve Liquid Problem 1106 Maximum Binary Tree Beach Problem Shuru Skin Pass Microsoft Interview Schedule And Senior So Let's You Quickly Rudra Description Agravan Interior With Notification Maximum Trick Building On This Is Defined S Polo Root Is The Maximum Number Indra are left sub tree is the maximum tree constructed from left part sub are divided by the maximum number the right short tricks is the maximum free constructed from crafts for a divided by the maximum number construct maximum entry bike given here key and returned root note of This free app by Rimsha ranged from 120 on delicious problems and have given one example care how to create a maximum binary tree so let's tree this example here and discuss the problem solve this is in the given to slideshow of you can see how to Find the maximum number clear and the number you can you please like this and you will make 10600 subscribe 505 again in the left here you have to find the maximum will be there will be some this subscribe quickly and use this 3463 10 Gwen you will Find The Year To Is The Amazing Are Right To And Will Become The Right Side Of This One Right After Three Layer Pendant The Meaning Of We Come Again Rise Of The Tourist Like This Cream And Absorbed In 50505 Maximum Which Will Give You A Clear And Remaining 0205 Left Right Left Subscribe My Channel Thank You Will Always Find The Maximum In The Air And How To Put As Drut And You Have Toe And Divided Into Life-Giving Quikr See Buildings Maximum Now By Every Night So Let Me Show You How We Can Do It's Clear Weekly Off Now Sleep Disawar Man Methodist Sonam Jahar Is Given To Rasoi Will Just Call To Make Final Hearing And This Will Do The Oldest Form Side So You Can See The Tree Notice Also 120 The Class Teacher Values ​​Royal And Also 120 The Class Teacher Values ​​Royal And Also 120 The Class Teacher Values ​​Royal And Left And Right Battery saver start live from lag and twitter in old software will give production sharing with father started in these cases and index increase length of the year - 180 basically in this case you can year - 180 basically in this case you can year - 180 basically in this case you can start this hero and will 200 to three four five six digit shoulder ₹ 100 to the end in which specific artist ₹ 100 to the end in which specific artist ₹ 100 to the end in which specific artist greatest and will return night start cannot be greater than end in that case how to three tunnel otherwise will just create one variable in dec20 end max vijay scooter in which invalid na posting 232 maximum tweeting truth and will Keep track of who will get the maximum and they will keep track of winter wear maximum element in the example reduce are three low to one a six 058 and will find the maximum here some maximum element 0123 is the in different so let's produce Basically so after doing its creator train track node from this maximum element like subscribe like this thank you have created this is a in a from this maximum element din will recursively call award omax binary method by passing the same name saare dastan 27th left or right And will be index - one left or right And will be index - one left or right And will be index - one for example in this case start will be to here right and acts will be the - 102 right and acts will be the - 102 right and acts will be the - 102 basically means basically water power to one passing the salary of the next call rate dalit terrorists and andar right side hui calling this right here Right Some Lines Should Have Ended In Wave Right Side Will Be Called Index class12 Android Means Dushwaar 2805 End What Ever You Get From This What Ever Root Wrought Iron Or Will Get Is Written Notes From This Function Will Just Prove That Left For The Left Here End Root dot right for the right clear and will be written in the root musical night sweet dream atul equal dysfunction software call from this left side on free din it will call again lighter to isko like extra will call on two din for two equal in this one Will perform it will be at ace2three * Will be destroyed 150 and will be at ace2three * Will be destroyed 150 and will be at ace2three * Will be destroyed 150 and will be at ace2three Basically and this thing will be and test on the right side of 36 powder equation works right 100% How you can solve the maximum 100% How you can solve the maximum 100% How you can solve the maximum binary tree problem is Woman Of The Pass Microsoft Problem Indore Interview Samay Chori Understand The Recognition And Doing So Is Judged Loot Summary Of Power To Do It Is Hui Air Dividing The Amazing For The Left Side And Right Side First To You Will Find Maximum Android The Left Side There And Will get the right side sharing and you will again fatherhood tips end the rights end here you will update the start and rate a ki sui will always updater start here dalit side will update ends end x minus one end order right side will update start acidic Plus Wandering Soul When Death Will Be Sign A Return Value Responsible Us So Let's Take The Example Set By One Ashwa Other Example Where Taking And Where Is The Meaning Of Word Unit Hair Soft Power Example God Accepted To Edit And Cities For The Real Of rebel 3635 65 blurred subscribe 2520 balls subscribe my channel and again for the petitioner and share and subscribe one percent faster perform such s pretty good for this is the way can solve maximum binary tree if you have already been noida list solutions playlist please check that Leaders Over It All Problems At Explain In Details With Example In Java Code Also Aayi Hai Wah Aur Father Playlist Contest Java Interview Se Aware Of A Difficult Job Interview Questions Tatva Aap Fabric Tech Companies In Passport Is Drawn For The Phone Interview Schedule Amazon Boarding Point Isolation White Building Interview Actually Online So Please Request Aa Fever Chawla Kar You Will Definitely Get Not Good Video Secure Preparing For Coding And For Interview So You If You Like This Video Please Subscribe And Lighted By Your Subscription Is Really Amazing With Can Reach To Other People Like you are preparing for java j2ee interviews a0 and you can also get help from this video subscribe and thanks for watching the video
Maximum Binary Tree
maximum-binary-tree
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value. 3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value. Return _the **maximum binary tree** built from_ `nums`. **Example 1:** **Input:** nums = \[3,2,1,6,0,5\] **Output:** \[6,3,5,null,2,0,null,null,1\] **Explanation:** The recursive calls are as follow: - The largest value in \[3,2,1,6,0,5\] is 6. Left prefix is \[3,2,1\] and right suffix is \[0,5\]. - The largest value in \[3,2,1\] is 3. Left prefix is \[\] and right suffix is \[2,1\]. - Empty array, so no child. - The largest value in \[2,1\] is 2. Left prefix is \[\] and right suffix is \[1\]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in \[0,5\] is 5. Left prefix is \[0\] and right suffix is \[\]. - Only one element, so child is a node with value 0. - Empty array, so no child. **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[3,null,2,null,1\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` * All integers in `nums` are **unique**.
null
Array,Divide and Conquer,Stack,Tree,Monotonic Stack,Binary Tree
Medium
1040
72
foreign so this question has been asked tons of times in so many interviews Amazon Google Microsoft Flipkart so many companies it's good to know about this question so the question says that we have been given two words when and word two then I think there's just two strings of different sizes now what we want to do is we want to find the minimum number of operations required to convert word one into word two what is the minimum number of operations required to convert word one into word two is the question complete or is it missing something according to you so you should talk about what are the different kinds of operations it supports yeah valid question so what are the different kinds of operations it supports so there are three operations that it supports now listen to them very carefully the better you listen the better you will be able to think so the first kind of operation that you can do is you can insert a character keep it in your mind that you have to change word one to become world two so word one is your Source word you can tamper word one you don't have to temper word two so you have to Tamper you have to change word one so that it becomes word two now what kind of changes are allowed so the first kind of change that is allowed in word one is that you can insert a character in word one and it means you can literally insert any character at any position so if your word one is let's say apple then you can insert B over here you can insert D over here you can insert Q over here you can insert n over here you can insert any character anywhere that is the first kind of operation which is allowed the second kind of operation that is allowed is you can delete a character and now again from your world one you can delete any character of your choice so you can choose to delete this P or you can choose to delete that e you can delete any character from anywhere and the third operation is that is allowed is you can replace a character now again this is very open-ended you now again this is very open-ended you now again this is very open-ended you can replace any character with anything so you can replace this L by Q you can replace this a by m so these are the three operations which are allowed and now you have to think and tell me that how many minimum operations do I need to convert word one into word two okay so let's take an example if your word one is horse and your word two is Ross what do you think should be our answer what is the minimum number of operations required to convert word one toward two horse to Ross okay so let us take a look and understand so what is our source word what is the source word which we have to change it is Horse let's take horse and let's play with it so our source word is horse and what if I first replace H by r if I replace this H by R we will get rods right let's do the next operation what according to you should be the next optimal operation maybe now we can remove r which are these are if I remove this R we will get rows now I think we are just one inch away what should be one more operation that we should do we should remove this e if we remove this e what we will get will be cross so you landed from horse to Ross by just performing one two and three operations so your answer is going to be 3. I'm sure that you can't do this transformation from horse to us in lesser than three steps you have to perform at least three steps does that make sense to all of you some yeah so this thing here three is called as edit distance of horse and Ross edit distance uh it is also called as Levenstein distance no need to remember just for you to know it so what is edit distance is simply a number that denotes the degree of similarity between two words so let's say there are two words which are very similar if they are very similar will their distance be very high or very low it'll be very low but if there are two words which are very different then the edit distance will be very high and this edit distance is a very practical thing it is not just a theoretical dynamic programming question it is something which is practically used by so many applications by so many softwares how many of you have uh experienced spelling correction being done on maybe WhatsApp or being done on uh Microsoft Word or Google doc have you experienced that happening auto correction you can call that auto correction so what usually happens is that whenever you write a word and uh WhatsApp feels that the WhatsApp does not have that word in its dictionary then it suggests you those words which are very similar to it and what is the meaning of similar so it computes the edit distance of all the words with it and then tries to you know find that which words are having very smaller distance and then it shows them off to you so edit distance is very important thing uh another thing so uh those of you who would have ordered something from Amazon when you write your address when you mention your address if there are some spelling mistakes in your address let's say you are writing Delhi and there is some slight spelling mistake in Delhi then uh Amazon software can detect that yeah the edit distance between what you wrote and what Amazon has is very low so probably you meant to write Delhi so it will auto correct it so these are some very practical applications already at any distance it is very important thing cool so now let's come to the important thing we want to write an algorithm which computes at a distance of two words so yeah you will see that if you have paid attention to me explaining longest common subsequence then this thing will look like a cake mop for you very easy so don't need to worry if you have paid attention there trust that it is going to be easy so let's say there are two words word one and word two and now just look at the board stop thinking there are two words word one and word two now let's say your word one ends with a and word two ends with a this is your ith and this is your jth character we are starting from the last characters so yeah let's look here for now let's say there are two words word one and word two and you are scanning them from the end if the last characters are matching if world one of I is matching with word two of J will it contribute to the edit distance if the last characters are matching will it contribute to the edit distance will you want to do anything to this a will you want to convert this a into something will you want to delete it or will you want to insert something after it anything like that no anything like that will be absolute nonsense because these characters are doing no harm they are already matching because they are already matching so let them match and focus your attention on the remaining part of word one and the remaining part of word two so I can say that if word one of I and word two of J which is the last characters of the two words that they are matching then the edit distance of i j is nothing but the same as at a distance of I minus 1 J minus 1. so again this is a very obvious thing nothing special about it another way in which you can realize this thing is uh let's say there is a world one and there is a word two your word one is a b c and your word two is apq so tell me what is the distance between ABC and apq how many changes do you need to do in ABC to convert it to apq two changes the first change is you can convert B to T and you can convert C to Q now if I introduce a character R here another character R here does the edit distance get changed no so if the last characters are same the edit distance of this and that is going to be the same as the distance of this and that and this is exactly what I have explained here and written it there so this was the case when the last character smashed what in the last characters do not match so let's say you are world one ends with B this is your character and your word two ends with a this is your jet character so if the last characters do not match if this is B but that is a will you want to leave this B as it is it a correct thing to leave it as it is no we need to take some action we need to act how many element of choices do we have three elements of choices the First Choice could have been to insert a character what character would you want to insert in word one if at all you want to insert what characters you'd want to insert a because if you insert an a right after this B then that a will start matching with this a the moment this a starts to match with this a then you can now easily focus on finding the edit distance of remaining part of word one with remain part of word two the first choice that we had was to insert if we insert that means we are doing one unit of operation and after doing that one unit of operation what just happened the character that you inserted got matched with jth character of W2 so now your J will go back but your I will still stay there you understand this point because this B has not been matched with anything so your eye will still stay there but your J will move back by one unit so what kind of transition will happen Ed of I comma J minus 1 this is what happens in case of U inserting a character in W1 to match the last character of W2 so this is the transition corresponding to insert does that make sense to all okay what could have been the other choice could have been to delete a character so let's do it all over again your word one ending with B your word two ending with a this is your ith and that is a jet character if at all you want to delete some character which character you would want to delete you'd want to delete B Because if you delete this B it may happen that there was an a before it that kind of got matched with this a or there was some other a before this B that at some point of time got matched with it so the second choice that you have is delete corresponding to delete what will happen because you delete this character so your eye will move back but your J will still stay there so in this case your eye moves but your J still stays there what is the final operation that you can do replace so let's say there was B here if you want to replace this B with something what will you want to replace it with you would want to replace it with a the moment you do that both these characters get matched and now you focus on the remaining part of word one and remaining part of word two in which I will also change and J will also change so in this case corresponding to replace it will be 1 plus e d of I minus 1 J minus 1. so when the last characters of the two words did not match then we had these three options but what should be our actual answer we are interested in the minimum number of operations so whatever is the minimum of these three things that is going to be the value of so isn't it easy it's extremely easy if you stick to the Concepts so what you have to do is that you have some strings and let's say you are scanning those strings from backwards then there can be only two possibilities the either the current characters match or they do not match if they match think what should be your transition and if they do not match then think how many elements of choice you have corresponding to those elements of choice you will see how your ing day they cannot change are you able to understand this idea are you able to understand how to think so I'm not interested in you just being able to understand this question it's the thought process which is important if that is being ignited inside you then that is of significance to me Nothing Else Matters there should be some meaning of Ed what is the meaning of adij the meaning of Ed Isa is I denotes the part of first word from 0 to I and J denotes the part of word two from 0 to J whatever is the added distance of this prefix of word one and that prefix of word two that is e d of IJ okay if you understand it now we are almost ready to write the recursive code but before writing the recursive code we need to be clear about the termination conditions guys do you see one thing here that again your I and J are always being reduced only so even if this condition is true your I and J are being decremented and even if the you know the last characters did not match your I and J they are being decremented only So eventually it can happen that either your I becomes minus one or your J becomes minus one so if your I becomes minus 1 what kind of world one does it denote it denotes an empty word one right now tell me one thing if your word one is empty and your word too is something like a b c d what will be the edit distance how will it be zero how can you do zero operations to this and convert it to ABCD is that possible four so if the first word is empty you have to insert all the characters of this one by one here so if the first word is empty the answer is going to be equal to the length of second word you get that similarly what will happen if your J is minus one if your second word is empty and your first word is let's say ABCD what will you do you have no choice but to delete all the characters from here so it means that if second word is empty which is if your J is minus one then you have to return the length of your first word symbolize that do you get it so this is what your termination condition is now what will be the length of second word uh sorry what will be the length of your first word if the last index is I what will be the length will it be I or will it be I plus 1 it'll be I plus 1 because indexing starts from 0. so I can say we can say that if J is minus 1 return I plus 1 which denotes the length of first word similarly if your I is minus 1 if your word one is empty then return J plus 1 which denotes the word the length of second word so that is your simple termination condition so we are just talking about termination condition so whenever you have to think about termination condition just think how your I and J are changing so you can see that your I and J are always reducing only So eventually it can happen if your I becomes -1 becomes -1 becomes -1 so if your I becomes minus 1 that means that the first word is empty and you want to convert it into word two you have no choice but to add all these characters one by one here so if your I is minus 1 you just written J plus 1 because J plus 1 at that time will denote the length of second word similarly if your J is minus 1 and you want to convert word one into an empty word you have to delete all the characters so you'll have to return I plus 1 which denotes the length of your word one at that stage cool so we have our termination condition we have our recurrence relation so can you write the recursive code I'll write a recursive code called as get edit distance which is taking i n j and returns an integer denoting the error distance so if I is minus 1 return J plus 1 as discussed and if J is minus 1 return I plus 1 as discussed otherwise what to do the first thing you will do is you will compare the last characters of the two words so if world one I matches word to J what will you do you will simply say that hey return the edit distance of remaining parts right if this is the case okay otherwise what will you do otherwise there are elements of choice so that means you're supposed to be making these three calls and after making these three calls whatever is the minimum value of them that you will return so you can say hey otherwise I'll return minimum of the three things and you can put those three things as it is over here and put those three things as it is over here that's it drop done so this is your logic so there will be overlapping some problems because you can see that two of the calls here I comma J minus 1 and I minus 1 comma J are just like LCS calls isn't it so if in LCS you got repetitions here also you will get repetition for sure correct so there will be repetition so what to do memoize the first step is to decide what is the dimension of this problem two Dimension we need I and J so we need an answer ready of two Dimension now what will be the size of First Dimension depends upon how many different values I can have I denotes the length of word one so if the length of word one is m then I will vary from 0 to n minus 1 so this can be of size M with the same logic this can be of size n and everything can be initialized in null initially so this is the initialization that can be performed okay in this case you can also initialize everything to minus 1 minus one it is up to you because see initialize them to something which for sure is crap which for sure is garbage because we know that edit distance can never be a negative quantity so if answer of i j is negative that means it's a garbage value it's not been solved so you can initialize them to null you can initialize them to minus infinity negative thing anything that's up to you it does not really matter okay now only things that remains over here is memorization checks can you put your memorization checks super easy so after termination condition here you can check if answer of i j is not equals to null then you will simply return answer of i j otherwise you will make the call and you will store that inside answer IG same thing needs to be done in the other scenario as well you will solve for it and you will store it inside answer I J and finally you will just return answer is Do You observe that there is a very similar pattern which is being used across all the problems of DP so the only thing that you need to do is you need to practice with this pattern so you have this set idea inside your brain now you need to work with this idea on some problems so again like uh if you have your if you have an ongoing subscription on Vanessa you have a lot of ample of homeworks based on the applications of this idea so like once you learned Lis LCS you found that riverwala question to be very exciting similarly once you learn this you will find its application based questions that are there to be very exciting and you'll be able to map the third process you'll be able to apply the thought process and then you'll be able to retain it for very long amount of time then this will just became a nature of you a nature with which you can think for a given dynamic programming question anyways let's talk about the space complexity is going to be M into n because we have declared ancillary of size M into n what about time complexity what were the steps to figure out time complexity the first step was to find how many different problems we are solving so how many different problems we are solving M into n and in order to solve a problem how much work we are doing so even if you're in this case you're just doing one assignment operation in the other case you are finding minimum of maybe three things doing three additions you're doing constant work for each problem and there are M into n problems so total work will be nothing but M into n
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
1,711
hey there everyone welcome back to lead coding in this video we are solving the second question of lead code weekly contest 222. so you can go through the problem statement uh in simple terms the problem is asking us to find the pairs such that the summation of both those numbers is a power of 2. so let us see this example in this 3 and 5 is such a pair because 3 plus 5 is 8 and 8 is the power of 2 then 7 plus 9 is 16 against the power of two so these are the pairs that are available to us and we have to return the number of such pairs so one obvious way is to do a brute force and brute force will be n square we are going to go on each pair for each eye we are going to go on each shape and we will see that if the summation is a power of 2 so it's simple to check the power of 2 that we can do in a login time so it is given that the number could at most be 2 raised to the power 20 so it is going to take log of 2 raised to 20 with a base 2 that's going to give us 20. all right now we have to do better because the number of integers could be 10 raised to the power 5 so n square will give us tle now we have to do something clever than this what we can do is let's say the given array is one two three four five six so this is the given array okay now let's say we want to find for 3 let us say this is x and we want to search of y such that the summation is 2 raise to 2 over z and x is equal to 3 in this case now what we can do is we can go starting from 1 to so these are the power of 2s 1 2 4 8 16 and so on so we are going to go on each of these and as we know the limits are 2 raised to the power 20 so a number could at max be 2 raised to the power 20 and in the worst case if both the numbers are 2 raised to the power 20 so that is going to give us the summation as 2 raised to the power 21 as the summation so the summation of x plus y could at most be 2 raised to the power 21 so that's why we are going to go uh from z starting from 0 till 2 receive or 21 so we will be going on this 2 raised to the power 0 is 1 2 raised to the power 1 is 2 and so on till 2 raised to the power 21 so we will go on each of these numbers and we will find 2 raised to the power z minus x so this will be the y that we want so for each of these numbers we are going to take the difference with the current number x and we will search in the remaining array that the number of y is existing or not so let's say we are on the number 2. so two minus three it is minus one so we will see if minus one is there obviously minus one is not there because the i think it is only non-negative numbers which are only non-negative numbers which are only non-negative numbers which are present here then we will go to four and then we will see the difference is 4 minus 3 that is 1 so we will search if one is there or not then we will go to 8 and 8 minus 3 is 5 then we will search if 5 is there in the given area or not and this is how we can do this now in order to search we can what we can do is we can store them in a map and unordered map so that we can search the element y efficiently now let us discuss about the complexity of this solution so basically we are going to each of these numbers so it is big o of n to go on each of these numbers and then for each of these numbers we are finding y and to find y we have to go on each of these numbers that is 2 raised to the power z and there are 21 such numbers so it is 21 multiplied by n big o of 21 multiplied by n and then searching the number y in the numbers which are given to us it is constant because we are using an unordered map so this is the complexity and according to the constraints which are given to us it is 10 raised to the power 5 it is going to become big o of 10 2 into 10 raised to the power 6 and it should give us ac but during the contest i was getting tle let me show let me try it now we will do a slight optimization after this first let us just code this one so we have an unordered map of type int then we will store each of these elements now we have the accounts and now we are going to go on each of these elements one by one so this is our x and then we will start from i is equal to 0 i smaller than equal to 21 and i plus basically we have to find 2 raised to the power i so that we can do so that is let's say this is z is 2 raised to the power i so we can either use the power function or we can use the left shift operator that is one left shift by i this is 2 raised to the power i and the y that we want to search is z minus x now we will search if this y is there in the map so for that if uh also it might be possible that let's say we are searching for the number one and for two is the power z the y that we are going to get is one so both of them will be equal so we have to handle this case as well if y is equal to uh let's say x if they both are equal then we have to do answer plus equal to m of y minus 1 otherwise we have to do answer plus equal to m of y simple let's make an answer here and there's one more thing so after this so for this 3 as x and 8 as 2 raised to z the y we got is 5. now when we are coming to 5 for 5 as x and 2 raised to the power z is 8 the y that we are going to get is 3. so 3 comma 5 is a pair and it will be counted twice so every pair will be counted twice if we are going with this method i hope you understand so let me take another example let's say we are taking this 2 and 6 so let us take 2 as x and 8 as 2 raised to the power z now the y that we will be getting is 6 so 2 comma 6 is the pair now when we come to the number 6 and if we consider this as x and 2 raised to the power z as 8 then the number y that we will be getting is 2 so 2 comma 6 will be counted again so every pair will be considered 2 times so that is why we have to return answer divided by 2. let us try to run this also they want us to take the modulo so let us create a variable here mod 10 raised to the power 9 plus 7 and after each of this iteration i am going to take the mod so answer mod equal to mod let me try submitting this during the contest this solution was giving us dle and we are still getting the tle so this optimization that we can do here so let's say the numbers which are given to us there are they are not in order so let us first start these numbers which are given to us so in our example it's going to remain same 1 2 3 4 5 and 6 and so on so these are the numbers which are given to us now once we sort the array which is given to us what we can do is we can go to each of this number consider them as x as we did last time and now we will run the power of 2 starting from i is equal to 0 till the point when so 2 raised to the power i minus x will be equal to y now this y should not exceed the x so we have to go till that i so we just want to find a y which is within this range starting from the beginning and smaller than the current element we have to find y till that point and as soon as the y is exceeding the given x then we will break out of this loop so this will help us in counting the pair only once so we won't be counting the pairs twice as we did last time and this will save a bit of time although the complexity is going to remain same but it will save us some time so let me just start the given led now this is the y so if y is greater than d sorry x then break otherwise do this and we don't have to fill the map from the beginning so we want that whatever element we computed so whatever x we have seen we are going to insert that into the map and here we will return the answer so it is giving us -1 and okay so we have to remove this condition let us try to submit this now and it got accepted so this solution is also of the same complexity that is 10 raised to the power 6 and it is getting accepted because of this slight optimization that we did here and the space complexity is also big offend because we are storing all these elements into a map so this is it for the solution so if you want more such videos in the future do subscribe to the channel and press the bell icon so that you can get notifications thank you
Count Good Meals
find-valid-matrix-given-row-and-column-sums
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Array,Greedy,Matrix
Medium
1379
1,277
Hello Guys Welcome Back Door And This Video Will See Given A Matrix How To Decorate The Number Of War Sub Matrices With All Once Soldiers From List To Twenty One Of The Match Challenge So Let's Not Look At The Problem Statement Letters Udayveer Vriksha And Want To Count number of matrices with this app you can see the number subscribe 269 subscribe this is the only for the total number of subscribe values ​​which contained in this problem will give me number of subscribe values ​​which contained in this problem will give me number of subscribe values ​​which contained in this problem will give me a request to find the total subscribe and subscribe the loot vishal this problem they will Show you to be methoded in order to solve This is the first This Ruling Planets International Day of my video You can watch them back to solution of the subscribe this Video give a like And subscribe The Amazing will be the number one to subscribe will start from the Top 09 They Will Update Dec 09 Subscribe Model This Value Select Is The Answer Of This Two Values ​​Is Equal To The Government Values ​​Is Equal To The Government Values ​​Is Equal To The Government Research Is 2018 Total Number Of Elements 22222 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the subscribe and subscribe the Wind and use this is the roll one side this and subscribe to this Hussain Bhai M day you will have total number of into muscles and maximum size of the square which will be possible is minimum department embark on a regular matrix no later Say want to count all the coordinates and matrices in what will be the time complexity for the total time complexity will be and minus Plus one subscribe this regular matrix this point will absorb school this point to you can not at this point and will not be possible only to multiplication obscene noting the number of possible cells from where are square meter exercise constant and will have to multiply wealth x widows Sliding Window Veer Wedding The Problem Solved This Problem Will Be Equal To Subscribe Matrix Size [ __ ] For This Is Subscribe Matrix Size [ __ ] For This Is Subscribe Matrix Size [ __ ] For This Is The Time Complexity Of Only Single Size Or Matrix And Where Needed To Count All Subscribe To A Minimum Of So This To Multiply Minimum Of The Total Time Complexity. And you can also get you can improve the time you will get the latest jobs which they can make from which give only for creative table apne seconds back chakra dasam make deep to be vansh sexual tricks the sum of the subscribe The Channel Please subscribe and element 8000 subscribe this one important provide latest and values ​​and values ​​to solve provide latest and values ​​and values ​​to solve provide latest and values ​​and values ​​to solve previous side subscribe also will not give the google maps request oo for which is equal to with sexual tricks will be considering and account of number of sub square matrices idea having all once inside The Matrix Notice To Be To Matrix Is Given Will Be Considered Dasham Vyati Which Is Not To Subscribe Is Equal To Subscribe 44000 This Is Not To Be Considered As Given In The Total Time Complexity Not No Weather This Will Not Withdraw Weir Wedding Elements And No One can we do subscribe battery saver mode on it is in the same time e matrix What will be doing this will just determining whether this inter metric will get introduced into account and not burdened will not thinking about the two back to matrices and 151 size matrix This on soul can find all types of matrices and looted account in the same time solar system and observation that gives node this point to that is the bottom right corner subscribe valve what will be the number subscribe not understanding in this video you will get 300 is The Point subscribe this Video subscribe kare 010 Can Never Be Included in a Square Matrix Having All Vansh Vo If You Are Serious Role Simple C Phone Operator Say for This Vway John Indian Point Pending Point Miss Bottom Right Corner Soi Dushmani Bottom Right Corner of Square Sub Matrix And inter metric ton subscribe and want to know what is the number of york this point is the only subscribe did not understand the example of values ​​will be given m id point subscribe to this feed medicine how many sub matrices of this inter metric morning content and This one will form the bottom right corner Observatories Saudi Arabia to Sach Matrix Answer metric shelf and distic 0 matrix this is for the bottom right corner and elements of enlightened souls will help you did not understand more examples for later don't forget to subscribe this channel Subscribe To Be More Than Size Which Will Only Be Used Only Government Responsible For This Point The Quite Well Because They Can Not Extend The Size Of The Matrix Is The Given Cell Is The Bottom Right Corner Office Peon Trick 0530 Element Now Benefits 300 Will Always Be Vidron Simply Copy Element Calculations From This Point Roll Number One Know This Point What Will Be The Number Subscribe Bottom Right Corner Subscribe Must Subscribe Now To 9 0 Tree Where They Have All One So Will Simply Footwear 0910 Login To The First Column Tweeting and Chief Size Greater Than One Sources 10111 Subscribe One Know When You See This Element The Video then subscribe to the Page if you liked The Video then subscribe to the Will Only Live 120 Not Only Will Be Able To Understand How To Calculate the Number Subscribe to The Question Which Problem to Your Mind If They Are to Give One Position Latest to This One How to Determine How Many Square Sub Matrices There Will Be Vinod Is Particular Elements The Bottom Right Corner Do We Need to Travels from the Beginning To 10 element and this round sea process is there any optimize process for finding this so latest love scene in devotion for optimal process letters were given a square matrix subscribe every where they have all once 100 according to the previous explanation left all these values ​​end attractive in left all these values ​​end attractive in left all these values ​​end attractive in particular value azeem that this is the number of was amazed with the giver celebs the bottom right corner software writing a to this elements bottom right corner subscribe Video subscribe 991 here this to is dark two square meters which is having this elements bottom right corner To Change Something And Use This Subscribe Element Bottom Right Corner Subscribe Not Different Sizes And Will Be Used 2ND Year Subscribe And 151 Others And Know To All So Much Didn't Understand This Point Quite Vikas This Is Not Very Important Soldiers In The Two Countries Value Secretary Vinod Dard Subscribe Button Ko Na 2424 Uddin Dhoy Conclusion Please Subscribe This 181 Here You Can See This To The Guardian Year Will Simply Minimum Of Elements With New Updates Reviews And This Point Plus Minimum of element latest from this point Subscribe Meeting of the squares of matrices which is lending and deposit is the bottom right corner is this is the singer same thing and singer something is the bottom right corner for peon this is the same with different shade at this Point Not Exactly At This Point But Its Corresponding Point In The Law The Guardian 2012 Which Exam Point Subscribe Serving This Point When Skin This Point Is Equal To Two To This Point When Skin This Point To Point Is Equal To Reel I came to Jaipur Already written the volume two and three OK so what will be selected value for this point again one with new value how to find and just one time so you can dare to care services and this point to subscribe LutaOne Hair New Subscribe Minimum of elements which Can be seen from this example subscribe and subscribe the Channel and subscribe the subscribe matrix that and we use to the previous property in order to find a grievance cell how many square time treasure and in gift for each and every cell the number of matrices having all Way to sum of the squares and isse singh this is the best all subscribe vol welcome to the number subscribe 270 this point jab skin knowledge se vibar ko subscribe now to receive and different style a point but with fear ending at different points in Obviously that is now metro is different Sufi can just take a parameter desert in points parameters and count the number of matrices and in a different cells in this will give the account of units of matrices OK in the morning that your daughter's wedding dish values ​​in order to count The Number Of dish values ​​in order to count The Number Of dish values ​​in order to count The Number Of Medicine 90 Latest By Using This Will Give You Already Know What Was The First And For This Point Subscribe Veer Website Will Have Element To The Top And Left In The Air Force Which Can Extend The Size of Square Beyond One So When They See No One Will Have to Processes Have Already Explained You in Order to Feel and Particular Sale Will Have to See the Minimum of These Reviews and Will Do a 100 Don't Wash Dresses 4 Digits Only One Subscribe 19 Similar For This Point To Minimum Values ​​And 2nd December Minimum Values ​​And 2nd December Minimum Values ​​And 2nd December Display Subscribe Now Similarly For This Point Will Be Amazed With Simran Serve With This 2009 Subscribe 0 SisOne Date For This Is Vivek Volume Minimum Of This Three Plus One Which Will Be Equal To One Not To Find The Contact Number Of Matrices Visit Have To 8 This Value Sachiv One Stree 4600 Number Of Matrices Having All One Side It Is Equal To Tanning This Is The Time Complexities And Of And To M And Space Complexities SMS And Of Into Him For This Express Which way request you feel this table no basis of dynamic programming solution so let's not look at the code not win this code you can see but where giver metrics and have found the number of rows number of columns norvekar dip table and the will take account Available which will be quite till 2018 net of the number of war matters with all once known will be the first floor and the first column and where feeling processions update the value of baroda first prove this application developed by wedding value se effective andher will be only One Squares of Matrix Available Deposit Cannot Be Extended Because of Rates on Top Element and Symbols for the First Column0 Will Simply Yadav This Note for the Will Have to Do It Is the Value of Wave Liquid Current Element Can Get Rid of Top 100 Feet from Will Have To Do The Value Of Doing So Will Be The Number Subscribe Button Solution Different Languages ​​And Everyone Can Different Languages ​​And Everyone Can Different Languages ​​And Everyone Can Benefit From Like Share and Subscribe
Count Square Submatrices with All Ones
largest-multiple-of-three
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3. Total number of squares = 10 + 4 + 1 = **15**. **Example 2:** **Input:** matrix = \[ \[1,0,1\], \[1,1,0\], \[1,1,0\] \] **Output:** 7 **Explanation:** There are **6** squares of side 1. There is **1** square of side 2. Total number of squares = 6 + 1 = **7**. **Constraints:** * `1 <= arr.length <= 300` * `1 <= arr[0].length <= 300` * `0 <= arr[i][j] <= 1`
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Array,Dynamic Programming,Greedy
Hard
null
76
hey everyone welcome back and let's write some more neat code today so today let's solve minimum window substring we're given two strings s and t and we want to return the minimum window in the string s which contains every single character present in string t and it's possible that might not even exist in which case we can return an empty string so in this case our string s is this big long string and our string t is this a b and c so we just need we don't need to find a b c in here we just need to find a substring of s that contains all these characters and we want to find the minimum string that contains all these characters so one possible string is this right it has a d o b e c so it has a b and c but there happens to be a shorter string that has all of those as well this string b a and c so they are out of order so b a c and there's an n in there as well but this happens to be the shortest one it's length four and so that's the result that we're going to output so what's even a brute force way to solve this so we're given s and t right and we want like if we're checking a substring right like this substring maybe this is our solution right how do we even determine that well let's use some hash maps so these two are our hash maps you can see i have one for t what does this hash map represent well you look at t right because for each of these substrings we just want to make sure that it has at least one a right one a has at least one b and it has at least one c because that's what we have over here we just want to make sure that we find the minimum substring in s that satisfies this condition so for every possible window that we check in s like maybe we check this window we are gonna want to have a hash map for the window and we're gonna count how many a's do we have initially we're gonna start with zero right because initially our window is gonna be just empty or whatever we're gonna start with zero b's and zero c's but for this current window you can see we have one a one b and one c right so we have one a one b and one c so as we compare right we compare how many a's do we have versus how many do we need right this is how many we need and this is how many we have in our current window you can see we need one and we have one right so the relationship we're looking for is greater than or equal right we want the counts all to be greater than or equal but one thing you can see is brute forcing is gonna be difficult right so let's say we initially start with this window right we see we just added an a so what are we gonna do we're gonna update this now let's just check is our window valid well we have at least one a and so remembering that this is how many we have in our current window and this is how many we need to satisfy the condition so initially let's start with this window just one a so then we can update our count for this window right add a single a so now my question is have we satisfied the condition do we have everything we need well how are we going to check that well we have to check all of these right so is the have count greater than or equal to the need yes it is what about this is the beat count uh greater than or equal to how many we need the answer is no right so therefore we don't have how many we need so therefore we have to actually expand our window right we have to add another character this d right but that's not actually going to update our window because we don't need any characters other than a b or c so we don't really care about the d the same thing is true for the o but now we have a b right that's good because we do need a b so we add a b so now we're gonna have to run the same operation do we have everything that we need so we're gonna be doing some repeated work do you notice this repeated work we're doing we have to check if we have enough a's which we know we do because we already checked that when we first added this element so we notice we do have enough a's do we have enough b's well this time we actually do because we just added a new b right that's the most recent character we added great so we know we have enough b's do we have enough c's we do not have any c's in our string the count is zero therefore this condition is not met so we do not have our result yet we have an a and we have a b but we need to add more so now we're gonna add an e which we don't really care about we're gonna add a c so finally we have so finally we can see that we met our condition right but we with our current algorithm our brute force way we have to repeatedly check every one of these even if we already know the count is met so this is basically where our repeated work this is what i'm going to show you how to eliminate but as you can see we have enough a's we have enough b's we have enough c's so therefore this is a possible result it might not be the minimum but it's a possible result and what's the length of this it is 6. so we can say for now that our result is length 6 and it goes from index 0 all the way to index five so i'll put zero five that's our current result so one thing we noticed is we're having to do a lot of repeated work to check that we have everything that we need we have to check every single one of these characters right but we don't we know we don't always have to do that so let me show you how to do it without repeating all of that work we're going to start out the same way so we're going to add an a right that's our first character so now we're going to check so now what we're going to say is a count is 1 right so now my question is do we have to check every single one of the halves because initially we know that none of the conditions have been met right initially we start with all zeros we also know that the number of characters that we need is gonna be three right meaning we need to satisfy the count condition for three unique characters right and we know that we start out with a have value of zero because we know for each of those three characters we have met the condition for none of them right initially we met the condition for none of them because we start out with all zeros but now you can see we just added an a so let's check just for this one character have we met the condition is the count greater than or equal than one yes it is we have one and we only needed one so we met the condition so what does that mean we can take our have value and update it so initially it was zero now we can change it to one so now we have one but my question now is have we met the condition well we need three but we only have one so we haven't met the condition you can see what i'm doing here right before we needed to check the condition for all three of these each time now we only have to check the condition for one we have one value that tells us how many we need so before we were we had to continue running an operation of length t which is in this case 3 but who knows it could have been bigger t could have been 10 it could have been 100 it could have been anything and we would be bounded by that but in this case we only have to do one operation for comparing these integers and one operation for comparing the integers of the character that we just added so for each character that we add we only have to do an o of one operation so now let's add another character let's add the d we know that doesn't really do anything we add the o that doesn't do anything we add a b this is good so how am i going to do things differently this time well like usual i'm going to change this one this zero to a one we know we have one b so now i'm going to check has this condition been met or is it equal i know last time i showed you greater than or equal but really what we're looking for is are they exactly equal because that's when we know the condition has been met so if these are exactly equal which they are in this case one equals one so what that means is we can increment our have value by one before it was one now we're going to actually change it to two and now let's check are these equal now have we me do we have what we need it's not because two is less than three so we haven't met the condition yet so we have to continue but notice how that was an o of one operation we just had to make one comparison here and then one comparison here we didn't have to go through the entire list so now we're gonna add an e which we don't really care about now we're going to add a c which we do care about so let's update the length of this now are these exactly equal we know we just met the condition for these last two now have we finally met our last condition and yes they're both one so we can take this through this two and replace it's getting a little messy but i hope you can see it so we have a three here so now let's make the comparison between these two and yes they are exactly equal so what that tells us is this string contains we have exactly what we need right so we met the condition this is a possible result and i'm just going to take the two indices the start and the ending of it which is 0 and 5 and i'm going to put that as our current result so our current result is from 0 to 5. and the length of that result happens to be six right so now what are we gonna do are we just gonna keep adding elements again and again well we wanna find the minimum so let's at least try to find a string that's less than six so what are we gonna do let's remove the leftmost character and keep doing that until this condition is no longer valid until we don't have what we need anymore so we can try to at least find a smaller result because ultimately we're looking for the minimum string so i'm going to take this character and remove it from our current window and so we're removing an a so what that means is we have to update this so it's no longer one we actually have a zero for count a now and now we know that this condition is this is less than what we need it to be so this condition is no longer valid so that also means we have to update this value so before we had a three but now we have to put a two we only have two of these conditions matt write these two characters b and c so now we're actually just going to keep adding characters we're going to keep looking for the minimum so we add an o but we know we don't care about that we add a d we don't really care about that we add an e we don't care about that we add a b over here right we do care about b so what are we gonna do we're gonna take the b count it's one currently now we have two now that's great because we actually have more than what we need right we need one but we have two so am i gonna take this and update it no because they're not equal what that means is we added an unnecessary character it's okay but it didn't help satisfy the condition we already know this and this were satisfied this is the one that needed to be satisfied so since it's not exactly equal we're not going to increment our have count so now let's add another character the a that we wanted so badly so we added an a we update the count of a we add one so now this is one we're gonna check are they exactly equal have we met the condition now by adding a character did we make these exactly equal and we did so what does that mean well we met one more condition so we update our have count it's now going to be set to three and now these are actually equal so we actually met the we have exactly what we need so we potentially found a result now the only problem is this result goes from index 1 all the way to roughly index 10 so it's actually bigger than our current result which is a problem so we don't update our result yet but now we want to try to find an even smaller substring than this so let's start popping characters from the left so we pop a d but d's we don't care about so we don't update our window and let's just keep popping values until this condition is no longer met so now let's pop a b so let's now we have to update our value of b so this was originally two now it's going to be set to one so now it's set to one so did we or did we undo this condition is this condition no longer valid nope because this is still greater than or equal to the count that we needed so the condition is still valid we don't have to update our have count yet so actually this string is still a possible result but notice this string goes from index 4 all the way to index 10 so it's actually length 7 and that's still greater than this string so we cannot count this as a result yet so now we remove the e and then we remove the c so we have to actually update our count again so this was originally one now it's going to be zero and now you can see that this condition is actually no longer valid so even though these two are still valid this one is not valid we have to update our have count so our have count was three but now we removed one so it's going to be two so now it's no longer equal so our string is no longer valid it's length five but it doesn't have a c we have a b we have an a but we don't have a c so we can't update our result so let's keep adding characters now maybe we'll find another valid string so we add an n but we don't care about ends we add the c that we want so we added a c so we update our c count now it's set to one these are once again equal so since they're exactly equal that means we just now have met the condition so we met one more condition so we can update our have count now to three that means it's exactly equal to what it needs to be that means this is a valid string so this goes from index 6 all the way to index 12 that's a length of 7 which is not smaller than our current result but that doesn't mean we can't shrink this right so let's start from the left and keep popping and making it smaller but also keep going until it's no longer valid anymore so we pop in oh let's remove a d but we're still valid right we didn't update any of these and now you see we have a string of length five so we can actually update our result so now we're going from index 8 to index 12 and that leaves us with a length of 5 but we're not done yet we have an e we can remove that e as well now you notice we're still valid we have a b we have an a and we have a c we didn't have to update our map our have count is exactly equal to the need so now we can update our result one more time and it's gonna go from index nine all the way to index twelve that's the string the length of it is four and lastly we are going to remove this b character from it as well and once we remove the b you can see okay we removed this one now we have zero b's remaining uh that's less than how many we need so we have to update the have count so we set it to 2 the condition is no longer valid and so are we going to continue our algorithm well we have no more characters left to add we reach the end of the string so since this is our current minimum and our current result this is what we're going to end up returning and by the way we just solved this problem in big o of n time because you see we added each character once that's an o of one we removed each character once every time we added or removed a character we did at most two operations right we had to update one spot in our map and we had to potentially update this right okay so now let's finally get into the code the first thing i'm going to do is actually handle a edge case so if the input string t which is you know our string is like the substring that we're looking for if it's empty then what i'm going to do is return an empty string because that's just how they want us to handle it in this problem and i'm going to have two windows that i showed previously so count of t and just the current window that we have they're both initially going to be hash maps they're both initially going to be empty and the first thing i want to do is initialize our count t map because we know this map actually isn't going to change at all so for every character in string t i'm going to add one to it but the value i'm going to get i can't just do this because it's possible that c hasn't even been added to count t yet so i'm going to do some python stuff i'm going to use the function get which is good for this so i'm going to get c i'm going to get the count of c so if c exists in our map it will give me the value that's stored in here if it doesn't exist i can put a default value which is going gonna be zero so if it doesn't exist this function will return zero so that's just a way that i like to handle this case so now that we've initialized the count of t we can have our variables have and need so we know have initially is going to be zero because we have zero of the characters we need and need is going to be initialized to the length of count t because that length of count t gives us the unique characters in the string t and then i'm just going to start iterating through every character in s so i'm going to use a right pointer for that the r is going to tell us the right boundary of our current window so i'm going to get the character that we just reached which is s at index r so i'm just going to put it in a variable c so with c we know we can update our current window so i'm going to do window of c and add one to it for the character that we just reached and here i'm basically doing what i did above if c has never been added to window we're just gonna return zero with this function so 1 plus 0 we'll put a 1 here if it does already exist this function will get us the count that was stored in here so we're updating our window we're adding the count to it now we want to know does this count completely satisfy what we were looking for does window of c equal exactly count of t that means we just satisfied a condition for the first time but one thing i also want to check before i check this is that c is even a character in count d count t so if c is in count t and this is true because we know we don't actually care about the characters that aren't even in the string t to begin with and we know if this is true we can update our have count so we can increment it by one this means we just satisfied a condition so now what we want to know does have equal need exactly so are they actually equal if that's true i'm going to run a loop and i'm going to show you why it needs to be a loop so we actually met the condition let's one update our result potentially right so if we found a new minimum result let's update so this actually reminds me that i didn't even set a result so let's set our result and our result length so initially we know our result is going to be a pointer like a left and right pointer so i'm just going to give it a default value of negative 1. and for the result length i'm going to put float infinity because that's a good default value in this case because we are looking for the minimum string so any value will obviously be less than infinity and i'm also going to initialize a left pointer because we know r tells us the right pointer left pointer will initially be set to zero but so now we can actually update our result we know the condition has been met so if the current length of our string which is going to be r minus left plus 1 this is how you just calculate the size of our current window if it happens to be less than the current result length which initially starts at infinity so this will definitely execute at least once if this is true we can update our result which is stored over here so we can set our result to left and right this is the window and we can set our result length equal to the size of this window which we just computed above but let's compute it again this is the size of the window and just like i showed you in the drawing while the condition is met we want to keep shrinking from the left we want to make this string as small as it can possibly be so let's pop from the left of our window right let's try to minimize it so i'm going to remove the leftmost character from our window map so the leftmost character is the string at index left right and from this i'm going to decrement it by 1. so now since we removed a character it's possible that our have and need condition is no longer met so i'm going to do something similar to what we did up here i'm going to check if this character s of l was in count t meaning it's one of the characters that we need to satisfy our condition and if somehow right now for the first time that we took this character from our window and now the count is actually less than the count that we need which is present in count t so now if it's if the if by removing a character we just made it less than what it needed to be what we did is we just took our halve and then decremented it by one right so this is just a part of removing a character from the left we update our map we update our have count if we need to and lastly we take our left pointer and increment it by one because of course we have to shift this by one if we're removing a character from the left of our window so now after we do this we're going to potentially check the have and need condition and it might be true it might not be true and whatever it is the loop is going to execute when it needs to so this is all we're doing we're taking characters adding it to our window map checking if the condition has been met updating the window accordingly that's all we need to do by the end the result if it exists will be stored in our result variable so our result pointer we can put it in uh left and right we can take result and extract it into left and right these pointers in this case these new left and rights will tell us the result so what we can do is say return from string s going from pointer left all the way to pointer right but we need to add one for the off by one error and we're only gonna do this if the result length has not has been changed meaning it's no longer infinity because we know it's actually possible that a result does not even exist if that's not true if a result doesn't exist we know we have to return an empty string so there it is this is the entire code i'll probably have to link this in the description because it's pretty long and even kind of messy and you can see it is definitely very efficient this is a linear time algorithm so i really hope that this was helpful if it was please like and subscribe it supports the channel a lot and hopefully i'll see you pretty soon
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
1,815
hello everyone let's take a look at this liquid problem it's the last problem in the bi-weekly it's the last problem in the bi-weekly it's the last problem in the bi-weekly context and it's a hard problem although it's a hard problem but after we analyze this problem it may be not that hard okay let's take a look at it if you haven't used the problem you can take some time to read it we can just start with example one in example one base size is three which means we will mix three and donuts every time so this is the best answer after a rearrangement so at first there's a group of six people somewhere can make two batches each is three so the six people can consume those donuts and there's no remaining donut next this group of two people though they can have the fresh donut then there is one donor remain next we have group of four since there's one donor remains so this group cannot eat the fresh donut the first people will eat the remainder then we make another batch the remaining three people have sweep donut next there's a group of five people they all can have fresh donut then there's one remain next says group of one six people just eats the remainder at last we have a group of three those people can have fresh donut okay then we find that it's always a good idea to put uh like a number that can mode batch size is zero for example uh six people they can eat all the donuts and there's no remain so it's always a good idea to put the numbers set mostly zero like at front also it's also a good idea to like to put like a two group of people such there's some more batch sizes zero together for example two and four two plus four is six more batch size is zero five plus one is six small batch size is zero it's always a good idea to put either a single num number system mode batch size is zero to front and it's always a good idea to per two group people that's yes some is uh like most batch size is zero like to the front so and this is also a tricky idea here is that for example uh batch size is four like five one four is one nine more four is one thirty move for it is one it's the same effect to have a group of five people nine people certain people one people since the mode is always one so that we can have code like this if the group of people mode batch size is 0 we can just increase our results otherwise we can pick a like two group of people that's their sum is uh like uh mode exercises zero like here uh for this group of people with more batch size we get if cons batch size minus g is greater than zero we can just use that for example one and three two and a two then we can increment our user by one and the consumes batch size minus g otherwise we just increment const g so after this initial process we know batch test 4 and this is our initial groups after the process count is zeros two zero resulted three now okay so now we have cons so we need to further process accounts seconds meaning like how many groups and likes their people like most batch size is one so zero for one we have two groups four two we have cell group for three we have zero groups next we need to process the cons to get our final answer so counter result is our partial answer we also need to process these cons for processing the cons we need to back checking since we don't know like uh there are so many groups in this count we don't know uh x if we should group like three such group together four such group together we cannot use credit approach here so we need to back respect checking to process it so each time we just follow from on one two like the size like uh we every time we can use it or not so we have so many choices we need to try all possible combinations so every time we if cons i is greater than zero we will try to use this group so uh if country mean is zero we will initialize time to one otherwise is zero since if counts remain is zero and we use this group must have be happy group since there is no remain now we use this group so cosine minus then we dfs recursively process it and don't forget to restart the state since we decrease the tanks i will increase it again so in this dff function we pass cons and we need to update remain here since this group the i group and they will eat some donuts so we will updates remain here okay at last we just update our results finally which just returns this results this function mean for count counts like given countries remain and how many happy groups are there okay it works but it's a little bit slow since there are many duplicated sub problems for example if this is our count like at first we will pick a group that has one people then we pick a group that has two people then cons becomes zero two 1 or we can first pick a group that has two peoples and pick up groups that only has one people count is still 0 2 1 0 so many duplicated sub problems but those sub problems they have same state for example constant sim so we can just construct a key from this count we can there many ways for example we can construct a key like this for a group of one people we have two for a group of two people we have one for group of three people we have one so this is our key function we just generate keys from our accounts we just follow from one to last since there is no meaning to start from zero since it's always zero so we will just general key like this okay then we add a cache to our backtracking function we have a cache it's a hash map it's a key string the value is an integer okay so we first generate key and if the key is already in our cache we just return the answer otherwise we use calculation for our current state and update our cache okay that's our final answer and you can pass the test cases okay so there's just two main components here the first one is the pre-process we know the first one is the pre-process we know the first one is the pre-process we know and says the value of each group can be very large like 1 million but there's no meaning to be that large since batch size is only at most nine and we know if batch size is four then uh like one five nine thirteen they all have same effect so say we don't need a large number we can just mode batch size and we just really like if g is zero we can just increase increment our result if there are two groups that their sum is uh like mode batch size is zero we can also just consume them first and increment our answer then after this preprocessing we have the cons vector and we need to use backtracking to process this cons vector to get the results okay see you next time
Maximum Number of Groups Getting Fresh Donuts
checking-existence-of-edge-length-limited-paths
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return _the **maximum** possible number of happy groups after rearranging the groups._ **Example 1:** **Input:** batchSize = 3, groups = \[1,2,3,4,5,6\] **Output:** 4 **Explanation:** You can arrange the groups as \[6,2,4,5,1,3\]. Then the 1st, 2nd, 4th, and 6th groups will be happy. **Example 2:** **Input:** batchSize = 4, groups = \[1,3,2,5,2,2,1,6\] **Output:** 4 **Constraints:** * `1 <= batchSize <= 9` * `1 <= groups.length <= 30` * `1 <= groups[i] <= 109`
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Array,Union Find,Graph,Sorting
Hard
1865
478
hi today i'm talking about leak code problem 478 generating random point in a circle what this problem asks you to do is write a solution object such that the constructor or initialization method takes a radius an x and y center point and the solution object should provide this function rand point which when called will return a random point within the circle described by the radius and x and y center coordinates in other words if we have an x and y center coordinate and a radius of r we can imagine that radius draws out a circle around x and y and rand point should return for us a uniformly distributed random point within this circle so uniformly distributed just means that any point within this circle or on its circumference is as likely as any other point within this circle so you may think that a possible way to do it is just to imagine the circle as a little spinner and so you could just imagine spinning a little spinner along here and letting it land wherever it may lie and then picking a point along the length of the spinner so you could just pick a random angle for the spinner to spin too and then you could just pick a random distance along that angle and draw a point there but one problem with that is that the points would be more sparse the further out you go so if the points are equally likely to land at any point along this spinner or along the radius then the points are going to be pretty spread out towards the edge of the circle and they'll be very tightly packed together in towards the center of the circle in other words it won't be uniformly distributed which is one of the requirements so there is a mathematical or analytic solution for this problem but when i was thinking about it i wasn't able to come up with what the analytics solution is after i submitted the problem i read the discussion section and saw that other people did have the mathematical analytic excuse me solution but i wasn't able to come up with it by thinking about it instead what i came up with is an alternate approach where i took the radius sorry the center point and the radius and i imagine that instead of describing a circle i just asked myself what about a square that kind of bounds the circle that i need to be returning a random point within so if i'd drawn that better you would have seen that the square is just bigger than the circle but the circle is contained within it so i asked myself how could i get the square for this circle and yeah i'll just explain briefly how i did that so i considered this square would be between the zero point of the square or the square's origin and the end point of the square and to get to the zero point from the center you just go up one radius and then left one radius so like add a radius to y subtract radius from x and you're at the zero point and then to go from the zero point to the end it's just plus two radiuses to x and minus two radiuses to y um and then we have our like the bounding box for this circle a box that goes all the way around it and so then i just want to pick a random point within my square and some of those random points will be inside of the circle and some of them will be outside of the circle but if i pick just random numbers like a random x between the zero point and end x and a random y between the zero y the zero point for y and the end point for y i'll have a uniformly distributed point the only problem is that maybe it's within the circle and maybe it's not so how we tell if a point is within the circle or not is if the distance between a random point is greater than the radius then we know it's outside of the circle and if it's less than the radius we know it's within the circle less than or equal to the radius so you can calculate the distance between two points in a cartesian plane using this formula which is x2 less x1 squared plus y2 less y1 squared and that whole quantity raised to the half power or another way of saying that would be the square root of that whole quantity so that will just tell you the distance between two points so if the distance between those two points is less than or equal to the radius it's within the circle if the distance between the two points is greater than the radius it's outside of the circle so ultimately the oh i guess this is the square point function it's pretty straightforward it's just a random a uniformly random point starting at the x zero point ending at the x end to give me my random x coordinate same thing for the random y coordinate and the ultimate function which will solve this problem is the rand point function and what it does is it starts with a random square point so remember that this square point may be within or outside of my circle and it's just going to say while the point distance between my random square point and the center point of the circle is greater than the radius pick a new random square point so this may require any number of random square points but in practice it picks a circle point pretty quickly as you can see the circle is most of the area inside of the square so it won't take us that long to find a random one inside of the circle yep so that's pretty much it for the solution as i mentioned there's a mathematical or analytic solution and that as you might expect is much faster than having to pick random points until you get one that happens to be within the circle but i think i was at least pleased that i was able to solve this problem in code even though i wasn't able to solve it by mathematically analyzing it and i guess to be honest i wonder how many of the people who were able to solve it solved it by kind of googling for that question which you know that's fair however you want to usually code um but i like to think of myself as having done a pretty good job in that i found my own solution without having to google for what it was um who knows maybe other people were able to find the mathematical solution easier shouldn't disparage them anyway i intend to uh to try to get a leak code problem a day or something like that cadence and as soon as i finish a leak good problem i just want to record myself explaining um what it was and how i solved it and then share that on youtube so if that's the kind of thing you're interested in let me know click the like button subscribe to the channel say something in the comments anything's appreciated thank you very much
Generate Random Point in a Circle
generate-random-point-in-a-circle
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`. * `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`. **Example 1:** **Input** \[ "Solution ", "randPoint ", "randPoint ", "randPoint "\] \[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\] **Output** \[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\] **Explanation** Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return \[-0.02493, -0.38077\] solution.randPoint(); // return \[0.82314, 0.38945\] solution.randPoint(); // return \[0.36572, 0.17248\] **Constraints:** * `0 < radius <= 108` * `-107 <= x_center, y_center <= 107` * At most `3 * 104` calls will be made to `randPoint`.
null
null
Medium
null
386
uh let's go through the liquor 386 lexical graphical numbers and this question uh it gives us an integer and let's return the lexical graphical order um from one two and for example to give an a equals 13. so the one is the smallest and one zero that is from lexicographical order that is the second one because it started as a one right and then one and one two one Street then uh two is greater than one so just test those kind of orders so intuitively we're thinking about the password we convert um those numbers to string and um the installed by screen and then cover the back but uh for this kind of range maybe it will pass the um maybe your past maybe with a tomato out of time so because third Toyota have a blogger and 10 complexity uh so for this question we need to have some other um Solutions so let's jump to observe the those kind of uh um is that numbers for example we what we want to um we went to uh to have the result is that for example we have Android that will be one to three four five six seven eight nine and if we have 10 right so we can put the 10 as the ones chart and also uh it have a chapter 11 12. in the Intel 19 and after the one zero there one zero it has each other uh 100 and um 100 in the one and uh until 11 we have a chart like a 110 to 100 19 right so uh if we um compose for example like a tree right and we can also have a CRS root but for this one because there is not included so we can have like a Chase so we are below um that kind of rules trying to find what we want to get a result is that and this will be lexical uh smallest and this is a second and this is a search and uh let's take an example for example this setting right for example we want to have um smaller than 109 okay so let's see um well it's a while um we go like this way and then like this way and this way um then it should go back to one zero go to 111 right and then we trying to go to each child again find this uh greater than one zero so we um just uh trim this kind of trees then uh go back and trying to go to the charts and go back so uh and here we have to one 19 right so if we travel like this kind of order we'll find out um the result it will be something like a 1 110 100 in the 101 and this is what we want actually on those kind of order is just a trees uh um pre-order traversal right so we can just pre-order traversal right so we can just pre-order traversal right so we can just use a trees the pre-order travel so to use a trees the pre-order travel so to use a trees the pre-order travel so to um do these kind of questions so right we can write a uh so let's uh write a couple days for this uh for this kind of uh solution because every number we just Traverse one time so it will be over in time complexity so we say that zero is not included so we are going to have um let's have this so I will restart first foreign each number uh we're going to have the pre-order shop also so that is a DFS pre-order shop also so that is a DFS pre-order shop also so that is a DFS we are going to have a um have a integer I um and also where we have those kind of results and I will just repeat this out right and I'm gonna go into this tree that the those kind of um parents to the charts right for example this is uh I and it's a child of Ip I uh multiple by zero plus zero until I multiply by 10 uh multiple by 10 plus 0 to I multiply by 10 plus 9 right there are 10 combinations um so um let's write the customer function private uh y with DFS we are going to have and into the current number right and also this uh integer as a result the accident condition for these DFS is that um if it's currently already greetings in um we need to have a record Tuesday and our limit on paint uh okay if this is already greater and then we just returned and uh we know this is a pre-order so we and uh we know this is a pre-order so we and uh we know this is a pre-order so we need to have the results and this kind of trust and then for then we iterate these numbers chart that is valued uh I equals zero now there should be included because uh but it's a child it's just a house for example this is one right uh one zero uh one two one night right so um so we have I equals zero I so I'm going to equal to 9 I plus you know we're going to have DFS and multiply by 10 plus I and restart uh so this will be the solution thirteen two um sorry this is so this will be the oh and time complexity
Lexicographical Numbers
lexicographical-numbers
Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order. You must write an algorithm that runs in `O(n)` time and uses `O(1)` extra space. **Example 1:** **Input:** n = 13 **Output:** \[1,10,11,12,13,2,3,4,5,6,7,8,9\] **Example 2:** **Input:** n = 2 **Output:** \[1,2\] **Constraints:** * `1 <= n <= 5 * 104`
null
Depth-First Search,Trie
Medium
null
1,760
So in this problem, basically I will do a dry run to show whether it is possible or not, which means the explanation of the thing I am doing a dry run, I have already given the background in the first video, so the next video will basically take a small example. So what you can see in this is given which means by breaking it we have to find out the minimum highest number. This array has to be made in such a way that we have to find out the minimum highest number and the permitted number of operations that we have is the maximum number. So let's see. We L, this will be our So if we don't do anything, then this will be the maximum, so Aa means 17, that is, the possible answer. Okay, so the matter is R is possible. LA means L, we take it from one, which means it is the most optimistic, so we take it as the middle. Mid in this case what will be our na like 1 p 17 pat e na mid nikala then nine let's see whether it is possible in naan or not basically what will we do by going to every place s this sapo one go to every place we will x mive by which we have mid Decided, if they do, then in this case there is Nan. In this case, Nan is actually there should be mid here. Okay, that's what we will do. Okay, so when there is nine, there will be zero at this place. When there is nine, there will be one at this place. So definitely if we both If we add then how much time will it take to spread the total. It should be one and that is within this range right so this is definitely possible so this is not a possible solution so when we find a possible solution what do we are Let's shift R there. Okay, sorry. If we shift R there, then whatever R is now, whatever R is, will not remain here. R will become R and will go to Na. Okay, right now Elv is still there, R has gone to Na. Because this is a possible answer, now we will find a new solution, if the new solution is five then it is five, then in this case one comes as the answer and in this case, whatever is there, then by doing right so plus then this four will come which is not possible. If it does not satisfy then it cannot be five and when it cannot be then what do we do, mid to L, which cannot be, if mid is taken out, if it cannot be, then we do plus to it, then A, which is now shifted, is now six. But if it goes away, it becomes new aller, then we will take out a new maid, which will obviously come from our rat, it came from t, so when it is on sen, then we got zero in it and in this case, we got two, then after adding, satisfy this. So, less than this is equal to two, so satisfying right, so seven is a correct answer. When it is the correct answer, then we shift a to that. What did we do to a, we shifted r to 67. Okay, this is what we did. Okay, now we will take out the mid, our six will come out and let's see what happens at six. At six, here comes one and here comes right so basically 1 p.s. also comes th on addition which is p.s. also comes th on addition which is p.s. also comes th on addition which is satisfied. If it does not do SETISFI, then what we will do basic will also do it, you will do the stool, you will do the basic erased from you will do the answer in the answer, which is the minimum thing in which we have two operations by dividing it. That sen is fine, that means within two operations, that sen is the same, we cannot do less than that, okay, the thing is, so how will we do that, I mean, what will we do to consume this, what can we do, we can do two operations, one In operation we got this state. In the second operation we got this state. So in this operation we can get convert this into n are in which the maximum number is from so see from this dry run you can see how our The code that works when a e aa happens then we will remove the answer this is the code and if you have seen the first part and now the second part I think you have completely understood how to solve this problem okay I will See in the next video thank you
Minimum Limit of Balls in a Bag
check-array-formation-through-concatenation
You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`. You can perform the following operation at most `maxOperations` times: * Take any bag of balls and divide it into two new bags with a **positive** number of balls. * For example, a bag of `5` balls can become two new bags of `1` and `4` balls, or two new bags of `2` and `3` balls. Your penalty is the **maximum** number of balls in a bag. You want to **minimize** your penalty after the operations. Return _the minimum possible penalty after performing the operations_. **Example 1:** **Input:** nums = \[9\], maxOperations = 2 **Output:** 3 **Explanation:** - Divide the bag with 9 balls into two bags of sizes 6 and 3. \[**9**\] -> \[6,3\]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. \[**6**,3\] -> \[3,3,3\]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. **Example 2:** **Input:** nums = \[2,4,8,2\], maxOperations = 4 **Output:** 2 **Explanation:** - Divide the bag with 8 balls into two bags of sizes 4 and 4. \[2,4,**8**,2\] -> \[2,4,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,**4**,4,4,2\] -> \[2,2,2,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,**4**,4,2\] -> \[2,2,2,2,2,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,2,2,**4**,2\] -> \[2,2,2,2,2,2,2,2\]. The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2. **Constraints:** * `1 <= nums.length <= 105` * `1 <= maxOperations, nums[i] <= 109`
Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively
Array,Hash Table
Easy
null
57
you would open fine questions around array in DSA rounds if you are appearing for fronting interview don't worry I am here to help you crack your dream job my name is vedant and you are watching array in JavaScript on GS Cafe so without wasting any time let's get started so today we are going to solve the question insert interval the question states that you are given an array of non-powerlapping intervals uh intervals non-powerlapping intervals uh intervals non-powerlapping intervals uh intervals this particular array where intervals I is equals to start I and I represent the start and the end of the I8 interval and the interval is sorted in ascending order so this interval is already sorted by the start I value and you are also given an interval leave interval which that represents the start and the end of another interval so insert new interval into intervals such that interval is still sorted in ascending order by start I and intervals still do not have any overlapping intervals merge overlap intervals if necessary return new intervals after intersection so uh the question is stating that we have a array of intervals okay they are sorted already by the value of the start index of each array okay so each array has a start index and a end index so they are sorted by start values and we have a another array which is called New interval and we have to insert this new interval inside the array of intervals that is given to us so if we try to you know insert a 2 comma 5 in this we can see that this 2 comma 5 interval is coinciding with this one comma three interval okay so what we have to do is we have to first of all combine these two intervals okay uh so if we try to combine these two intervals they will become one uh comma 5 like this I since 1 comma 5 is not overlapping with 6 comma 9 we uh insert 6 comma 9 as it is I'll go into depth uh once we go over a whiteboard so let us try to take this example and we form a logic to solve the question so we are given this uh intervals array one two three five six seven eight ten uh 12 16 and we have to insert this value okay so let me first draw the intervals for you so we have interval from 1 comma two you have one two we have three four five take five we have six seven F6 7 we have eight ten we have it 10 and along 12 16. and we have four comma a to insert so 4 will lie something between 3 and 5 over here so 4 is starting and 8 will be at this point okay so this is r or and eight new interval so we can see that it is touching one two three intervals of the original intervals array okay and so if we try to you know first of all what we will do is we will start iterating for on the intervals which is given in the array and we will maintain a result array okay so this interval I okay we will call this interval I whenever we are iterating so and this is a new interval so we can see that interval I 1 comma 2 is at the extreme left of the new interval or vice versa if we say if the new interval is at the extreme right of the interval I which means that once this end index of interval I is ending this is the new interval is not overlapping first of all and it is present at the right hand side of it okay so we can clearly see that this new interval is present on right of this particular interval so what we will do is we will directly insert 1 comma 2 inside the interval results array okay so we will push 1 comma 2 as it is okay we will not bother anything now we come to another interval I so this was done okay this was done now we come to this part on this part we see 3 comma 5 is overlapping with 4 comma 8 okay so now what we do we will do what we will do is we will try to merge three comma 5 with 4 comma 8 okay we will not insert anything right now because we are not sure after merging whether it will you know uh span again multiple uh intervals what I mean by that is let's say we merge three comma 5 and 4 comma eight now whatever is the new interval out of the result out of the merging is that new interval again overlapping with some another interval I okay we are not sure so whenever there is a case of overlapping we will not push anything unless and until the overlapping is gone okay so we can see that in three comma 5 there is a overlapping happening so what we will do is we will update the value of new interval okay so the new interval will be minimum of 3 comma 4 which is three okay so minimum of 3 comma 4 is 3 okay which so 4 is gone and maximum of 5 comma 8 which is 8 okay I am Crossing it so that it will make sense so again it becomes 8 okay now we did three comma five why we did minimum and maximum here so we see that this 4 value was somewhere over here okay like this so if we want to merge interval so will it make more sense to pick 4 or will it make more sense to pick three obviously it will make more sense to pick the leftmost value when you are trying to create value of the start index okay so that is why we have to take minimum of those okay because in this scenario the interval was overlapping over here okay there can be scenario that interval can overlap here also so in this scenario we'll have to take this particular value because we have to pick the left most so we have to always do minimum of the let okay and obviously when we are taking the minimum on the left it is obviously very obvious that we have to take them maximum on the right so maximum on the right is 5 comma 8 which gives 8 okay so this is the logic behind it Lobby drivers 3 comma five now we come to six comma 7 we again see that uh 3 comma 8 is overlapping with 6 comma 7 we will again do the same we will take minimum of three comma six it will be again three we will take maximum of seven comma eight it will again be eight now with drivers six comma seven now we come to eight comma ten now in eight comma 10 we see that it is again overlapping with three command because eight and eight are overlapping so what we will do is we will again merge this so we will take minimum of three comma 8 what will be it will be three again maximum of 8 comma ten it will be 10 okay this is the case now we have new interval with 3 and 10 and we Traverse this okay now we come to 12 comma 16 in 12 comma 16 we see that it is not overlapping with 3 comma 10 because 3 comma 10 is now at the extreme left of the interval I okay in this part for one comma 2 it was at the extreme right okay so we directly pushed one comma two but for 12 comma 16 it is at the extreme left so what is at the extreme left should be pushed first okay so we will push our new interval which is 3 comma 10 into the result array okay and we will now change new interval with interval I okay so new interval will now become well and 16 we will only update new interval for left case Okay so because we are when we are pushing new interval is now already pushed okay so new the value which was present in new interval is not of use anymore so we have to Now update the new interval with 12 comma 16 okay and we traversed it again so once we finished traversing all of it whatever was the new interval value which was 12 comma 16 we have to now push it okay so this is the answer one comma 2 3 comma 10 and 12 comma 16 let us try to verify 1 comma two three comma 10 and 12 comma 16 okay this was the result and this is the algorithm we have to follow so what we saw scenarios of overlapping cases in case of non overlapping it can be at the extreme right or it can be at extremely these two cases are handed uh handled separately if it is Extreme right we push the interval I if it has if it is at extreme left we push the new interval and we update the new interval if it is overlapping case we only update the new interval start index and the end index okay you can pause the video and try the same approach for this particular example one comma 3 6 comma 9 and it will make sense to you eventually okay so this was a logic behind uh solving this particular question and let us now jump to write the code for it okay so what we will do is first of all we will create post result this is our result array is this one which will contain all of the uh intervals now what we will do is for balanced pins database of intervals okay we are eye trading over each intervals okay so we have interval over here now we will check first scenario okay we will check the first scenario if the new interval is at the extreme right okay or we can say if interval I is and left so what we will do is if interval if the end index okay if the end index so how we will get an index it will get interval of 1 in interval of 1 is less than new interval of wave interval of 0 okay so new interval of 0 is present at the right and uh and index of interval I should be present at the left okay so interval of 1 should be less then new interval of 0 if this is the case then what we have to do is we have to push interval and that's it else if the second scenario over here is if the new interval is present at the left Okay so what we will do is we will chase see new way or what we see is if the printer one is present at the right okay so if interval of 0 is greater than new interval of 1 okay then what we will do in this scenario is we will uh push the new interval and we will update the new interval so we will do result dot push new interval and new interval will be we updated it else this is the case of overlap the water window is we will do update the start index and the end index so interval of 0 would be so we are updating the start so it would be matte dot mean okay Matt dot Main painter of zero and new interval of zero and similarly if we have to update the end index some math dot Max interval of 1 intervals of fund and once the loop finishes we have to do result dot push new interval and we will return result so let us try to run this okay it was accepted cool so code was fine so now let us uh talk about the time and the space complexity so the time complexity is bigger of n because we are only iterating over the intervals once the space complexity is Big O of n because we are storing the results inside the array okay so this was all in this video I hope you liked it if you have any doubts let me know in the comments this was all in this video till then take care goodbye see you in the next one
Insert Interval
insert-interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` _after the insertion_. **Example 1:** **Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\] **Output:** \[\[1,5\],\[6,9\]\] **Example 2:** **Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\] **Output:** \[\[1,2\],\[3,10\],\[12,16\]\] **Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\]. **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 105` * `intervals` is sorted by `starti` in **ascending** order. * `newInterval.length == 2` * `0 <= start <= end <= 105`
null
Array
Medium
56,715
16
in this video we'll delve into a concise and Powerful C++ implementation of the and Powerful C++ implementation of the and Powerful C++ implementation of the TM problem the code utilizes the standard C++ Library including vectors standard C++ Library including vectors standard C++ Library including vectors for array representation and unordered map for storing indices the two sum function iterates through the array calculating the complement needed to reach the target it then checks if the complement is already in the hash map if found the function Returns the indices of the two numbers otherwise it adds the current element and its index to the map
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
70
given a staircase it takes n steps to reach the top each time you can take either one step or two steps in how many distinct ways can you reach the top that's today's video let's get into it hi everyone my name is Steve today we are going through an eco problem seventy climbing stairs this is a very classic dynamic programming problem very easy but it's a good classical refresher you are climbing a staircase it takes n steps to reach the top each talent you can climb either one step or two steps how many distinct ways can you climb to the top given n will be a positive integer for example give an input to explanation there are two ways to climb to the top because top is only on two steps one waistline you climb one step at a time so it takes two steps the other way is that you just did jump two steps to the top directly so there are two ways to them 70 example is three input is free that means there are total three steps to reach the top so there are three ways one is that you take one step at a single time so total three one steps yeah the second way is that you take one step and at one time and for the following two steps you just jump two steps so this is the second way the third way is that it takes two steps at first right and for the last one remaining step you take one step this is the third way so total three ways so given n and could be 500 or 1000 how can we return the total number of distinct ways that we can climb to the top let's analyze the problem so suppose were given this example N equals to 6 so starting from 1 how many ways can we reach to step 1 there is only one right because the win take one step from the floor to step 1 that's it one way so we'll put one over here this just means there's only one way to get to step one then how many ways can we get to step two first way is that we'll go from bottom one step two steps to reach step two the other ways that we can just directly jump from ponen flow directly to floor too so two ways total here then we'll think about how we can how many distinct events there are to get to step 3 how many first way is that we can do step by step right step from bottom floor step one to step one from bottom floor to step one from step one to step two from step two step three once that I had a time this is one way the other ways that would jump two steps as we just went through in the problem description in the second one this is the second example input three right so while going through an input three so this is the second way which is jump two steps first and then take one step from 2 to 3 this is the second way third way is that would take one step from one floor to first step and then from first we directly jump two steps to the step 3 there are total three ways from bottom floor to step three then we can think about is there any repeated computation let's go through that again let's take a deeper or more detailed look at this is the first way take one step at a time so first to step one and then we jump we landed on step two this is part of the first way we lend it out step two of in business first way same way is that we jump two times directly first and then we also blend it on step two you actually that means we based the first two ways to climb to step three on top of the solutions of step two we landed on step two first in the first two ways to get to step three that means we can use this how many ways to climb to step two directly right and then we only need to add up the last one which is we didn't then on step two first we just landed on step one which is to step away to final top destination this is to step away right and then for this one what we can also use is the number of distinct ways that we can get to step one which is we only need to add up these two why is this because this one is to step away again this one is to step away to the final destination and this one is only one step away based on the problem description we can jump in the one stack or two steps so the number of ways so the number of distinct ways that we can reach to this destination is the number of distinct ways from that from the last destination only one step away plus the number of distinct ways to step away from the final destination so total if we can combine these two steps into one which is this number right the number of distinct ways that we can reach to step two and this one is just this one the number of distinct ways to reach step one then we add on these two together it's going to give us the number of distinct ways to reach step three so follow in this logic what we can get is for all of the rest of the steps we can finally know the number of distinct ways to reach to the top which 6 which is 6 in this case the number of distinct ways to reach stair number 4 is how many 3 plus to write the number of distinct ways to climb to step 3 plus 1 step 2 step 3 with just that fall or the number of distinct ways from step 2 jump two steps directly to step 4 so that we know the number of distinct ways to step 2 is there 4 is 3 plus 2 which is 5 so we know 5 is here then we can calculate the number of distinct ways for step 5 which is these two combined this one jump one step this one jump two steps so the number of distinct ways to step five is 5 plus 3 which is 8 then last stair 6 I mean distinct ways we can even take one step from Step five to step 6 or we jump two steps from stair form directly to step 6 so the number of distinct ways to climb to step 6 which is the top is 8 plus 5 is 13 because the problem says we can even take one step or jump two steps at a time so we only care about the last two steps how many distinct boys and how do we get him the last two steps we calculate from the very first stair that's how we get to the final state first assumption is that we can use in a cache or head array to hold every single possible distinct waste from step 0 2 all the way to step n minus 1 that's just to quickly put that idea into the actual code right now so a couple common cases if Ken equals to 1 what is written in give a can will be a positive integer so we don't need to worry about n is not clea for N equals to 0 so after this when n is greater than 0 what will do is that will initialize an array called DP dynamic programming we're just and you can call it whatever I just call it DP and the size of this array or this catcher is going to be n plus 1 because we want to return the number of distinct ways to reach step n so DP 0 is 0 to Q 1 is 1 and DP 2 is 2 and from tickets me will just calculate based on the last two steps right so what's time from DPI equals 15 I is smaller than or equal to n so that we can get up to n naught n minus 1 and then what we'll have is epi how do we deduce TPA or get declined from TP n minus 1 plus EP by minus 2 the last two steps because we can either jump one step or jump two times so ok similarly if the problem details that you can jump from one step or two steps or three steps then we can calculate value last step based on the previous three steps so it's all based on the problem description but the idea is the same ok then in the end World War two is that which is written DPM that's our final answer because for three steps DP is going to be three and how do you get free weekend from 1 &amp; 2 how do you get free weekend from 1 &amp; 2 how do you get free weekend from 1 &amp; 2 first and then we calculate D P 3 based on top of DP 1 and D P 2 the sum of these two known as hit submit answer all right accepted this is one way to use dynamic programming very simple classic problem but we are using an ax array which is costing us Oh an extra space so is it possible to further optimize this in terms of space complexity we can use constant space is it possible definitely as possible after we take a deeper look into this we realize we only need constant actual space we don't need to keep this internal already right all that we need is the last two steps suppose this n is 100 we only need to know that last two steps 99 and 98 for the rest from 1 to 97 we don't really care right so we can just keep overriding these to temp variables until we finally get to talk and if we write it in that way we don't need a whole extra array which is going to give us O one constant extra space complexity okay now let's put it that way let's remove this so we'll initialize two variables okay one step or call you one step is one and two step is to it's not super descriptive but that's fine you get my idea in their World War two is I equal to 3 I smaller or equal to n I plus first of all use a Templar about you how to use that and then we can overwrite use that to become one step so this to stamper is actually the third step right how do we get to the first time we use the one step plus to stack these to add it up is going to be the new to step and then the one step is going to be 10 we basically move everything upstairs one at a time so previously once time is one to stop as to where we're very Bonnie one step to step and then we put to step into a temporary book we move one step we calculate the third step to make that one to be the new to step and then we move one step towards the previous choose that right so that we keep or keep calculating this until we get to in which in this case is going to be Tuesday so what just written Tuesday in this case now let's fit some in again it's also accepted so this way we're not using an extra array which is costing this o n space complexity this one we're just using o one space complexity that's the entire algorithm I hope this video helps people better understand climbing stairs this classic dynamic programming problem if that's the case please give me a favor and hit that like button that's putting it out loud with the YouTube algorithm and don't forget to subscribe to my channel and hit that little bow notification so that each time when I published something new you are not going to miss out on anything right now we're going through dynamic programming problems after this well those were sorting and searching and then different combinations of data structures and algorithms to help people better prepare for their upcoming conan interviews so hit subscribe and tapped a little bell that's it for today's video I'll see you guys in the next one
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
421
Hello hi guys welcome to question today's question is this maxims of two numbers in there in this question be aware of it has been up to find now pair yield and this maxim for example where given importance of 310 phase to final year of elements which is- Who wish you perform all pressure is- Who wish you perform all pressure is- Who wish you perform all pressure operations and tender final maximum answer 16 in this question answers when I will who and 525 worldly tasks 228 Sunao This question is the medium difficulty level Shoaib Root for a process which comes into mind has been found all the players thoughts Possible in this way are and after each player equities or and a maximum of DJ and vitamin A written test and answer but for finding dividing all the best the complexity will be heroin square but as given in question and will have to key price all you need To no entry zone time so let's look at the president how will solve turnon time so in this question will be used in you dare to sector 63 noida sector 98 sector electrolyte structure which can have any number of children open and sharp not Responsible for is saunf bahu Jodi 70 hindi type question what to do when the are given of a given up in teachers nor will represent a teacher indore binary from it - 30 - 10 teacher indore binary from it - 30 - 10 teacher indore binary from it - 30 - 10 and so on but will do will stored in the representation of numbers in A day after her inside this number will run in the result will be inserted into positive energy presentation of every true Indian will send you a daily up-to-date 2040 8000 will not end with a woot you a daily up-to-date 2040 8000 will not end with a woot reason Light of note 1000 then 200 Feet of Light This Is Not Enter Into Its Wings Tours That Often Dream for Every Number to Be Spotted Starting With Her Daughter Is Not Destroyed Already Considered All Already Has 3 Minutes No How Will Win 10 Swift Will Take What's the First Day Off from left it is rose subhe teesri wazah and will oo cant dil laptop video laptop subscribe from this is not that no veer montu did not know which after which and debit card ban no this is a you have not have no where to insert One at not being check pad to right side is one will decide whether or not a subscribe button on the right side and here and win over the country will check the left side of 10 ki shubh and is not sudhir is notebandi left side saw her will Inverter 099580 moot this mode of country where is not no java but even know what will check the right side existence not get any one which will not work on that hand move to that node from this is not fair game so this note is a unique Value and you are British zero handedness note will check weather in the left side only cry system note suji road not exist on website from inside you will value of 043 left side view from this will not come into this will not appear in all is ok na Almost nine setting five will again started from head separated instruments and with similar to the procedure first 2012 0 to destroy 2099 come the one hand they did not stop this is not one does not exist for not attending the value of one and similarly they will Keep Doing Tasks and Install Number 90 Number One Position at Opposition Like He Didn't Interested New Delhi On 20 Percent Advantage of Attraction Say Special Song Sunao Vansh Withdrawal Number Minute Rai Unmute Rai Has Welcome Like This End Destroy consists of all the numbers will present in are suno but nobody will you will calculate maximum possible particular element at index like share and subscribe maximum possible 9 0 and sunao bhaiya check khayal checking the maxims and are using try what will you start hoti hai deposit opinion naav aur first element 0.0 so to maximize an first element 0.0 so to maximize an first element 0.0 so to maximize an answer vinod light bill to be different in the country should contribute in an answer otherwise dowry contribute to for wall paintings to contribute will have to look at wear look with raw one exit not know Like Share And Festivities With Gifts For One For All Hai So Will Take This One Into Account Dushman * Of Baroda 0.1 0 Results In One Will Take Into * Of Baroda 0.1 0 Results In One Will Take Into * Of Baroda 0.1 0 Results In One Will Take Into Account No After This Has Been Taken Into Account From This A Andar New Hai Begum Desh Nav day next since vacancy date which was the first and also for taking or be considered for tweet only member to keep in mind deficit of number rid sperm find and point to the first level best of the try know what is this nov15 web 2.0 hindi level committees this nov15 web 2.0 hindi level committees this nov15 web 2.0 hindi level committees 200 SECOND LEVEL OF THE TRIE ELECTIONS And 2008 to check weather in the right side of this not one a system not shown its display or not want we answer and will move towards infidels and left with no choice but to move towards left election is most developed and they are this country are Destroyed and the work of 14.5 and know it is one new but even under of 14.5 and know it is one new but even under of 14.5 and know it is one new but even under current nodes in president check weather exists in this life is note and subscribe Video subscribe left side se z900 10 results in one and you will contribute to an answer listen one tsp Twitter answer will move to the is not edit loot not know we are currently in the tribes and does not and work of work for in this 409 plus with oo a newlywed dish they did not and different 2002 check weather in the trolley become is not which Of This Is The Answer Of This Is Not The Answer Is The Work Of All The Spider Man E Agree Position Which In Which We Encounters Request 150 Using Power Function To Calculate The Calculating Decimal Equivalent Which Will Be Added In An Answer Siddheshwar How Were Supposed To Find Any 2009 Veer Will Be Us Every Element You Finds All Like This Only And With Witch Element Beams Or Witch Will Make Him Will Be Returned Listen Let's Look At Record Sunao In This Question ABC Ye Festival Electric Chair For Class 9th A Hungry Hour Two elements dentist left and right were but 350 and right will be 512 I am Sumit Medhak class's trial road embodiments of public services access dementia also so finally maxims and back to back two steps first will have to install element in array and second Step Store Tractor And Every Point At Every Element Where To Find Maximum Possible Or With Respect To The Element Of Village In More Per Ko Format Rai Show Will Write To Function If This Would Help Love With Us Will Return A New Head Wilson Office Number Delete New head and when will search giving a number and is dubai changes and vitamin a new hit the fastest rising star function remedy insert no but very few minutes for division number to insert and increase in second head of the present tense ye sunnat nodimciu head a That show first but left drop back to insert the number bit by bit nod32 fennel will be a your husband then a hybrid daily 1205 - - your husband then a hybrid daily 1205 - - your husband then a hybrid daily 1205 - - pure form in arranged number date of birth number first will find a current difference phase with that end Right but I that not when you find a certificate morning will do that yesterday number and will right swift number by 30 is and which one oo mein vriddhi step will get the best PM to politicize orbit insider one so ifin 2011 2012 2010 left Side Button Subscribe Now To Receive New Updates Reviews And Subscribe Button Right Side David Villa MP3 Short Note Cold One Using One Value And In The Point Is No Point In Two Head This Will Now Be Appointed To Per 150 Moving Towards Right Side C Letter To Interact With a point at which starts beating iconic starting with a ki naav being debated heroism in battle of move left nochegi is note is hua hai ki noida blood test bhi to pos creator nodi left a ki naav bjp leader not to left know when one is created A nod to move to 9 current left's repatriation this Nobel price but 3000 key elements left side fa3 left no water no exit point for Greater Noida in the year student knows no evidence and will not proceed to move to earth left no N Torch light does not exist to note on this website 10 Mukesh shift form the right notes a first for the right node that and even after comedy night note back to move to that in note current 222 the current light That now after 10 loop Executive Editor of the three times a day in all the certificates will be positive blood of this number will be will have been entertainment opinion so after 10pm to return a held on a note via 9 we are in the main function from Where To Call This Award Function To Make Attractive First Word You Will Form After Head Dept Se Stir Head Is Equal To New Trance Mode On 220 Awesome Head Noble To A New Web To Call The Function Of Insult After And Inside Every Number On This In 2-day strike from its rule numbers in see the 2-day strike from its rule numbers in see the 2-day strike from its rule numbers in see the return function held nowhere to insert religious head and number sorry number wise increase in number its to insight and e held on that not raised from 9 blind maxims and possible and avoid will find a maxims And Possible Using Between Number Decision Intimate Scenes And Possible In Three Languages ​​In Finding Maximum Possible Languages ​​In Finding Maximum Possible Languages ​​In Finding Maximum Possible Solution And Torn And Will Return And Vitamin C Maximum Dancer Sleep Civil Right The Function Which Determines Or Int I Maths And Second Function In This Will Give Lipsing Are Head Office try note sir head and vector that nine hindus will declare variables that is gold maths answer visto the i maths possible answer and initiated with intention on that noida toll bridge the gap to finally maxims and with respect to each element noida through are o The British and so on rent for every number whittaker node which cannot write notes4 a flying note 4 current and definition of with held always a but now value of number nov15 added at index in twelve equal to numbers of match that a mit heart attack Available Which Will Be Chal Bhai Karan Johar British To The Value Of This Job Is Possible With The Highest Value And Will Be Compared With Maths Answer Video not have much Maximum Possible You Will Need To All Of U Hai All The Best 100 Par All The Best Option Ladies Eye - - Laddu Best Known For Its Ladies Eye - - Laddu Best Known For Its Ladies Eye - - Laddu Best Known For Its Position Will Find The Best Print Thirty First Date Of The Best Option Will Be Given By Value Life In A Key And One Day That No The Body Is Bit Of Using So Body Is Better Than Sorry it's not I will bj vikaas vijay sorry worry not decide then good izzat beat of value 39 it's processes 120 idli 120 na in this case it's form maxims and fennel but this will help you find the right side of 1000 this point is 98100 A Special 09 Bill Give One Entries And 10 Have To Find Yourself But Sunao Tay Mein Notification Hota To Check In The Right Side Vriddhi One Big Sister Note Just The Current Light And Might Exist But Will Do The Current President 19000 But One Position Will Give The answer for super dancer to you that Karan Johar A plus equal to power of two positivity it is being so agent will contribute to the answer with to tower J dance plus season to tower J9 B-20 and dance plus season to tower J9 B-20 and dance plus season to tower J9 B-20 and rights activists who will contribute to The Answer Will Move Towards Right Side Current Is Equal To Current Light Nov 20 2013 Do Not Have The Right Side Par Try Not Were Left With No Option But Oo Left Side Only On New Delhi But In Developed Country Example CC Me BF Destroy And Supported Particular Condition Were Stopped Protest Visible Also Reduce Blood Sugar Making And Note Of But How To Get Last ODI Right Side But There Was No One President Subha Hai Were Left With No Choice But Toe Move Left Only 100 Hindi Support Will Move Tool December 2015 151 We Have To Forms And 1212 From Left Side The Current Left Exit Not Currently Exist Will Repeat Distinct In The Current Affairs In The Current Date Value Will Contribute To Workers And Answer And Will Descend During Size Updated And Left Side Is I Will Repeat You Left Side Mails fluid exit option a that nine after 10 loops is uniform 22212 condition me British zero and the best one and wakes up only corresponding calculating and karan johar demonetization were done without sleep over all I away from you follow behavior answering friends and will be comparing and Answer Here Final Match Answer A And Underwear Begum Act Answer This Current George Better Than T Maths Answer A Message Will At This Point After Dil Luteya Loop Radiation Which And Will Contain The Maxims And Possible With Highest Element Known Element After 10 Will Return For maths answer is me vitamin and MP solitaire make transfers in a main function will return max george inner the main function and jaipal ji and comment subscribe other is per the current president subscribe school ki congress party all deposit cases coincidence like this video thank you a
Maximum XOR of Two Numbers in an Array
maximum-xor-of-two-numbers-in-an-array
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. **Example 1:** **Input:** nums = \[3,10,5,25,2,8\] **Output:** 28 **Explanation:** The maximum result is 5 XOR 25 = 28. **Example 2:** **Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\] **Output:** 127 **Constraints:** * `1 <= nums.length <= 2 * 105` * `0 <= nums[i] <= 231 - 1`
null
Array,Hash Table,Bit Manipulation,Trie
Medium
1826
1,869
lead code 1869 longer continuous segments of ones than zeros so the question explained is that you'll be given a string something like this and you need to see what is the longest continuous string for one so in this case the this out of this is a continuous string of one and this one is the longest what's the size of it three right at the same time check the longest continuous string of zero so this is one and this is one which is the larger largest of these this one it size is three so even this is three so in that case I'll return false because the longest continuous one is not bigger than the longest continuous zero right but if say this was like this then the longest ones would be three and the longest zeros would be two so I'll return true in that case so this is what we need to do programmatically okay so what I can do is one way to do it is that I can split this entire string by taking all the at all the zeros right so if this is like zero right so I'll split it here then this would become two string then I would split at this zero so that would create two string uh yeah then I'll split here that will create two strings and no more and then I'll take the largest of this so these are like four strings and I'll take the largest of it and it's like right similarly I can do for uh zeros so taking the same one if it was yeah it was originally like this so I'll split by ones so this will be removed and this will turn into two strings then this is another one so this will be removed this will be two strings one of it will be empty and then this three again this would make two strings zero and the rest and then again I find one so this will again be removed and we created two string this will can be split it and it will be removed so this will again create new string and then finally for this one this will create a new string so finally there would be all the strings and the largest of it would be this and it size is two so this would return two this would return three and then I can compare and return so how will I do it in code return I'll take length of s do uh Max of s dot split at one right and this will return an array of all the strings or I could do it zero here yeah and then Max will have a key of length so it will decide on the length function it will pass all the strings to the length and it will decide the max based on the response that gets back with length so that one string will be returned by Max which is the largest and the length of that I'll take and I'll check that if that is greater than I'll copy this entire thing and split it by one now so this will give me the longest quanti is zero string with zeros okay so I'll compare the two with greater than sign and return it let's run this and see and that worked let's submit it and that worked the other way of doing is this used a lot of internal functions although this is order of n solution but there was a lot of internal function usage so if I were to do it in a interview setting how would I go about it so I would first uh collect all the uh the largest size I'll maintain the largest size for Zer say m0 I'll initialize it with zero and M1 so m 1 and M 0 I'll initialize both with zero so I'll keep the longest uh string with zeros here and the longest the size of the longest string withd one here then I'll store current to be zero no and it initialize current with one so the smallest Zer or ones would be the first element right so I'll initialize that with one and then I'll go about I in range from index one to length of s which is the last index and then I'll check if s at I index is equal to S at i-1 at i-1 at i-1 index if it is equal then what I'll do is I'll increment my current by one if not what I'll do is I will set current to one again reset it and before that resetting I'll check if s ius1 is equal to Z then I'll compare m0 and set m0 is equal to Max of m0 and current whichever is maximum that will be set else I'll set M1 is equal to Max of M1 comma current so whatever this current was storing for that will be compared with m0 if the last element was zero and if the last element was one then it will add compare to M1 and add it update M1 so that's all finally I'll return M1 greater than m0 whatever the answer is I'll return that let's run and see that didn't return true for this that is because I am doing one thing incorrectly which is um I should be checking uh after this Loop is over okay for the last uh for the last string it is not going in the else block right so in that case I will after the loop is over I will check once again if last string which is s at index minus one is equal to zero then Max is I'll update m0 else I'll update M1 and uh then now will check let's run this and see and that worked for all the test cases let's submit it and that worked a
Longer Contiguous Segments of Ones than Zeros
longer-contiguous-segments-of-ones-than-zeros
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest continuous segment of `0`s has length `3`. Note that if there are no `0`'s, then the longest continuous segment of `0`'s is considered to have a length `0`. The same applies if there is no `1`'s. **Example 1:** **Input:** s = "1101 " **Output:** true **Explanation:** The longest contiguous segment of 1s has length 2: "1101 " The longest contiguous segment of 0s has length 1: "1101 " The segment of 1s is longer, so return true. **Example 2:** **Input:** s = "111000 " **Output:** false **Explanation:** The longest contiguous segment of 1s has length 3: "111000 " The longest contiguous segment of 0s has length 3: "111000 " The segment of 1s is not longer, so return false. **Example 3:** **Input:** s = "110100010 " **Output:** false **Explanation:** The longest contiguous segment of 1s has length 2: "110100010 " The longest contiguous segment of 0s has length 3: "110100010 " The segment of 1s is not longer, so return false. **Constraints:** * `1 <= s.length <= 100` * `s[i]` is either `'0'` or `'1'`.
null
null
Easy
null
147
hey everybody this is laurie this is day two of the league code daily challenge for november hit the like button hit the subscribe button join me on this card let me know what you think about today's farm uh which is insert it's insertion swordless so apparently this has been out for a little bit because of daylight savings it's always very confusing but anyway let's look at today's problem uh let me know what you think let's do insertion sorry repeats now okay uh okay so insertion sword for a linked list i guess it is what it sounds like do we return the head is that what's going on it's not very clear okay so you return the head it seems like this is not clear from this example that what it is but i think it is just literally implement the insertion sort so it should be pretty straightforward um if you know the algorithm which they tell you so let me know what you think but yeah but so i'm just trying to think whether it makes sense to get um it makes sense to get uh the smallest element first and then put in the front or get the bigger the biggest element put in the front and then just keep on doing it that way that's what i'm thinking about i think obviously it makes no difference realistically but uh i guess depending on how you want to up solve and how you want to be precise we can do this so let's just keep track of um of a tail which initially we're going to put let's just say none right and this is where we insert our biggest element um right or sorry our smallest element and then now we just need a loop while true let's just say current as you go to head maybe uh now first find the smallest element starting from some uh head element from kern maybe we'll have to figure this out we have to clear this out as we code it but um but yeah so first we start and let's just say new head is equal to none maybe but we'll figure it out and actually that we should we just say the tail should you go to head right um and all these things don't technically matter to be honest as long as you make sure your invariant for the problem is correct then as long as you kind of code the rest of your problem with the same invariant that you came up with that should be okay so let's just say current is your tail um min element is equal to say infinity for now uh moon element value say main element is equal to current i guess we don't need the element value then in that case while min while uh current is not none current is equal to current.next current.next current.next but not before we check to see if it's the main element so if min element dot value is greater than current that value then min element is equal to current right so this should get us uh where we need to be for the tail um and now tail is where you begin uh maybe there should be tell this is a little bit weird i think that's why um okay let's just say i think in theory you're supposed to move this forward but i think we could actually just create a new list so let's do that let's just create um let's just create a new list then this makes it easier and then we just go to head right we could go through the head every time and yeah and then now main elements should have the smallest element so then new head so none new tail is equal to none uh and you could do it another way with the sand notes but that's where i'm going to do it so yeah so new head we don't really care about the new tail in theory we add next is z co2 uh main element right this is just really annoying to get right because then now you have to delete min element but then you have to kind of make sure that the previous point intermittent element uh skips you so it's like all really weird that's why i always find these problems annoying but um but it's okay we could find it um we could just do another iteration but is not a fun problem it's not hard it's just annoying and bookkeeping as i would like to call it um let's just have a previous uh and a min element previous this is ridiculous but okay fine this is so much easier with a double doubly linked list but uh but maybe that's fine okay right something like that okay and then now we can we move to node so previous uh if previous is not none then we okay maybe the other way if oops if previous is none that means that we're removing the head so head is equal to head.next so head is equal to head.next so head is equal to head.next and that's all you need really um yeah else then previous.next is equal to previous.next is equal to previous.next is equal to min element dot next and that's pretty much it as well um and now we want to put min element in the next best so we do this but we not before we go if new tail is not none then we just do this and that's pretty much all you have to do if new tail is none then that means that new head is known as well then new head is equal new tail is equal to min element i think this should be good uh let's return um yeah i think the wow true is that we have to make sure that um there's still an element so wow head is not none let's give it a go first and then see if that looks okay not that confident to be honest because these things are always tricky and yeah and that means that there's an infinite loop somewhere also i just want to put in this case as well uh they don't make it paste cut and paste friendly but that's okay so time limit exceeded that means that um well ahead we don't set head that's why in theory this should trigger eventually when head is the min and then this should be none but i think there may be some invariant that's not true here so we remove current oh no we removed min element oh this is actually main element previous i can add them confused so maybe that's why let's hop so uh well okay it's something it's not the right thing there's something um oh yeah we set new tail down next is a good main element but then we said new tail as you go to newtown.next tail as you go to newtown.next tail as you go to newtown.next because now the new tail is the new tail right easy mistake to make uh okay so let's give it a submit actually i should usually i test like one element cases and stuff like that but uh yeah forgot this time so yeah but it looks like it's okay uh it's about dirty lines of code but to be honest it's still a little bit annoying a little bit um just bookkeeping and it's the tricky part is that there are a lot of edge cases and with experience and practice you can kind of see where the edge cases are and then code it in a way that makes it easier to handle the edge cases otherwise it's just a lot of if statements i'm not saying what i have here is the best but looking back looking at it now to be honest i'm pretty happy of what i have with respect to like keeping it small and tight um like this is a thing that i honestly myself don't practice as much because it doesn't come up that much in competitive programming right so yeah let me know what you think about today's problem let me know if you have issues it's okay like i think algorithmically it's um it's not that interesting per se but you know there are a lot of possibilities for implementation issues and offline ones and weird pointers not pointing the right way so it's good practice for implementation purposes anyway that's all i have for today i will see y'all next farm bye
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
210
all right so let's talk about the course schedule too so if you didn't watch this course schedule one then you just go back to watch it so once you're finished you'll be able to understand uh what additional code you need to add so basically in this one you are going to return the order of course you need to take for i mean to finish all the course right so um basically you need a list and then once the queue is empty then just keep pushing and then when you push you just add a person to it so this is going to be pretty much the same idea so um i'm just like okay so i'm just like stop coding so hashmap integer right so this is going to store the number of courses and this is going to be the list i'm going to go math okay so um i would be able to know that what the courses i need to uh what the courses i need to take uh for the courses i need to take after right so for example b so you must take the b course first before you take the a course so this is like outgoing like a like outgoing direction right so something like you must take the b first before a right so and then we still need while we're starting in degree array and this is going to be represent number four courses and i can traverse the requests right so i'm going to say star is going to be what reverses one and it's equal to what process is zero so starting zero is definitely uh i mean sorry starting m start representing the starting course and represent the ending course right now you can use the uh i mean map.plus something like this i mean map.plus something like this i mean map.plus something like this right but for people who don't know how the compute is absent now we just now just write another way so uh map.content star so if uh map.content star so if uh map.content star so if the map doesn't have the star then you just put the star with the new arraylist and then once you create it right then you can just say and i get a start and i add the course into the list so i also need in degree and this is copy and paste in degree integral and plus this is because i have an incoming degree from of course b right so this is going to be pretty much it right so i need a q for integer right q equal to new linked list this is going to represent what the cursor you need to just keep adding for uh for in degree equal to zero right so you know this is of course you have to take first right so for in ui listing nums courses and then i plus so if in degree at i equal to zero cue the offer yeah okay so now this is gonna be um pretty straightforward so uh you basically traverse from the starting course and then you just push i mean just traversing uh while you are i mean while you're linking to others courses right and then you just decrement the incoming degree when you remove so i would say well q is not empty so in current with q double and then i will just say traverse my neighbor and now i'll say mata get over d4 and this is going to be what current all new release all right so you definitely need to use net uh or default this is because what happens if a current doesn't uh doesn't um uh doesn't have anything right so you have an uh you have an empty arraylist so i'll just decrement the incoming degree for the neighbor and if this is equal to zero i will just push into a queue all right so this code is 99 like the course schedule one right so in this case you need to return in array right i'm gonna call resort new ins this is gonna be based on what the number of courses i need index for the results right and i probably need a counter right i probably need a counter so when i pull right i include my counter and if the coin is actually equal to the number of courses i will just return results else new end as you right uh where is it so if there's empty right then you just return to zero and so i'm not finished i didn't push into the result so once i pull out the q right i will say index for the turn and this is going to be pretty much the solution so let me run it all right so yeah uh the timing space is gonna be v plus e b represent the number of courses e represent the course you reject uh you relate to so this is going to be pretty much it right and definitely you can use uh the list array to solve this question like look for schedule one yes if you didn't watch the uh the video just go back to the previous one and this is going to be pretty much a solution so i will talk to you later bye
Course Schedule II
course-schedule-ii
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. * For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**. **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\] **Output:** \[0,1\] **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\]. **Example 2:** **Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\] **Output:** \[0,2,1,3\] **Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\]. **Example 3:** **Input:** numCourses = 1, prerequisites = \[\] **Output:** \[0\] **Constraints:** * `1 <= numCourses <= 2000` * `0 <= prerequisites.length <= numCourses * (numCourses - 1)` * `prerequisites[i].length == 2` * `0 <= ai, bi < numCourses` * `ai != bi` * All the pairs `[ai, bi]` are **distinct**.
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,269,310,444,630,1101,2220
1,326
Hello everyone, welcome to you, we are going to do video number 61 of my channel. Before starting, let me tell you the playlist of DP concession questions. If you want to see, then you can see there. I started understanding BP from the very basic. In that, we solve each and every problem through recognition memorization and bottom up, so you can refer to the playlist as well, so what is today's question, DP's lead code number is 1326, hard marked, but very simple, through recognition memorization. These questions can also be solved today in the morning itself, I have posted its video using greedy approach. You will remember it. Today in the morning it is okay but a simple recreation of this, memorization is absolutely literate, you have to write zero and this too will be done, okay. The name of the question is Minimum Number of Apps, You Open, You Water. You have asked this question. It is ok and I will not waste your time in understanding the question again. Already, I have explained the question. You will also see its bill in the video of Giridih, I am giving the link. I will give it in the comment area and in the description, I have explained the question there. Let's see directly how we can solve it with DP and in this video we will solve it using our Khandani approach. What is the Khandani approach of DP? What is the Khandani method? DP's own recognition and memorization and where do I make its bottom up? On the DP concession question, the bottom will also appear in the playlist. If it is okay for every video, then we will make it today. There is no problem in this. So see, let's solve it with this example. Solve it in the traditional way, simple, you will open it Okay, open tapa note, open tapa, these are the two options, you will open that one, you will not open that one, our problem will be solved just by this, how do we solve this problem, okay if You open it, take it, this is your penance 01234, so you should know the left range and right range of each type, what did I tell you in the greedy solution, I told that we create a separate vector in it for each type. Let's write the left ring and the right range, right, so let's do the same first, after that let's move ahead, so see what I have done, I have taken the input from and from that I have made the range named ray, this is the range named hey. Okay, look, pay attention, the ranges came out the same, it was given that this is the range of any type, I have changed it, the plus range will come, so if you take it out, what will come 0 - 2 i.e. -2 0 + take it out, what will come 0 - 2 i.e. -2 0 + take it out, what will come 0 - 2 i.e. -2 0 + 2 - 2 The range is from 2 to 2 but -2 is 2 - 2 The range is from 2 to 2 but -2 is 2 - 2 The range is from 2 to 2 but -2 is not there, zero is the minimum, so I have given you from zero, you may remember this in Greedy also I had told you, okay look similarly, 1 - 0 and 1 + 0, so 1 is look similarly, 1 - 0 and 1 + 0, so 1 is look similarly, 1 - 0 and 1 + 0, so 1 is similar to 2 3. Look at this 2 4 - 2 4 similar to 2 3. Look at this 2 4 - 2 4 similar to 2 3. Look at this 2 4 - 2 4 + 2 What will happen, there will be six, but six is + 2 What will happen, there will be six, but six is + 2 What will happen, there will be six, but six is not there, maximum is four, so I have given four, I am fine, I can do this from tu to four, so if I make a light drawing and show it. So this penance is fine by doing it from zero to tu, and this type of penance, pay attention to this, see that it can be done from tu to four, that is, it is 2a, right, it is fine by doing it from here till here. So Idli, the answer should be two that if I open this type then this much tax will be done and if I open this type then this much tax will be done then the entire garden will be taxed, so the answer is two because you will have to open two types, okay That's the answer, I told you, but now let's see how to solve it with DP, okay, so I have made this vector with range, okay, I will index it, zero, one, three, four, okay, so what did I tell you that friend, any Any type of i, I have two options, I will take it, either I will open it or I will not open it, if you open it then no problem, it will flood further i+1, then no problem, it will flood further i+1, then no problem, it will flood further i+1, what will I do and even if I open it, I will go to i+1 But science, we have go to i+1 But science, we have go to i+1 But science, we have opened it, so what is the maximum extent of the garden that would have been soaked from here, this much of the garden would have been soaked, okay, so tell us one thing, what will we have to keep preparing, what is the meaning of maximum, where did it even go to mathematics? There will be a garden, if I have opened this type, you would have also reached there, then I will continue to do more curries, okay, this thing is clear, okay, then tell me one thing, if I come here, okay, remove this now, if I came here, yes, this is the maximum, I am writing it down so that I don't forget that I have to keep doing more max. Ok, tell me one thing, now that I have come here, is it okay, so if I want to check, is it already wet? Because of this, remember, he could even get you wet, so if I want to know whether he is already wet or not, then obviously what I will check is this one, if this guy is smaller than you. Okay, and look at this, there is also a forest in the middle, that is, this one is smaller than you, what does it mean that this one will also get wet, so it is a good thing, it will get wet, isn't it, what am I saying, now I am currently here. If I am standing on it, look at the first band of I. What am I saying? Look at the first band of Range of I. It is small, which was the previous one's Max and Se marks, and if it is this, then it is small, do you understand the meaning? This too must have been done for sure, but if the mother had taken it would have been bigger, then this point is very important. If it is what it is, if it was bigger, it would have been three or the tax would have meant that it would have been bigger than its max. So what? There is a problem, understand that it is okay, it can wet you from zero and right now I am in G type, it can run to three seven, what does it mean that if the first band of where I am standing becomes bigger than Max and If it grows bigger then brother, it will be a mess, we will not be able to get the whole garden wet, at this time we will have to turn back because brother, it will not be possible, okay, one thing has happened, isn't it was a very logical thing, I hope you have understood. But one more thing, think for yourself, I am comparing, but to compare, brother, we will have to keep them in order, whatever tapas we have, we will have to keep them in sorted form, only then we will be able to compare, there is one. Will he be able to do this or not, how did he know because it is in sorted order, see, it is from zero to you and this is from one to one, meaning from one to one, it is one to take the mother, one to one, this is the range, okay. So, it was in sorted order, only then we will be able to know, I am fine, so what does it mean, now it will definitely be in sorted order every time, so what does it mean that one more thing, we came to know that brother, we have to sort our This range is clear till now, shorten this range of ours and what two things have we learned when we will do recension tomorrow, we will have to walk neither max nor lake, nor is this its max and what is it, why because when I am here, then I We have to see whether this banda is wetter than the previous one or not, or is it wetter than the previous one or not, otherwise I will compare this previous one with Max and others, okay then we will have to go to Maxind Lake, okay this point is clear, Max and That thing is clear, okay and remember what I said that from where I am standing, how will I compare the range of I, if its first band, if greater is taken out than the max of the previous one, then brother, there should be a return which cannot be anything, mines. Saying one return means that it is not possible, it will not be possible, okay, infinity tax will be charged for gardening, okay, you have to pay minimum tax, you send it to infinity, brother, it will not be possible, okay, we have come to know many things, first of all this. We came to know that we will compare like this and to do this comparison we will need max, that is why we have written max here, it is okay and why we will have to sort, we will also know that only then you will be able to compare like this, only then you will sort. So such comparison will be valid for everyone, isn't it, will the comparison be valid for everyone, whenever you sort, okay, you will have to shorten it, so let's see whether it is sorted or not, it is not visible to me, look at this, it is zero, then This is you, this is three, then this is you, so let's write this here, let's do this here, 24 will come first, after that three, common three, you will be four, after that 3, okay, it is clear till now let's move ahead, so now see. Now follow your own method and start from here, okay, you can either take it or not, okay if mother takes it, I did not take it, then I will go to I + 1, not take it, then I will go to I + 1, not take it, then I will go to I + 1, okay and initially I had max and zero. Max and Zero will remain zero and will not change because we did not take this type and if mother had taken this type, we would have taken this type. If we had taken this type, then I would have taken Max and change would have happened, otherwise what would have happened to my Max? What is the maxim brother, are you there or can you reach up to you, this is okay, so which one was it that I took this type, then I band the account of this type, now it is okay, now I came here, so I first I have seen that brother, I compare this first i.e. the first band of I of the range, first i.e. the first band of I of the range, if it has been taken out bigger than the previous one, there is more point, otherwise it is so, otherwise we will not return anything from here, it means we will not run away from here, it means it is going well. This one must have got wet, this one must have sent the type also, okay, so that means there is no return from here, that means they are going good till now, so the same thing will happen again here, we will try two options, take this or It is okay not to take this okay, so I am following my mother's advice, I am this, take this okay, so I am following my mother's advice, I am not making the complete tree diagram, it will become long, you can try making it in your free time, okay, so I will try not to take this and if I don't If it is okay then Maxind will remain the same, you will remain the same, no change will come, ok, okay and if we did not take, then the account of one type will remain the same, nothing will be added, okay now I have come here. Remember, Max is still there because we did not take the last type, Max and there was no update in it. Okay, now let's see what it has. Okay, so first of all let's see its first band i.e. the range. I dot first band i.e. the range. I dot first band i.e. the range. I dot first, do they give greater max and no? If not, then there will be no returns from here, meaning they are good. There is no such condition that there is a gap in the middle. Okay, so it is not so, then it is good. Then Here we will try two options, either we will take it, we will not take it, we will either take it, then I followed my mother's advice, I did not take this, mother, it's okay, look, you can make the entire tray time, I will make whatever suitable tree diagram to shorten it. I am going there, okay, because of my mother, if I did not take it, then there will be no update in Max and Max. Maximum will still remain 'Tu Ka Tu' and the Maximum will still remain 'Tu Ka Tu' and the Maximum will still remain 'Tu Ka Tu' and the value of Tapa will still remain one because I have not taken this also, I have not taken this either. Didn't even take this one, took this one, okay now look, I came here, okay, still you are Maximum, right, and look at this one, you are the first guy, so is his floor banda bigger than Maximum, not at all big, okay, not big at all Okay, let's go, that means now we can flood further, so here also there are two options, will we take it or not, so this time no, I am late in taking it, mother took it, I took it, okay OnePlus One, you are okay, now if I take it If I have taken it then I will have to update it means we have taken it, we have opened this type, what will happen after opening it, look at it will get wet till the maximum range, okay, so maximum I have updated it, look here. And science, we have opened a type here also, OnePlus One, look at two type A, mine is ok till now it is clear, now look, now I have come here, A has gone, now let's see what is its duty, it is not from 3x at all. Neither is it overlapping nor see, this banda could have wet even four and this is 3, which if the story had started here in the middle, this too would have got wet, then it means that we have not left any part of the garden, okay, that was good. Then we will try two options here, take this, do not take this, I did not take this because of my mother, it is okay, it means I give you greater, give equal, you give color, sorry, the name of this factor, we just have to see that brother, have we soaked all the gardens or not? It's okay, even if we do n't find all the gardens, we would have returned to the story midway. Remember, every time they used to check Banda first, Max would have returned from there itself, if we had reached the end, that is. There are chances that we might have soaked the entire garden, but since you have already spoken, you know what needs to be checked. Now brother Max, what is it is cool, be greater, give equal, remember the point of this last garden. What was the point of the last garden, whatever was the value of N? What is the number of points of the garden from zero to the end? What is the last point of the garden? N is so you know what I will just check here if max and which is there. If he gives a greater, then the last point of equal to you garden, what does it mean that brother, it is not necessary for us to open any other type, it means that we have soaked the entire garden and it is not necessary to open any other type, return it to zero, we thought it was ok. There are two types and nothing else, turn 0 from here and if this does not happen, it means we have gone out of bounds and we have not completed the entire garden, give max and greater, if you are not able to do it then brother, we will tell you. Brother, no, it is possible that the whole flower is not there, you may not be there, then I will send infinity, if it is not infinity, then I will send a very big value, I will send nine to the power of 10, meaning what is it that it is not possible, no, I will send the biggest value, I will say no. It will be possible brother, if you can't then this was how the base was which was most important. This was how the base was which was most important. Rest can be measured simply. There are two options for every type for every tap. So now if we see then what is its code. How to make it simple, how is this my base? Okay, so remember, first of all, you used to check that brother can flood further, otherwise, remember, how do you check that I am standing on GI, if its first banda is taken out big. My last one's Max and means brother, there is an empty part in the middle, the part in the middle will not be able to be a garden, no water is put in it has dried up, you should understand this very well, this is why I told you. So at this moment I know what I will do, I will return to infinity here also, I will tell you brother, it will not be possible to complete the entire garden, it is okay because we are sorting, shortening and this is the condition. Brother, you will not be able to complete the entire garden by sitting, okay, this thing is clear and if it was not then what would I have done, just two options, either you go, open the note, do not open the type, then just solve it. Two i plus one and what will be the max, it will remain the same as it was because if we did not open the current then the maximum will remain the same, what is the other option brother, open it up, then how much heat is opened, one type. Opened One Plus, solve the rest further and bring i+1 and now look, pay attention, here the max i+1 and now look, pay attention, here the max i+1 and now look, pay attention, here the max will change further, remember how the maximum was calculated, the maximum of which is already the maximum, till now the comma which is my current range gets updated. It will be fine and what will we have to return in the last so that the minimum is reached, I noticed that okay, we will take the map, two things are changing, what is changing is that the index which is there will be stored like this in the last time i.e. the stored like this in the last time i.e. the stored like this in the last time i.e. the map actually. rangers.size i plus range of i ok and push back the range which we are making here into the range vector, push back and then we will sort it also, remember what I said about sorting. Will put start comma and ka foot dal given ok after that start two shots brinjal and extra are not doing inter result is equal you do a simple solve function tomorrow we will not be able to do -1 in money if not be able to do -1 in money if not be able to do -1 in money if it is not so then We will return the result. Okay, that means I am saying that if there is infinity in the result from here, then what does it mean? I am trying to tell you that you will not be able to complete this then we will attend minus one and now there is no infinity. So whatever value of the result they will return, okay now it is simple to write your solve function and i in max and what else is brother vector of par range ok now see I had said that if this i &gt;= now see I had said that if this i &gt;= now see I had said that if this i &gt;= size Gone means out of is closed, it is a good thing, but check here if max and greater are equal then you are fine. Reached the last point of the garden means they are happy. Now we have to open any other type, it is not necessary, then zero is required. And if it is not so, then brother return internet is fine, internet is not sending because look, OnePlus will also do it, if you go ahead then if you do international plus one then it will go out of bounds, that is why I have sent a very big value, power nine of the tank, okay. Meaning, what is the issue that a bigger value has to be sent, I write the bigger value, ok, let's remember after this, what do you always check first, brother, the first value of the range of I on which I am standing, if given greater, is taken out from the max. No, it means there is a gap in between, he could not give water to it, then return the same big value, power of speech is 9, okay, till now it is clear, now there is a simple rickshaw i.e. if the note is open tap, if tap is not opened rickshaw i.e. if the note is open tap, if tap is not opened and Sent the range because we did not select the tap ok and did not open it to the type and if we opened it to up ok then opened one type then made it one plus and after solving it i plus one now see max and change will happen Neither the maximum nor the second value of the range of I is clear till now and what to return for the last minute, the minimum of note, the value which came by typing open and the value which came by typing open, please give me the minimum from Indore. Okay, now I have done everything, but look at one thing here, a small type has been done here, remember the minimum of N used to be there, I plus Ranjit I, whichever of the two becomes minimum, okay see, first with the example test. Let's see if we pass the exam test, then we will submit it and see, if the match comes then we will memorize it. It's okay, it's late that we have passed the exam, but this time limit will definitely give us one thing. It's okay because there are two options for each type. Now let's start this, I had said that I will map the foot off and comma and take this foot of incoming to do voice, this will be I and this will be max and it will be okay and the spawning what is the result my store Tha MP is ok so before doing everything I will check return first that if in MP find MPRUT already this par is stored i comma max and ka is even clear and if not then there is no problem to return in the last Will send it here before the exam and what is ok first let's see the exam. We have done it easily and should pass. I hope you have got a lot of help. Any doubt? Resident comment area Ultra C Vaidya Next Video Thank you.
Minimum Number of Taps to Open to Water a Garden
sum-of-floored-pairs
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open. Return _the minimum number of taps_ that should be open to water the whole garden, If the garden cannot be watered return **\-1**. **Example 1:** **Input:** n = 5, ranges = \[3,4,1,1,0,0\] **Output:** 1 **Explanation:** The tap at point 0 can cover the interval \[-3,3\] The tap at point 1 can cover the interval \[-3,5\] The tap at point 2 can cover the interval \[1,3\] The tap at point 3 can cover the interval \[2,4\] The tap at point 4 can cover the interval \[4,4\] The tap at point 5 can cover the interval \[5,5\] Opening Only the second tap will water the whole garden \[0,5\] **Example 2:** **Input:** n = 3, ranges = \[0,0,0,0\] **Output:** -1 **Explanation:** Even if you activate all the four taps you cannot water the whole garden. **Constraints:** * `1 <= n <= 104` * `ranges.length == n + 1` * `0 <= ranges[i] <= 100`
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Array,Math,Binary Search,Prefix Sum
Hard
null
1,636
okay so let's try the next coding Excel file so open the and go to the file so open the and go to the file so open the and go to the problems tab and in the search question number 1636 and you will find this question sort array and increasing on it is also under the HD category so click on it okay so let's see the option given an array of integer number so we have some array is given sort the array in increasing order but based on the frequency of the values we need to sort this array on the increasing order so it doesn't mean like one two three is the increasing order or one two three no based upon the frequency of the values we need to sort so as an example so one come two times two come three times three come one time so let's took this array so let's put sorry let's do this array so one come two times right and 2 comes three times and three comes one times so we need to sort based upon the frequency so who has the like lowest frequency so 3 has the lowest frequency then one has the lowest you can see then one comma one then 2 has the frequency 2 comma two so this is our like output array okay so we need to sort our input array based upon the frequency okay so let's uh see other value if multiple values have the same frequency then sort them in decreasing order so like in this case all have the different frequency so this has one frequency this has two this is three but like if there is some example as an example if we took this example go to this example then in this case 2 comes two times three comes two times one come one time so we know we need to best uh like we need to sort based on the frequency so first one will come because it has the less frequency then what should we put whether we put two or whether we put three because both have the same frequency so in this case they have mentioned if both have the same frequency then sort them increasing order decreasing water means uh like so first three will come and then 2 will come if it has the same frequency then we will have to sort based upon the and decreasing order all right otherwise if they have the different frequency we need to sort like based on the frequency so let's break this question okay so to even sort this we need two we need to like sort based on the frequency so first we should know the frequency of all the elements so to find the frequency of the all the elements we need some like dictionary and we will iterate over the array and we will find the uh number count so let's calculate the frequency okay so num counts so there is some empty dictionary then for number in nums num counts of num is equal to num counts dot get num comma zero plus one so just print it print off num codes let's try to run it so this is not like the question is still like about a sold but we are like trying to see whether whatever the logic we have right here is this working or not like uh because to sort or sort our array we need two sort on based on the frequency so first we need to calculate the frequency so till this point we have just calculated the frequency we have not sorted it so let's find out whether we have like a calculator the correct frequency or not so let's see so one has two frequency two has three frequency three has one frequency which is fine let's see the case two has two frequency three has two frequency one has one frequency which is also fine so minus one has one uh one has two one has uh one has three one okay so basically like we have sorted so our we have the frequency like a hash map is perfectly correct okay so what next so now like we need to create some like output array and in the output array we need to sort we need to add the element based upon the frequency but like the output array like the dictionary which come so if you see the dictionary which come it doesn't like uh say because a 5 has one uh four has two so it is not in the sorted uh like the frequency is not in the sorted all right so first we need to sort the dictionary all right so let's sort the dictionary so sorted num counts okay so sorted is the inbuilt function so we need to sort the dictionary dot items because we need to sort of the key value okay so if we just do like this then what will be the output print sorted num counts let's try to run it okay so it says okay let's try to convert into dictionary as well predict of this uh no depict of this okay so we have uh here we have sorted based upon the ha so see if we just write this sorted so by default it gets sorted based upon the key so first you put one then it put two then it put three it has not sorted based on the frequency even if you see case two so first is one then it is two then it is three case three first is minus is because minus 6 is very simple then minus one then one four two but we want to sort based upon the frequency not based upon the key so what we need to do So within the sorted function there is a like if you need to like sort based upon some element we need to pass the key so let's pass the key so Lambda X colon X of 1 x of 1 means like because this dictionary has two value key this has this like dictionary will give us the Tuple key comma value and by default it is so if we did not provide any key by default it is sorting based upon the key but we need to sort based upon the frequency so this is zeroth Index this is zeros Index this is the first index so let's put this x this is X so how we are going to assess the value of 1 so X of 1 so input is X So based upon the x of 1 okay so let's try to see that what will be the output now it looks it's sorted based upon the frequency because uh one frequency which is the smallest frequency it converts first then uh the two frequency then the three frequency in the case two one frequency and then two frequency in the case three so one frequency then two frequency and three frequency which is perfectly fine but there is a one more condition it is mentioned if multiple values have the same frequency like in this case like in the case number two they have mentioned if the multiple values so these values have the same frequency the frequency it has two frequency three has three also two frequency then we need to sort based upon the decreasing order so basically three should come first and two should come after that because the decreasing will be three will come first and two will come last So within this like argument we have one more parameter this will not a parameter that is only the variable key only if like by default first it will check X over x01 means by default it will going to like a sort based on the frequency which is fine so but if what if the frequency will same then what will happen then it should sowed based upon the key but if we do like this by default it is going to sort in the increasing order but we need in the decreasing order let's try to earn it first uh something is wrong was never closed okay so sorted one bracket start items key Lambda X of 0 x of 1 and this is one more bracket yeah so let's try to write it so okay because it has different frequency so we can't uh figure it out because it never even went uh to X of 0 because if like the frequency is different it's just going to show it based upon the frequency so in this case like this output is okay in this case uh like this output is wrong because by default like we said if the frequency is same so in this case if we set it the frequency is same then it should sort based upon the key so it has sorted based upon the key and it is the increasing order because we have not mentioned reverse is equal to true and we can't mention reverse is equal to true because if we mention reverse is equal to true then the then this also is going to reverse uh like which we don't want then like this one also going to reverse which we don't want so what we can do is we will just put minus here we'll just put minus here so what it will do is when it found the same frequency then when it found same pregnancy then it will go to the second condition and the second condition is 2 and 3 then it is going to check two and three then I want three first and two second but by default it is going to like sort in the form of any increasing order so if I put minus 3 and minus 2 then minus 3 is smaller than the minus 2 then I just put minus three so I tell them if you get 2 then treat it as a minus two if you get three then treat it as a minus 3 then if I try to run it now you will find now I have sorted based upon the frequency as well so based upon the frequency because uh frequency and increasing orders of 1 then 2 and then 2 but if the frequency is same then the numbers are the decreasing order similarly case here so if the frequency is same so it has one frequency so if the frequency is same then it's in the decreasing order so 5 is faster than minus 1 and similarly for two and two so four five will come first and one then minuses and then three so first it will sort based upon the frequency if the frequency are same then it is going to sort based upon the key but the key should be decreasing order so we can put minus here okay so what next so once we have the key once we have this dictionary what we have to do we have to just iterate what we have what so this is the key so we want in the array so we want one three and two times one and three times two so that's it so we can what we can do is we can take a num's array all right so why I'm taking the number again so because of like uh we don't need to allocate some other memory it's already there and we are taking like initializing the same again all right now I need to just to run a loop so key comma count in protidanum dot items okay now what I have to do so I have to do nums is equal to nums plus nums Plus p star count or you can say is equal to nums Plus T star count all right so what uh why like what we are doing is so it will iterate over this dictionary okay so key is three right key is three so I need to append in my array but how many times I need to find that is the count so only one time I need to find so only one times I need two part then the key is one then how many times I need to open so one into one so basically but it will give like when I do one star two my output is one comma 1. right so when I do two star three my output is 2 comma two and num is the array so if we add two errors then it will be one comma two like this so we are doing the same thing and we have to return the nums so let's try to run it so now our sample KC has been receptive selected to some of it so our solution has been accepted and that's it so you can also try it's a great question and even though it's easy category but a little bit like this tricky part uh generally maybe being asked in the interview as well like if first we need to sort based upon the frequency which anyone can sort we can create a dictionary which easily we can create along with that we can use the sorted function or even you can use the sort function and by default it is sort based upon the keys which is fine but we need to based upon the value so that's why we are using the sorted function because we can pass the key argument and the key argument we can give the value but the second part says if the value is same then you need to sort based upon the decreasing order of the key so that's why we put the second condition as well once we get the sorted dictionary then we can just iterate and like put in our result in Array so that's it that's the end of the video uh thank you
Sort Array by Increasing Frequency
number-of-substrings-with-only-1s
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order. Return the _sorted array_. **Example 1:** **Input:** nums = \[1,1,2,2,2,3\] **Output:** \[3,1,1,2,2,2\] **Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. **Example 2:** **Input:** nums = \[2,3,1,3,2\] **Output:** \[1,3,3,2,2\] **Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. **Example 3:** **Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\] **Output:** \[5,-1,4,4,-6,-6,1,1,1\] **Constraints:** * `1 <= nums.length <= 100` * `-100 <= nums[i] <= 100`
Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.
Math,String
Medium
1885,2186
77
Hello friends welcome to code Sutra in this video we'll be solving lead code program number 77 combinations and we solve similar problems in one of our recently concluded workshops and if you are someone who is interested in search workshops please do consider joining our telegram Channel and I have mentioned the link in the description in this problem we are given a value of N and we are given a value of K what is the end and what does K mean N means we have the combination we have these four numbers available from one till four we have these four numbers available and we have to form a combination of two numbers using these four numbers right and it is that we will not repeat for example 2 1 equals one two so we need not repeat if we have already formed this we need not repeat this combination or this combination is not also a valid combination that is the thing now if you are given this four numbers what are the combination of two numbers that is possible these are all the combinations that are possible and we have to return all of them now let's look at another example and draw some conclusion or observations out of this if you understand this example it will be very easy for you to understand the solution now we are given n is equal to 4 but in this case k is not equal to 2 but k equals 3. now let us look what are the different combinations that we can form now let's look at this problem and let us try to add one more number to it can we add one more number to this one two yes we can add what is that number we can add any number three and four let's add 3 let's add 4 this and this is done now to the same thing which is the next combination one three can we add any more number yes we can add F4 now this is done we are left with 1 4 can we add any more number to this no we cannot add similarly for 2 3 can we add any more number yes we can add and that will be 2 4. now we are done with this and for this number and this number we cannot add anything so this will be our final answer so essentially what we did let's take this simple example where n is equal to 4 and k equals 1 and this will be our answer because we can we have to choose only one number and we choose all the one numbers in the next step when K is equal to 2 what are we doing we are adding essentially all the possible numbers to this combination what we did was one two one three then one four that is what we did and similarly for this and this as well and we neglected those combination which is not possible so essentially what we are doing we have a bigger problem that is we want to form three numbers a combination of three numbers but can we reduce this to a sub problem yes we can reduce it to a sub problem how we can reduce it we will pick up a number first for say for example we picked up one now what is the sub problem get reduced to we no longer need to pick up from the entire array or the arraylist combination that is given to us we have to pick just from these two three four and our K will also reduce from its value right for example we have add this n is equal to 4 and we chose 1 as soon as we chose one we have this reduced and our value of K also radish now let's add the next number if we are adding the next number that is equal to 2 what is K become K get reduced to 1 again and we also will reduce this list to this so what we are essentially doing is we have a bigger problem and we are reducing the bigger problem into smaller problems and solving reducing the value of K at each step until we have k equals to 0 this will be our base case right this is when it comes to K now how do we go about this the only thing we have to do is keep track of the start and digit keep track of the starting number for example in this case we can add anything from 1 2 3 4 since rra is empty our answer is empty now as soon as we add say 2 can we add 1 to this it is not required right we will maintain since it is given in the question that will maintain this order or this and this needle not be produced once again just this has to be produced so we can maintain this order as well so once you have added two we can just conclude that we will add three and four or whatever numbers are further that and we will no longer add any number prior to that now let's understand this with the help of an example I have taken the same question and the same example where n is equal to 4 K is equal to 3 and start is equal to 0 which means we can add all of this when start is equal to 0 what are the options we have four options right I have written all the four option one option two option three and option four that is we have added one number to this as soon as we add one number to this does the value of n gate change no the value of n will remain the same all over now what happens to the value of K will get reduced by minus 1. if you look here the value of K get reduced by minus y but this is a quite tricky thing as soon as you add one now further we can add from the first Index this is the index that I am mentioning here similarly as soon as you add two we can start from the second index similarly when we have added three we can start from the third index and from the fourth index now if you go further down the load we cannot add anything so I haven't extended this path or this path now let's look at these two examples these two example right we have added one to our answer what is this answer we'll be sending an arraylist to this step and we'll be adding 1 to the terrorist now after we have added one to the arraylist now what are the chances we have two we have three and we have four let's our add all of them and we if you see here we have formed all the combination of two digits which will lead to three digits right here also one combination will be formed which cannot be formed so I have not written it as soon as you are done with all this option what is the value of K get reduced to 0 in the final step I have taken these three example I have just written these three examples and written in down here what is the extension of all three is we are just adding finally we have added these two digits and finally we are adding three and we are adding four now it is also way more important that you keep track of the flow of the arraylist right for example we sent an empty arraylist from the top what was added one was added 2 was added first and three was added one two three was added but can we use the same arraylist or we will be using a different arraylist for every path now we'll be using the same arraylist now if we want to use the save arraylist or the vector whatever I have to do say for example we have to come back here and again add 4 to this right so essentially what we will be doing to the previous step will be sending just one two and this one two will again add 1 4 to this and we have this sensor now if you go to one more previous step this will be removed as well as this will be removed now we just have one and three will be added and the combination 4 will be added so it is also important that as the arraylist flows from down top to bottom the data gets added and it is also important that when it goes up the data needs to be deleted whichever we added at each step needs to be deleted this is one option or we can form an arraylist at every step that is also possible but this is the better option because that will be a costly process to form an arraylist or a vector at every stage now let's look at the code the coding part is very simple let's have a helper class which will take care of this recursion what we will do with this helper class this takes the input of start and we have a value of n that never changes and we have K which reduces it every step and we have the list of integer or vector which will flow from top to bottom right now what is the case what is the base case is if K is equal to 0 we'll be adding it to our final answer which is a list of integer or vector now finally once we have added we have to return because we will need not add one more element once again now what we are doing here is we are adding all the element from the starting point till the ending point but I have changed the formula here a little bit why we saw in the case because if we are adding 1 4 is there a possibility that we can add anything again no right so that case is taken here with this formula and what we do we add the number I whichever is at the start until and then we change or call the function once again by increasing the value of I that is the start will be increased or changed to I plus 1 and the value of n remains same care get reduced by 1 and will be passing the same arraylist we are not changing we are passing the same arraylist and once we are done with this don't forget we have to remove that particular element which we added at the last right and now we have the complete function where we will be calling the helper class and will be returning the answer and there are a few problems that are similar to these problems one is lead code number problem number 46 39 and 491 and we have a telegram group where we'll be discussing about these problems and I have mentioned in the link in the description so do consider joining the telegram group thank you please do like share and subscribe
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
416
Everyone welcome to my channel but missing discussion problem list dot this 416 partition equal subsidy even perfume increase problem I will highly recommend you to watch this video you submit committee's after disaster 232 jag milk solution of this point pure account statement give in Theory Names Containing Only Positive Integers Find A Way There Can Be A Politician * Saturday At The Sum Of Elements Politician * Saturday At The Sum Of Elements Politician * Saturday At The Sum Of Elements In Both Subjects Are Equal To Here Each One Example 1371 511 5 Only Letters Written In History Records Which Can Be Divided Into Two Parts In The Quantum of 11th 12th part 150 gm Paneer where you can be divided into two parts and 1000 v 500 600 800 60 divided into two to return for example and try to understand a give the total two a plus 11.52 divided into two parts plus 11.52 divided into two parts plus 11.52 divided into two parts in one single Point will have 11-11-11 in one single Point will have 11-11-11 in one single Point will have 11-11-11 total no ki no issue check here another area have taken here the total swami is 11th the effective best way to me cod bo2 path din Tubelight 5.5 834 note interior is it din Tubelight 5.5 834 note interior is it din Tubelight 5.5 834 note interior is it is not possible 54934 first chakra vishuddha is the Total form of this element is this number and not involved in deposit part 2 and day they can proceed for this problem which is the first one and the same numbers should be even nine if taken second and total evening is 21 that means coimbatore divided Into Two Part 111 Dhananjay Patil hits 150 cm The Total Are Now Look Amazingly This Puri Can Find The These are out of It I Can Develop Your Not Means Just Exam Numbers From Another Day They Can Form Will Not Doing Right and This Exactly This subject time is equal to two key problem hair's you can imagine this 1150 there is an English behind it 11:00 icon for more note is an English behind it 11:00 icon for more note is an English behind it 11:00 icon for more note commerce subject big near the numbers person just pass delivery in to-do list person just pass delivery in to-do list person just pass delivery in to-do list numbers and a little while solution situation related Anshul Yadav Find explain for decide review that problem they need to pass the are and obscene what they are expecting from other cities happiness pass the total sum way to 98100 but pass in this function and midwaying to do you don't know you agree with check oil dedicate the Previous solution in this function variety pass the examiner song so what if he does not have to first check the front 100 units and then Samveda wrist wearable day oil check ipsum model of 280 and not mean that you will not listed in the name passing in This Function The Amazing December 2004 Justification During This Not Present To Not All Set To Return Forms Vikas Dasham Is Not Even Day Vikrant Famous Father Newborn Submit It's Working Thanks For Boys That A
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
977
hey guys welcome to a new video in today's video we're going to look at the lead code problem and the problem's name is square software sorted array in this question we're given our integer already num sorted in ascending order and return the array of the squares in the ascending order so this is the input nums given to us we Square all the elements and return its result in sorted order so let's take a look at the example one and see how this can be solved you know often time so let's take a look at the example one I've drawn the same example here so we have the input array nums which consists of elements sorted in ascending order we are going to use the two pointer approach to solve this question the first pointer will be starting at the left index position pointing at the beginning of the array and I'm going to create the second pointer right pointing at the end of the array now let's find out the element square at left so minus 4 into minus 4 is 16 10 into 10 is 100 so I've created a result array so among this right square is greater so add that element at the end of the array so initially I'm going to use a pointer I it will point at the end and I'll add the greater of the two squares at the end of the array and then decrement I so the next output will be pointed here and now because we already squared the element at the right index position we decrement right so right will now Point here and left will remain at the same position Now find the squares at the left and X position and right index position elements left index position is 16 and right index position is 3 into 3 9 among the two left square is greater so add that element at I so 16 will be added here and because we process the element at left we increment left by 1 and right will remain the same now let's continue to find the squares left square is equal to minus 1 into minus 1 it will become 1. right square is equal to 3 into 3 which is 9 among the 2 right is greater add that element at the new i u i will be pointing here right so add it here and decrement I for the next insertion since we process the element at right decrement right and left will remain the same now let's find out the squares at left and right left is equal to minus 1 into minus 1 which is equal to 1 right is equal to 0 into 0 which is equal to 0 among the two left square is greater so add the element at left at I and decrement I for the next insertion since we process the element at left increment left now left square is equal to 0 and right square is equal to zero so the else condition passes so we add right square at I and then decrement I as soon as I goes out of Bounds at the leftmost index it means that we have filled the result output so we return this result array as the output now let's code it up and then I'll do a dry run again for the second example so coming to the function this is the function name and this is the input array Norms given to us and we need to return an integer array so let's declare the integer array first I'm going to name it result the result array is also going to be of the length of the input RN ohms now let's declare the two pointers left and right left is pointing at the beginning and right is pointing at the end of the array now let's use a for Loop which will iterate according to the length of the result array pointing from the end so the I inside this for Loop is going to represent the element being added at the index position inside result so we are iterating from the end of the result till the beginning and once you reach the beginning of the result array it means all the elements have been sorted and we can return the output so inside this for Loop let us find the left square and right Square so left square is going to be inside nums pointing at left into the same element and now we find the right Square we Square the element at right index by multiplying the same element twice so if left square is greater than right Square we add left square at the end of the result array I will be pointing at the end of the result array so result of I is equal to left Square and now we can increment left because we already processed that element and in the else block which means that if left square is equal to right square or if right square is greater than left Square we place right square at result of I and decrement right because you already processed that helmet so we move on to the next right element now outside this for Loop which means that we reach the beginning of the result array and all the elements have been added into the result so we can return the result as out now let's run the code the test cases are running let's submit the code there you have it a solution has been accepted the time complexity of this approach is O of n because we are iterating through the result array from end to beginning so it will process all the elements and then denotes the length of the nums array or the result array as both are same and the space complexity is of 1 because we are not using any extra space and generally you don't count the result array which is the return type as the space so of one is the space complexity now let's do the dry run for example two so I've created the result array knowledge declares the two pointers left and right left will be pointing at the beginning and right will be pointing at the end now I will be pointing at the end of the result array left square and right Square left square is equal to 49 right Square equal to 121 right square is greater so it will go into the else block and add right square at end of the result array 121 will be added here and then we decrement right so right will be pointing here and then we decrement I now we find the left square and light Square left Square remains 49 and right Square becomes 9 because 3 into 3 equal to 9 now left square is greater so we add the left Square 49 at I and then increment left and then decrement type for the next iteration Now find out left Square left square is minus 3 into minus 3 which is 9 and write Square 3 into 3 9 both are same so else block will be executed because for if clock to be executed left Square should be greater than right Square so at the right Square which is 9 and increment right and decrement right the next iteration left square is equal to 3 minus 3 into minus 39 right square is equal to into two four left square is greater so add left Square which is 9 and increment left and decrement I now find left Square 2 into 2 is equal to 4. right Square also 2 into 2 equal to 4 both are same so else block will be executed so at the right square decrement right and decrement I now I is equal to minus 1 and this condition will fail that I should be greater than equal to 0 which means that we crossed the left bound and all the elements inside result have been filled so you can return that as the output which is matching here so you come out of the for Loop and return whatever is inside result that's it guys thank you for watching and I'll see you in the next one
Squares of a Sorted Array
distinct-subsequences-ii
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
String,Dynamic Programming
Hard
2115
68
Hello everyone, welcome to my channel, so today we are going to do question number 68 of Let's Code, whose name is text justification. This question has been asked in Uber and Google. Okay, this question implementation is the best. There is no need to put any intion in it as it is said in the mains. In the question, we have to do the same, so let's see what is in the question and what we have to do, so we need to give some words and examples, mother, I wrote this word first, country here. Okay, if I try to write an example, I will not be able to see. Okay, so what is this, it should be left hand right justified, that is, how it should be, that is what is telling here, okay and then This is one more point but d last line of text it should be left justified and no extra space in certain between words ok so what is this is that in the last line there should be only left justified and not right justified so what is it? It means that mother, this is the justification in the end, it is okay from here, how many justices are these 1 2 3 4 5 6 7 8 9 10 11 12 13, okay 15 and 16 have gone back, okay mother, it would have been mother or two words, tea. Do n't turn it off, okay, this is the condition given to us only for the last line, so it is simple, we just have to follow this condition and write our code, it is true that there will be space in between in its space, three okay, meaning words - Out of three okay, meaning words - Out of three okay, meaning words - Out of all the words there will be one less word. Okay, so this is also done, now the first thing we will do is I remove it, so we have children and we have to do event distribution, then we have one less word out of how much gap is available. done we have so many gaps so let's make it again 123456789 10 11 12 13 14 15 16 ok now what do we have next example less than that tu gap run gap then what will we do example of daily justify us for the third line Have to go 10 11 12 13 14 15 16 Okay, if there is one word then zero cap means one mines, then this is all we have to do and simple, let me run more runs in this example, if I am late, then let's make it again. So you will understand again, then how did we get how big in this 1234 5678 910 10 words out of 16, we have filed 10 characters and out of these 6 children, we will see, how many gaps will be there, how many words will there be, what will we do, acknowledgment is one knowledge. Met is done, okay gap is two words, if there is one gap, then we had to justify retirement, okay, so we left all the gaps in it here, okay, so for this, we have only one request, we reduced it to zero, okay and then we If we create a line, then we will record as many retirements as we will fill, so what will we do in between the gap, we will remain the same, so I hope you have understood that it is simple, we just have to follow two-three steps simple, we just have to follow two-three steps simple, we just have to follow two-three steps and now I will give you the code. I understand how we will write this in the code, so let's go to the code, we are going to write its code, for how long will we run it, till we keep the word in which we use counter, it is simple, we can expand further, example, I told you, example, we Can't add, this look will be broken, so what were we doing for retirement, which were the remaining characters on the left, which were spaces, we were dividing them from those which were our spaces, okay, I told you one, if the space is zero. Let's go, how was our one, okay, then how will we handle it, if the space is zero, then what will we do, we will assign zero to it, okay, what was required, what will happen to it, then what will we do if we impose the condition if Mines is equal to one, okay, if it is not in the last, then what will we do, as much as our retirement was, which was our required retirement, okay, so we will set it here, then we will set more space in it as much as we have extras, okay and We have created till now in the extra so now what will we do if some space goes back then what will we do we will put a space there till then we will set it to ok then what will we do and we like here we want
Text Justification
text-justification
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. **Note:** * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`. * The input array `words` contains at least one word. **Example 1:** **Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16 **Output:** \[ "This is an ", "example of text ", "justification. " \] **Example 2:** **Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16 **Output:** \[ "What must be ", "acknowledgment ", "shall be " \] **Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. **Example 3:** **Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20 **Output:** \[ "Science is what we ", "understand well ", "enough to explain to ", "a computer. Art is ", "everything else we ", "do " \] **Constraints:** * `1 <= words.length <= 300` * `1 <= words[i].length <= 20` * `words[i]` consists of only English letters and symbols. * `1 <= maxWidth <= 100` * `words[i].length <= maxWidth`
null
Array,String,Simulation
Hard
1714,2260
906
So WhatsApp Web Big Ajit Mahajan End Welcome Back To Do YouTube Video Withdrawal Solving Till Now Number Nine Just Inserted Chords Super Palan Recent Visit Of Minutes And Shouldn't A I Late Say Possibilities Are Pig Palan Roo Acid Romantic Songs Play Open Loop Positivity End Represented in Tears Left and Right That They Also Given So Many Countries Set The Land of Blood and Writer of Tintin Beta Testing and in Teachers Recruitment for Maths and Power 800 Letters Video Examples to Understand Problem Statement Butter's Research Example2 Subscribe 100 Units Switch on the number to the number 90 subscribe that from today August 02 ok 24 all phone numbers and follow rooms and rest where to and friends ok soe this is the Number subscribe and subscribe the Channel for growth and Radhe every number industries which can directly and generate all parents to present in the trend video definitely famous fashion taking every number not behave new subscribe to the Page if you liked The Video then subscribe to the Page Apne Power Line With The Help Of Taking Two Years Into Account Cafe Zinda Research Anywhere Between Us But Even Smaller Sweater Solution Vikram And Optimizers Fennel To The Structure Of The Love You All Subscribe And Others 4884 Setting On This Subscribe Our Channel And Subscribe The Ok Should Support bhi to basic structure of any follow road which can generate condition only rostring david to make online directly something in the middle and even lord vishnu and so where given string to be stored in the power and tricks mobile number hai main to abhi extra bihar directly Generating Numbers From Want To Power In Which Are The Land Reforms Withdraw From One To Two The Number To Don't Have Enough To Take Into Consideration Subscribe Our Channel Must Subscribe And Between The One A Purse Or Win A to J cigarette from one to the power for ok so after 10 point basically with synonyms for want to know subscribe Video to problems and converted into a terrible fix width to the number one to the and Jhalawar road to Sangam in this particular lutb school from Land Forms of December subscribe to the Page if you liked The Video then subscribe to The Amazing subscribe and subscribe the Channel Hon Singh Dodiya Doing and Posted by To is Just 2 and Similarly for 11.10 Justin is Just 2 and Similarly for 11.10 Justin is Just 2 and Similarly for 11.10 Justin Attemp Revolutionaries String and Taking 1000 Loot 10298 Jet Airways Pendant The Best Doctor subscribe The Road Different from others and subscribe Must subscribe button of numbers with synonyms and number 90 loot weeks dot yaar just wearing and sacrifice there lives in the sense of right and left ad mid life in the land cruiser subscribe and subscribe the Channel subscribe Video Ko Jo Half Ise Submitted Main India Set Saugandh And This Video Guys Like Button Comment Subscribe liked The Video then subscribe to the Page Ki A
Super Palindromes
walking-robot-simulation
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Array,Simulation
Medium
2178
1,379
hello friends so today in this video we're gonna discuss another problem from lead hood problem name find a corresponding node of a binary tree in a clone of that tree so what you are given in this problem is you are given two binary trees a original and a clone so both the binary trees are exactly the same but the problem is like because both of these trees are different it means that they require different memory allocation though both the trees are same but see if you like if you make two trees which are exactly same but they allocate different memories now because you have stored these trees differently in the memory so now there's a cloned tree and the original tree so you are given a reference to a target in the original tree so you are given a reference that i like i have a node or like i have a pointer which is pointing to a particular node inside the original tree which is given as a target so which is like a tree node pointer which is equal to target okay so now you have to find out that you have to find out the same node like so as you can see because both of the trees are same okay you have to find out the correspondingly same reference node in the cloned tree so as you can understand more with the example if you are given this as a like this is the original this is the clued tree you are given that my pointer is pointing towards this node so this node is corresponding to this node in the clone tree so you are given the address of this node and you have to return the address of this node okay i hope you get the point so you actually have to find out the same node address in the other tree okay so what you can simply do in this problem is because you do not know that this tree is some sort of binary tree because you're only given the reference or other point like an address to particular this node so what you can simply do it is because uh you can just do a dfs okay uh on this binary search okay so what you can do is just do a dfs on this binary tree and correspondingly do the same dfs on this clone key and whenever you reach the target node because you're doing the same dfs on both the trees simultaneously so when you hit this node in this tree you are simultaneously also hitting on this particular node so just save this particular node or address and that's done okay i can directly show the code part if you have any doubts i can also like free field to mention on the coin box i will help you to find out any if you have any problem so i have written down an okay function which is actually the recursive function to do the dfs on both the original and the clone tree so i have to actually send the original tree address the clone tree and the target value which we have to find out and have to return the answer which is a global like uh three node pointer which is actually store the corresponding address of the node in the clone tree so what i actually do in this okay function is i take the input off as the argument of the original tree the clone tree uh like three pointer and the target my base condition will be this is the base condition when my original pointer because i am iterating over this original tree pointer which is this original pointer is actually giving me the pointer i am currently on so in dfs what i can do i iterate over the current node and then go to left and right so if at any point i hit a null which means that i cannot go any further i will return at this point okay if at any point my original value the node i am on the original tree it matches the target tree it means that okay i am on the node which i am looking for so now see that same node in the cloned tree so i will mark the same node in the clone tree which is here in answer because there is only one target value i will not see that same target again so i will just take that clone particular pointer i am on and store that into that answered which is a global value okay if i do not hit that point what i'll do i'll recursively call this ok function again for the left side and for the right side so what you can see here is when i go to the left side from the original tree as you can see i'll simultaneously also call this left pointer on the clone tree okay and same will do for the right pointer on the original tree so i will also go to the right side on the clone tray so it means that i am iterating over the or like i'm doing a recursive call on the clone tree and the original tree on this and like at the same time because when i'm calling the original tree for the left side i'm also calling the clone tree for the left side so it is like iterating over both the point at the same time and whenever i find out that i am on the target value on the original tree i will be also simultaneously on the cloned tree like same node value so i will now store the address of that clone value in answer and then in the end we have to turn on the answer one i have understand so it's just a basic dfs problem on the binary tree if you understand the basic dfs recursive call you can easily write down this function and whenever you hit the target value you can return otherwise i hope you get the point and intuition and the word for this problem if you have any doubts you can mention down i will see you in the next one until then keep quoting and bye
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
reconstruct-a-2-row-binary-matrix
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree. **Example 1:** **Input:** tree = \[7,4,3,null,null,6,19\], target = 3 **Output:** 3 **Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. **Example 2:** **Input:** tree = \[7\], target = 7 **Output:** 7 **Example 3:** **Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4 **Output:** 4 **Constraints:** * The number of nodes in the `tree` is in the range `[1, 104]`. * The values of the nodes of the `tree` are unique. * `target` node is a node from the `original` tree and is not `null`. **Follow up:** Could you solve the problem if repeated values on the tree are allowed?
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Array,Greedy,Matrix
Medium
1711
35
hello everyone my name is daryl i work as a software developer and in this video you'll see how i naturally work through elite code challenge this is a problem that i'm seeing for the first time and i'll explain myself as i work through it my solution won't likely be the best or most efficient it'll be the one that i come up with first so this problem is another easier one it's called search insert position so let's read through it given assorted array of distinct integers and a target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with o log n runtime complexity so let's look at the examples here so the first example we have one three five six and the target is five the output is two here we have one three five six the target is two the output is one so in this one the five is actually in there and it's returning an output of two because that's the position it should be in and it's also the position that it's in this one the target is two and if there was a two in there it would be inserted at slot one then we have one three five six target is seven it would be put in four which would be here 0 would be at 0 and this one yep so we have that the length is going to be between 1 and a thousand here we have nums is going to be between one and ten thousand and each value could be up to well could be negative ten thousand to ten thousand nums contains distinct values sorted in descending order and the target will be in the same range all right let's copy this over and we will start working on this one so we're given the int array and the target yeah that's pretty simple and we're just returning it in so to get all login it should be pretty simple what i'm planning on doing is simply looping through this array checking what the current value is checking what the next value is if the next value is equal to our target then we'll return its index if the value that we have that where our target is in between this one and the next one then you'll also return the next index and that will be old login let's get started on that we're gonna have the index value in nums with index one thing that we're going to need to do here real quick for the case is where it needs to be zero because it's not going to work with the quick little algorithm i'm going to do we'll just do a check to say if target is less than or equal to since we know this is going to be ascending we can do this nums zero returns 0. and then now we know that's not the case when we get in here just do if target is less than or equal to value not value nums index plus one so if the target is less than or equal to the next value x plus one and i'm going to rename this to underscore since we don't use it because i believe at this point we just need to do that and one more thing we need to do so if it gets through this and still hasn't found a spot we just need to return numbs.size numbs.size numbs.size because that means it needs to be put at the end so let's try this and see how that works out so the example worked let's go ahead and submit okay randex out of bound exception it's checking too much okay so let's say if nums dot size is greater than or equal to index plus two and i'm saying index plus two because index plus one would get the position if we weren't considering the first one to be zero so if we were at three as the index then we're saying is the size of nums three plus one which is the four which is the actual length plus another one so let's try that run the example again and submit all right there we go success so this one is slightly better than average with the runtime and it's a bit better than average on the memory usage awesome that was pretty easy so let's go ahead and go over the code real quick so first we're just checking if the target value is less than or equal to the first value in the int array if it is then we're going to go ahead and return 0 because we know it has to be the first starting position otherwise we're going to go ahead and loop through with the index and we're going to be checking first this is what we had to add to correct our issue we're going to check if there is a next value in the array that we need to check because if we're at the last one if we're at the last index we don't want to do this check because we're going to get array out of bounds when we do this so we're making sure we're not going to get an array out of bounds then we check if our target value is less than or equal to the next value in the int array because if it is we want to return that index the next index if this goes through and it goes all the way to the end then we know we need to return nums.size then we know we need to return nums.size then we know we need to return nums.size because that's going to be equal to the next index that would be after the last one alright thank you for watching hope that helped you guys out catch you guys next time
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
946
hi guys good morning so this video is your problem valid stack sequences although it's a pretty easy problem if you have watched are the problems of Stack which you have did in the last two three lectures then it will be very easy for you to solve it but in this video I'm going to show you as we saw okay to solve the problem of Stack we can have multiple options vectors dqs also like vector if it's off strings then we also use strings maybe also you can use arrays and for array you need pointers to actually pop and push that's the same thing via which you can actually optimize this thing although you might have included it and it's pretty easy I'll highly recommend you implement that same thing with stack and whatever you know so far but in this video I'm going to show you the special trick so in this video we're gonna see two main approaches to solve this problem but if you have watched the last two videos then it would be very easy for you to actually understand it or maybe attempted by yourself also so yeah before further Ado let's start with this problem it states that okay uh we are having two integer arrays called as pushed and popped each with distinct values please mark this word distinct values which means the numbers in that are distinct they are not repeating right cool if you have to return a true if this could have been the result of a sequence of a push and population on an initially empty stack or we can also see vice versa if we apply some portion population on these two stack so it should become empty so basically push and pop Operation Push we are having okay pop we are having we have to apply these operation and make a stack empty that is what our aim is cool uh or false if it can't become empty let's see the first example because see with the example itself we understand what we have to do now my operation is okay I have to push one then also parallel you have to think okay I also have to pop four but I also know one thing okay my values are distinct so if I have to pop 4 then I have as soon as the four comes I have to pop it right now I have to push one because see okay stack is empty right now I have to push one I'll push one but finally I'm thinking I have to pop four I have to perform I have to Puff four because as soon as let's say four comes and let's say you entered another element let's say five above it then no matter what you can't perform because the four will never come again it's the reason whenever the four will come you have to pop so you have to parallel think okay whenever the four comes I have to pop cool no worries but right now I have one so I just pushed it in my stack because operation on a stack so I just pushed one in my stack because four not yet received two pushed because four it's not four three pushed because it's not four first okay fourth push now but as soon as I found four I have to pop it because I know the values are distinct and the fourth would never ever come again after this thus I just pop my four and I'm good now the next element think of to pop S5 and can I see five so cool no worries I just pushed my next element okay not sorry oh it's five we have to pop five right just pop five no worries I just push my I just move my pointer J to next location because now I want to see for next because it is beam popped it is bean pop Knight next I have to think for three to being popped okay oh I can see my top is already a three I can just pop it down okay my face popped I can see the next element to pop is two and I can also see okay my stack top is two I can pop it's super fine my stack top is of the same element I can just pop it down one I can just pop it down oh it becomes empty what we wanted was nmt string we can say okay we are good to go um let's see another example to actually okay what we saw was actually right or not same in this case push four just pop it down cool now the stack is three uh and next element is three pop it for short just pop it next element is five is it uh top we had to right now so it's not we can't pop it so I'll just push the next element which is five in my start okay cool but now the next advice which need to be popped is five and also we had at top is as five so I just pop it down cool I had to pop a one at the top I have a two okay so I can't pop it but can I push anything else also because right now I'm not sure okay what is in the stack inside but yeah let's analyze okay if we can have something oh we can't have something right my push has become empty nothing will come forever I need to pop a one on my top it's two I can't pop it which means okay my operations are finished it's done but the stack has not become empty while we wanted the stack to become empty that's the same thing you have you just have to push your pushed array you have to push these elements in your stack and as soon as you find any element of the pop just have to keep popping because if you don't pop now swear you will never find that element again so it's the best chance okay just pop as soon as you see it that's the same thing which you have to implement via stack because it is it's legit saying push pop of a stack same apply same just what it is saying we'll just do the same thing exactly same thing I just use a stack to actually apply that pushing pop operation the pointer to actually move on to that my pop diary because you know okay I was just seeing okay it's four then I was just moving that my JJJ so that's okay I know okay it is being pumped now I have to pop this cool no worries then I just moved on my pushed array elements okay or gentlemen I need to push every time I'm just pushing the element no worries also I just check oh is the stack top actually equal to the element which needs to be popped if yes then what no worries just pop it down so I'll just pop it down and also I just need to worry about the next pop element so I just Implement by J pointer and for sure whenever we are about to pop in a queue or get a front in a queue so pop in a stack or get a front in a queue we just firstly check okay if that is not empty because if it is empty and will and still if we are pointing to this thing then it will give us another contraception and we don't want that so every time it's very standard that we just say okay if or why it is not empty then only we can actually uh ask for the top element and ultimately I just said it needs to become empty to actually return a true if it becomes empty only then I can return a true and that's pretty much it time is often space is off uh o of N and space is also open because we are just iterating on my whole push and pop diary and here we are using a stack so it's just open but as I said don't you think it's very easy and very normal don't you think like I'm just asking if you just know basic stack isn't it very easy it is right it's the same reason I just asked you how can you optimize it you will just see okay what Arya has told in the last video is that we that Stark is internally implemented as a vector right okay cool uh vector and array are kind of same it's just that okay in a vector I can do you see it's a vector then I can push an element in a vector and pop an element from the end of the vector but in an array I can't push an element by just adding a element in the end of the array but I can't pop the element out of the array right it is not an operation because R is based on index is right so if it's based on indexes okay when I say okay I have this particular area of infinite length let's say then I have to add an element so I just increment my pointer I then I just add my element here at this location if I just want to pop it why not agreement my pointer I to actually okay now I will just say although the element is right here but still I'll say okay now my pointer is up till here only and if it is my array if it is of infinite size let's say infinite sense 100 let's say but are required that says 90. then 1 2 3 4 now let's say I want to add an element so I will just add I'll increment my pointer and I will add a 5. it is how an operation is performed on an array now RN why I am thinking of an array here but you said that I need a vector and all that stuff see I said that we need to optimize this thing I am not saying to through the same thing in another form I'm saying to optimize this if I just use the vector again then still the space will be open because still it will be exactly the same as stack but if I use an array I know okay my pushed a input is actually an array what I can do is I can apply because I'm just iterating on those elements so I'm iterating from the start and going on so it's kind of okay I just need to think of it as an array I have been given now I just need to okay modify this and use this as a stack because I just want to optimize this thing I can't optimize this because ultimately I have to go on to every of the pushed and the popped element because ultimately I have to at least grab the input from my eyes but maybe I can just optimize this because it is using a stack extra thing which I'm being using so maybe I can optimize it maybe nothing shot maybe so it is the same thing we think okay so you are having an array we want to add an element we added this but let's say I wanted to remove an element you can't remove it at the mid location right so how about if I just remove my move my pointer back now I can just say Okay up till wherever my pointer is that is my array with this I'm although it is placed at this location but I'm not seeing it I am just saying okay I don't see it I only see up till this location where this we can actually trick us and this thing to actually think okay it's actually an back rather than a simple array let me show you how that's the firstly main thing that okay we just analyzed and use pointers to actually move in my array to actually replicate the same stuff as stack which means earlier what we were using in this particular thing if you saw we are using a stack push stack top stack pop the same thing I can just see as I said stack push stack is nothing but an array push is just pushing at a new index I plus pop is nothing but I minus top is nothing but value at I that's the same thing I did push which means I plus I just pushed and I just did a i plus now Pop a top element which is nothing but I minus 1 whereas as it's it was same as here also as I was saying okay if I had some element because I was I'm pushing it I and I'm doing IPS press so I has increased right now that's the reason I'm just grabbing my I minus 1 because I push that I not at I Plus 1. so and I has increased to I Plus 1. so I just need to do a i plus 1 minus 1 to actually reach back to I where actually is the push element so it's the top okay cool I just modified the exactly same code and here to pop is nothing but decreasing that I pointer and it's just doing a pop and for sure we have that base condition okay for sure you have to just make sure that as you made sure here also that your stack is having some size here your eyes should be more than zero because as soon as it goes less than zero you are screwed you can't access negative indexes it's not python so that's pretty much it okay Aryan uh you showed the code but I couldn't get it that how actually it is happening no worries let's see how it is happening as I said I just replicate the whole array because I am given this as an input I have to use this input as a stack itself and how we can use the stack by increasing and decreasing the pointers but it is already filled and we also can't um change the next locations I mean I can just do a pop from the left or a push it from the right I have to go my array from here only so yeah as soon as I obtain a one and for sure I'll just keep on checking okay if it is four as soon as the four counts I have to move my pointer back okay one comes my eye pointer moves next afterwards one is place I is initially here one is placed at this location I and then I has moved to I plus 1 as I showed you for the next upcoming thing I plus one as I showed you cool no worries then again a 2K I see what I'm doing is I'm iterating on my pushed array and the same pushed array is being replated as a stock okay cool then two came uh two I added at the location I and I is increased three came three hours at the location I and three is uh I pointer is increased four came four is added to the location I and I is increase which means as I show you the code I has increased so I minus 1 is nothing but four part of that J is 4 it is same I need to pop it how to pop it just move that I pointer back which means I pointer will move back which means actually now the array is up till here only it is just popped which means R is up to here now again I was it trading on this particular push pushed so my phone was done next element upcoming would be fine because see I was legit iterating on this particular array of push it is being done elderly so now I just have this array the element which is incoming which is five I just placed it at my location and I increase my pointer you saw what happened my array is changing and it is just reflecting the stack itself it is being done what is what it is but array it just got overridden by that four cool now I'll just say okay five I minus 1 it's also five just pop it which means decrease the eye pointer goes here I minus 1 3 j3 pop it which means degrees that I pointer I minus 1 to J2 pop it we decrease I pointer I minus 1 J 1 pop it decrease the eye pointer I zero J for sure has reached uh I zero which means oh which means I have completed my all the operations my it's completed it's done we have reached the end of the stack is empty we are good we are done it's the reason we can return a true you saw what happened time will for sure be open because you have to trade on the whole position pop diary but the space is just reduced to open because now you're losing no extra space no extra stack we are just modifying this particular input which is pushed although in the interview you will just have to mention to the interviewers okay it is not recommended in the production code to actually modify the input but you have to tell to interview that okay you know a technique to actually optimize the space and not seen to not tell it but ultimately when you just speak the whole thing just in the end let him or her know okay it is not the production recommended thing that you actually modify the input itself because this input it can be the downstream for many other resources if you just modify that stream then it's not recommended because you are using this but maybe some other controller the other division or some other thing is also using it so you like it's recommended to not modify the Upstream input but you have the particular approach to into the interviewer and that's how you just got the attention all the codes of two pointer as well as the stack for both the languages uh all the languages Java C plus and python is down below I hope that you guys liked it if yes then do the like button it helps motivates a lot although I can't reply to all the comments but I just put in the hearts to actually let you know I have a radio comment so yeah it's all from me and I hope that you guys liked it if yes then do the like button and see you next weekend goodbye take care
Validate Stack Sequences
smallest-range-ii
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Array,Math,Greedy,Sorting
Medium
null
169
everyone welcome back and let's write some more neat code today so today let's solve the problem majority element i probably should have solved this problem earlier but don't let the tag fool you it's easy because the simple solution is actually easy to implement but there is a follow-up that's not very easy to come a follow-up that's not very easy to come a follow-up that's not very easy to come up with so we're given an array of nums of size n and we want to return the majority element and the majority element is defined as being the element that appears in more than half of the array so for example we have four elements let's say we're given an array of four elements that means there's guaranteed to be a majority element an element that appears in more than half of the array so in this case there has to be an element let's say it's one that appears for three values in this array it could even appear in every single value possibly but not necessarily so we could have let's say a two in the last position so in this case we would return one as the majority element so the easy way to solve this problem is basically implement it as if we were finding the most common element in the input array but to actually solve the follow-up but to actually solve the follow-up but to actually solve the follow-up question we will have to leverage the fact that it's the majority element not just the most common element but for now let's focus on the simple solution we're given some values we want to know what's the most common value the best way to do that is to count the occurrences of each value what's the best data structure to do that sometimes you can use an array but if you're given arbitrary values like these values could be in any range let's say the best way to do it is with a hash map the reason we're using a hashmap is because we can have any key value we can use any integer that could be in the nums array as the key value and uh the value in this case is going to be the count of each number so n is going to be mapped to the count and we can do this operation any operation on a hashmap is an o of one time operation so uh we can count the occurrences of each value in big o of n time just by iterating through the entire input array but the downside is that the memory complexity is also going to be big o of n because we are using a data structure a hash map so this solution is pretty straight forward to code up if you're familiar with hash maps so let's get into it but let's keep in mind that there is a better solution which is also linear time but uses less memory okay let's code up the hash map solution first so let's create a hash map let's just call it count we're going to count the occurrences of each value and let's at the same time uh keep track of what the max value is so far so we're going to have a result variable which is going to keep track of whatever the max value is let's initially set it to zero and the max count of that result value and this result is really just the candidate we don't know that it is the result until we finally go through every single value in the input array so for n in nums so you can think of the result as like the candidate for being the result so for each value we want to update its count so this end value uh we want to increment its count by one so we can do that like this in python one plus whatever the current count happens to be if n has not already been inserted into our hashmap we can return a default value of 0 like this in python and possibly the count of this value could be bigger than our max count right now right if count is greater than our current max count then what do we want to do well we want to update the result we want to set the result equal to n because clearly its count is greater than our max count so then we can set it to n but if that's not the case if the max count is equal or even greater than the count of n then we can leave our result as it is currently so result can stay assigned to the result and similarly if we want to keep our result updated we should probably keep our max count updated as well the max count is always going to be the count of whatever the result happens to be because the max account is always going to be set to the max of the current count of whatever value we're looking at n and whatever the max count already was so that's the entire code last thing we have left to do is actually return whatever the result was and let's run it to make sure that it works and as you can see on the left it's pretty efficient but there is one improvement that we can make to our solution and that is uh getting rid of the hashmap and just so that you know it is kind of difficult to come up with this algorithm that i'm going to show you it's actually named after it's like an academic algorithm that's named after people boyer moore algorithm so don't feel too bad if you weren't able to come up with it yourself but it actually is very easy and simple to implement once you know it let's just take this array on the right what if we just tried to maintain one max and not use a hashmap would that work out for us well we'd look at the first value one so we've seen a single one so far so it's our max currently and then we see a two value so now there's a single two value so these two are tied for what the max is well two variables isn't so bad that's doable but there could be a ton of values in the input array next we see a two value so there are two values next we see a three so now we gotta start keeping track of threes because three might become the maximum now there's two threes in here so these two are tied for what the max is so maybe we're not even looking at the one anymore but then there's two more ones so there becomes three ones and then one becomes the maximum it's not possible if we're counting the occurrences of every single value to keep track of what the max is but the good thing here is we are guaranteed that there's going to be a majority element meaning that take this array for example there's gonna be a value that appears in more than half of the array so we could have four threes in an array of size seven and that fact that if that one number in here is going to appear in more than half of the array is essential for us to solve this problem in o of one space with linear time the idea that we're going to use is going to be similar to what i talked about a moment ago we are going to keep track of what the maximum is and we're going to do that with just a single variable so we're going to take the first element in this case it's a 2 so we're going to set our result equal to 2 and we're going to keep track of the count of what the result is so far we've only seen a single 2 so we're going to say our count is equal to 1. so next we visit the second value it's also a 2 so the obvious thing to do here is just to increment our count because the result is the exact same so now our count is going to be 2 same result next we see a 1 value so what's the intuitive thing to do here well this is the first one that we're seeing we don't necessarily know that but we know that our result currently is two it occurs two times the count of it is two so we might see a bunch more ones one might be the majority element how will we know that two is not the majority element anymore and it's been overtaken by some other number well we can every time we see a value that's not two that's not our current result we can decrement the count and once the count becomes zero and at that point we will know that maybe this is not the result because we've seen an equal number of twos as we've seen other numbers therefore it might not be the majority element and the important thing is what is going to be the result at the end of the array so let's continue with the algorithm for now if you don't quite understand it i think you will by the time we are finished with this so we see a one now we're going to decrement our count by one so now our account is going to go down to 1. we saw a value that wasn't the result now we see another one value so we're going to do the same thing decrement our count now to zero right at this point we don't know if this is actually the result anymore because the count of it is zero that means so far in the array at this point we've only seen four values but this is definitely not the majority element in the first four values but let's continue we don't know what's going to happen we see another one value well at this point we've seen more ones than we've seen twos and we kind of know that because our count right now is equal to zero so we can go ahead and decrement this by one again which will put us at negative one but that doesn't really tell us anything about this result that just tells us that this value occurs less than half of the time in the first five elements of the array because its count is negative one so a better thing to do would be to actually reassign the result so now the result is no longer going to be two because it's count is already zero and we found a value that's not equal to two we found a one so we're actually going to set the result now to be one and we're actually going to update the count now to be plus one so meaning this value one has a count of one and all that means is that this might be the majority element and right now we know that actually in the first five elements this is the majority element one is the majority element but you're probably wondering it could have been different right we only looked at the first five values so far two of them were twos three of them were ones but what if the last one over here wasn't actually a one what if it was actually a three right you might be thinking well isn't this algorithm wrong then because in that case our result our account would have still been one but our result actually would have been set to three and what if the algorithm stopped here what if these two values didn't actually exist then we would end up returning three as the majority element isn't that wrong well yes you're right that is wrong but what's also wrong is actually the input array take a look at this array we have a 2 a 1 and a 3. this array actually does not have a majority element right and that's what this algorithm depends on there has to be a majority element so you might have a lot of questions but trust me this algorithm does work and we'll explain a little bit more at the end so at this point we've reached uh this two value over here so what are we gonna do uh it's not equal to the result and our count is not zero at this point so what we're actually going to do is decrement this by one so now our account is to zero so what that tells us is this one does not occur a majority of the time in the first six elements next we see the last two and since our count is zero and the two values different from our current result we're actually going to update the result right now set it to two and increment the count and set that equal to one and at this point we have finished the entire array our result is two so we're going to end up returning to so we actually got the correct value that is the majority element in this array but you might just be wondering how exactly did it work it kind of feels like magic maybe there are some test cases where it won't work and i'll tell you that as long as the test cases are valid as long as there exists a majority element this is always going to work and if you have a hard time seeing why exactly that is try just taking this example array where two is the majority element and one is the non-majority but these ones could be the non-majority but these ones could be the non-majority but these ones could be anything it could be you know some value like three or it could even be multiple values or it could be a three a four or a five it could be anything but think about it like this you could rearrange these twos any way you want and the algorithm will still work you can try you could have alternating twos and then the non-majority element right something non-majority element right something non-majority element right something like this and in this case we'd say okay plus one to two minus one plus one right at that point we'd see two is the majority element it occurs a majority of the time we could swap these around we could front load the non-majority elements right we could the non-majority elements right we could the non-majority elements right we could have a one and then have some twos and we'd say okay minus two plus three because we know that the majority element occurs more often than the rest of the array combined right so we'd see that this is the majority you might start to see kind of why right this is the intuition behind it because it occurs more than half of the time that's very important that's why this algorithm works now let's code it up it's pretty easy to code so this is our original solution where we used extra memory and the hashmap but let's code up the more optimal solution we're going to be keeping track of two variables similarly as last time the result and the count we're not going to call it maxcount this time because it's gonna be going up and down but we are still gonna go through every single value in the input and remember to the count we are gonna increment it by one if the n value that we're looking at is the same as the result but we're gonna decrement it if it's not the same so we can use like a ternary operator at least in python it's nice and easy to write so we'll add one if n is equal to the result else we will add a negative one basically subtracting one from the count that's all we're doing with this line but what we remember is if the count is equal to zero which it actually is initially what we're going to do is set the end value to the result so if count is equal to zero then we're gonna set the result equal to n now we're doing it like this for two reasons one initially we set the result to zero right we're just doing that as a default value right we don't know what the actual result the actual majority element is gonna be so as soon as this loop executes it's gonna see that the count is zero so we're gonna set the first element equal to the majority element and after that the main algorithm is also going to start you know to execute it's going to count and then if we ever see that the count has gone down first it'll be it'll increment to positive one but if it ever gets back down to zero then again we're going to update the result and as i showed a moment ago we're pretty much guaranteed by the end of this that the majority element will be set to the result and that's what we can return so let's run it to make sure that it works and as you can see it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Majority Element
majority-element
Given an array `nums` of size `n`, return _the majority element_. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,2,1,1,1,2,2\] **Output:** 2 **Constraints:** * `n == nums.length` * `1 <= n <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
null
Array,Hash Table,Divide and Conquer,Sorting,Counting
Easy
229,1102
989
That Aapke Ajay Ko Hua Hai Hello Everyone Welcome to New Video in This Video By Going to Discuss the Problem 518 Form of the Problem Statement Problem Sahrdaya Just Right for Example Agar Na Dhan Na Refined Via Electricity Rates Subscribe in dark form is 20202 and we have how many thirty-four of one person so what do thirty-four of one person so what do thirty-four of one person so what do we have to do first of all we get this number if we convert it in village then subscribe our channel now how do we solve this problem they come to us And many people will try to convert it first of all that means convert it in school and then subscribe and our spend and after that we subscribe it again 1234 Okay so we move on to the constraint so the constraint is known to us and given the content. Which is ours, what can its length be? 10225, that means our video can be subscribed by the youth, they can click long and hard. If we have to work, then what will we do? If we are the ones who do school work, then this will not work for us here. Here we do not forget to subscribe village alternative and subscribe is to be activated. Okay, now what will we do here. If we talk to the people who add in this, we will write 1318. Do these two sides, if you want to run here and subscribe 560, then we can do that. First of all, which is ours - 110, we will add our given number, ours - 110, we will add our given number, ours - 110, we will add our given number, okay, so this is ours, now what will we do, we will take this, so make its meaning here, what will be the last date of the volume, if there will be one. We will store your answer here, if we are ready, it will come here. Now what we will do is divide it by this, add this number, so we will now have the schools here like in Play Store, divide it here and mix it. If we put a village here, we will put it here and join it, then we will take this and then we will add zero to the next one, then we will get 150. What will we get? If we take, then we will add here and divide. We will do this and we will take this and then as this is over and what we have is over then what will we do this we have this where we have to do here we have to take number nine okay now we What will we do now, we will put the first one of 998 128, from whom will we take the models, from whom will we get the tan, if we get it, then we will put it here in our final, we can put it in the beginning also, after that we can use it by subscribing. Or if we subscribe to it, then what will we do now by dividing this, we are like here, we are the ones who use it, we are here, we can do it and use it, okay now Village after village and we will add this mark here, this is our model of nine plus one, then what will we get, if we get it, then what should we do here and share, then where should we do not have anything, so unless we have Pass again subscribe your life and yourself and here we are with the one who will save us and whatever we do then what do we do then we take it first, if we take it then we would have got the benefit, again if we divide the tension then this one If it had been removed, then the torn bag would have been folded again, then we would have divided it with someone in Noida and if we had got the model here, what would we have done? First of all, we used to reverse 590. If something like this became ours, what would we do? So what do we do? First of all, first of all, we will find out our length, which will be our this and we will make it a variable in these instructions, so the intent, we will cut it with two na dot loops, we do, we We do, we will have to create, if we were appointed here, above, if we see what we have to do, we will have to create a list, play list, then we create a list that subscribe and if we have solution subscribe, we are accused that its size is not specified in advance. We will do this and this will be created with this type of ours, village is next, we will run our equal, now people, for how long should we run it, if the one who is watching our videos, then ours, subscribe to this channel of ours and there are other conditions along with it. And apart from this, there should be a condition that whatever number we are getting, we should get number we are getting, whatever number we are getting, we should get 100. Now inside this, we will be number one here, when ours which we have, that means this is what happened to our ghee. So, what will we do in that case, we are going to talk about it, whatever is our number, we will add it first, we will add it to this, meaning if we appoint, this is our Ghaghra number, this is our minus one, means it will work last. -If work last. -If work last. -If our ghagra is ours, our solution is ours, our village, ours and its models will be taken from the train and we will add this inside it, no issues, this is our ghagra, we will add this here, it is disgusting to use that ours. That is our name plus that the young man had run away. If we had taken then we would have divided in the last then this is ours if this is the second then inside this we are our solution. Inside that we will add 80 villages. We will keep doing it continuously and which is ours. That anger will be equal that our every bay divided by will come out so the slices will be equal to tension now as if our oil is finished then what will happen to us we will get our list now how our list if our 1234 then give us one then If we have to reverse it, then we will use collection to reverse it, then collection lottery will end like we do, after this our statement collection and inside this we will reverse it, subscribe, if we get our answer and we will return it, then we will return it. If you subscribe to this channel, then we will understand it through the example of our example in which our career will go forward in the last, then if we take the example of little knowledge and husband and simplicity and if we add to it So, first of all, our appointment is our nitin22 subscribe here, which is one of the two, this is ours but here, so what will we do with this solution dot, what will we add to our list which we have created, name not removed. Let's say that 9 plus 96 will be found in this, so we do this here - - - - Here we have started pointing this as if we will point at the first index. Now this is our first and quantum co same thing our cigarette daily 120 so what we have to do is not our 33033 so here what we will do is divide this and subscribe to our channel here we will take so now we What will we do, we will add to it, what is the neck time of what to do, like we have got the model state, we will do, we will divide the tan, we will become, and again this is our ghagra of a person - this is what we and again this is our ghagra of a person - this is what we do. We do, we do, it is not 90, our equal to zero should be broken, and what will be our final, what will go to 530, if we use it, then it will be more our gown, which we do, 3103 simple solution that For this, if we look at our time complexity, what will be the time complexity, then if we look at our K, our time complexity depends on two things, our time complexity depends on one thing, what if we are given a very large value of K, okay? So what do we have to do, whatever number of digits it has, at least this loop will run, so whatever our second tractor is, it will depend on our n, whatever our size is, so our time complexity will depend on it. But it will depend on two things, first of all it will depend on our N, so whatever will be the maximum of N and the flame of the log, why are we saying because our log is also of Stan, what does it give us, salary number of Units because if our number is 100 then its value will be three layer plus how many digits will be there in Vansh if there will be four digits then in this style we get the knowledge that the digit depends on the number of units and the number which is added after turning off the science of it. So it depends on how many sides we are making here, whatever will be ours, it will be locked because of the war which is on us and for this problem, we make it first of all which Ki Ko and our key size name dot length neck numerical strength will be made I which will be ours - One ours - One ours - One problem has to be made a list, okay so we will make a play list, it will be a to-do list, what will be its interface list, the reason for which From we have and by creating this and we click on this so we will do then we will leave this sexual subscribe - - - - subscribe - - - - subscribe - - - - - - - 0 happened because we have to consider the equal to case or if it is better than zero. What will we do with these two, what is ours, we will add to it, we will add it, we will not do it, we will subscribe and we will take the bell, what is ours, by what name is it and what will we do with it, we will divide it, okay. If it is ours then we will take the question and under what condition will this come under our Greater Dainik 2020 So we do, and whatever is ours, we will give it to everyone. This is our simple project, we will divide the bar tension, as if these people will end, we will make our return, we will return it, we will submit the solution in this way and see if there is any meaning in our court, we got the writ 6 for this, we are here to reverse the So let's use this, apart from this - - here use this, apart from this - - here use this, apart from this - - here this from here and this is the very last one like subscribe before that - - do this subscribe before that - - do this subscribe before that - - do this here because of this, if we do n't want it here only then what do we do here in the village to reverse 84 miss call Okay, now if we run it should run properly now. And this is our video. Now let's submit it and see. And this is our submit. Which is faster than more people. Subscribe to this. How to solve this problem? Thank you for watching my video
Add to Array-Form of Integer
largest-component-size-by-common-factor
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
Array,Math,Union Find
Hard
2276
1,717
hey everybody this is larry this is me going with q2 of the bi-weekly contest for 3's maximum score bi-weekly contest for 3's maximum score bi-weekly contest for 3's maximum score from removing substring so this one to be honest um during the contest when i solved it and you know you could watch me to stop it during the contest um and you could hit the like button hit the subscribe button join me on discord and ask me more about this question um to be honest i don't have a great proof with this problem um i just what i did during the contest was i looked at a few um possible things which is you know if you have b a or something like that well in this case you really have no choice which to go and of course if you have the opposite of that you also have no choice right so the only time you have a choice is if you have you know bab or bab and in this case you always want to do greedy by removing the one that costs the most um and because even if you have multiple even if you have four right here um you either do ba and like if ba is more expensive then you do the ba and then you do the ba right if a b is more expensive you do the ap and you still get the same um you get the same uh characters right so that's basically the idea that i have with respect to figuring out how to do greedy i wasn't able to prove it um like in a very definitive way but uh but that's basically the idea right um because like for example if you have something like this um you know if you could do ba or a b it's going to give you the same answer so if you're going to get the same uh answer um only on the only choice that you have then you might as well take the worst one um i got a wrong answer in this one because i did i was terrible and i um i did copy and paste what i should have done was um probably refactor this but this is the code that i have in the contest so basically i wrote if x is greater than y meaning that it makes sense to do uh a and a u then and b i basically just go through it and i remove all instances of a and then b by using a stack add to score if it's the other way around i also do it but you know during the ba and then i add this score y to the score and then at the very end i just go for it one more time to uh to remove any remaining a b's that are left in you know whenever is possible um and yeah and that's basically the idea of just greedy and as you can see i did a lot of copy and pasting here which ultimately cost me five minutes and penalties um because for some reason the system like this test i guess it just i don't know it was good enough for that um so i got a wrong answer because i didn't write stack 2 in some of these because i copy and paste um but yeah so the solution here is just greedy um you know whatever gives you more uh while you do that first and then after you do one pass of that do another pass where you try to remove anything if possible um and that's pretty much it um yeah and the reason why i kind of was let down this way during the contest was that um i saw the length and it's n and n is really big so i knew that this was going to have a linear time solution and because of that um i kind of figured out it was greedy just by guessing because it was not greedy and we need some way of doing uh more proof force it's gonna be at least n square and that's just too slow right um so that was my guess um yeah that's all i have for this problem um and yeah in linear time because we do two scans and we use you know stacks so that it you know just goes for a run of time uh so it's gonna be linear time in terms of space it's gonna be linear space because you know we have two stacks linear space that's all i have for this problem let me know what you think and you can watch me solve it live during the contest next enough any number of times um this feels like one of those greedy problems that is hard to prove hmm that's really annoying to prove this one okay don't let the body go like this oh now i wasn't confident about this one at all i just don't know how to do it otherwise uh okay um thirteen thousand okay mix up the signs oh that's weird x is greater than y is greater than x wait welcome just didn't happen oh that's just silly this is what happens when you copy and paste i knew i should refactor this into a function still may be wrong but maybe better oh hey uh thanks for watching uh this was a rough contest um for me uh just because i was being silly maybe i need more sleep but yeah hit the like button to subscribe and join me in discord and i will see y'all later bye
Maximum Score From Removing Substrings
minimum-cost-to-connect-two-groups-of-points
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Array,Dynamic Programming,Bit Manipulation,Matrix,Bitmask
Hard
null
295
welcome to july's leeco challenge today's problem is find median from data stream the median is the middle value of an ordered integer list if the size of the list is even there's no middle value and the median is the mean of two middle values for instance if we had an array of 2 3 4 the median is going to be 3 and if we had an array of 2 and 3 the median would be 2 plus 3 divided by 2.5 now we want to implement a median 2.5 now we want to implement a median 2.5 now we want to implement a median finder class which basically has two functions either add a number uh from the data stream to a data structure or find the median which returns the median of all the elements so far so they give you a bunch of follow-ups so they give you a bunch of follow-ups so they give you a bunch of follow-ups and stuff but let's ignore all that let's just think about what we would do if we had some sort of data stream like if we just had a bunch of numbers coming through into our data stream and we added it into like a list we would have to have it ordered to find the median right so there's no guarantee that all the data coming in is going to be ordered so we have to sort it each time but once we sort it becomes relatively easy to find the median all we have to do is if the length of it is odd we just take the middle value what we'll do is get the length and divide it by two and that's going to give us the middle value here now otherwise if we had even numbers like this what we do is get the b the middle index right here as well as the one i think maybe let's see this is four so we'd have to divide two so we could say minus one for one as well as uh and divide by two for the other one so we'd get these two so really the key thing here is how can we keep this list sorted each time uh because if we can sort our list in a very efficient manner then this would be relatively easy so the first approach i thought was we could use a sorted list what we can do is from sorted containers import a sorted list this is going to allow us to automatically keep our list sorted whenever we do an insert each insert takes log n if we did that everything else takes care of itself so what we'll do is initialize a let's call this array and we will start with a sorted list we'll also keep track of the length right here and this will be so that we don't have to calculate it every time now when we add a number all we have to do is say add num we'll increase our n by one here now it's just a matter of whether it's odd or even see if it's even uh we can do that by calculating the modular if this is even then what we'll have to do is uh return self.n uh we'll get i'm sorry self.a self.n uh we'll get i'm sorry self.a self.n uh we'll get i'm sorry self.a self dot n divided by two minus one and we'll do the same thing right here except without a minus one and we'll divide this by two otherwise if it's odd we just return self dot a self dot n divided by two and this should be it this would work um it looks like that's working let's go and submit it so you can see that adding this number takes log n while finding the median is basically one it's pretty much instant now this might work for a lee code problem but if you were in an interview they might not like this because you're kind of cheating by using an outside data structure they might not really like the fact that you just took advantage of this so what are some other ways what could we use like more traditional data structures to solve this well imagine that we had our sorted list right whatever 1 2 5 10 and then 16 and or 90 100 something like that one of the things we can realize is basically the only number we care about is the one right in the middle right we could split our list into two data structures one with the bottom half of the ordered list to be on a heap or rather a max heap we'll make this bottom half a max heap here and the top half will make that a min heap and that way what will happen is the max on the max heap the number on top is going to be the one right in the middle or the um number right on top of our min heap is going to be the one right at the bottom of our top list here and what happens is we just will keep the bottom half uh with one greater number we'll have this be like n plus one and this be n uh the way we can do that is say that we enter like some number 15. we'll first insert it we'll do a heat push onto our heap here what that's going to do is 15 is going to get on top right here right and after that what we'll do is take whatever the max number here is on our heap and push it back to this top half so now 15 gets popped off here and it's going to get put on here like this now at the end if we find that this top half of our heap is bigger than our small heap we're going to pop this back off and put it here just to keep that data structure intact here we can see it's both even so we'll just keep it and since the lengths of these are equal all we do is take the top of our heap on our bottom half that's 10 and then take the mac or the min off our min heap from the top half and that gives us 10 15 just divided by 2. now if we didn't have that 15 all we would do is take the number on our max heap on the bottom half and we'll just keep this you know at most n plus one greater than this the top half and that way yeah hopefully that gives you the idea of what we're doing here so let's have two heaps we're gonna have the bottom heap and we're gonna have our top key there's gonna be two lists now when we add what we do we have to do a heat push onto our self dot bottom first and what we'll have to do is since this is a maxi we're gonna have to make our number negative so we'll do negative num and after that we're gonna heat push onto the top half and we'll do a heat pop from our max heap here so this would be bottom and we have to revert that invert that back to negative so if we find at this point that the length of self.top is greater than the length of self.top is greater than the length of self.top is greater than the length of the self.bottom we're going to we of the self.bottom we're going to we of the self.bottom we're going to we push that back to the bottom here so we'll do keep push back onto the self dot bottom uh negative we'll have to make it negative again and keep pop from the self.top here pop from the self.top here pop from the self.top here now finding the median uh depends on whether the links are equal or not if that it's not equal length of self dot bottom does not equal length of self dot top that means this bottom one uh you know has one more so we can just return that whatever's on the max heap there so return self.bottom return self.bottom return self.bottom zero otherwise what we'll have to do is uh get both of these here bottom zero plus top zero and we have to divide it by two and this should work also so let's see if that's working oh okay i forgot because this is a we made it negative just adding these together won't work so i believe we're going to actually subtract here which actually is adding so that should work see this still says negative two which isn't right okay one more i forgot to make that a negative there we go so let's go and submit that again there we go so this is going to be also let's see since these are all he pushes this is all going to be log n and finding the median this would be one so this would also be the same time complexity uh it's just it's a little bit more complicated because we have two heaps but i think it's a lot more clever so i like this solution all right thanks for watching my channel remember do not trust me i know nothing
Find Median from Data Stream
find-median-from-data-stream
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. Implement the MedianFinder class: * `MedianFinder()` initializes the `MedianFinder` object. * `void addNum(int num)` adds the integer `num` from the data stream to the data structure. * `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input** \[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\] \[\[\], \[1\], \[2\], \[\], \[3\], \[\]\] **Output** \[null, null, null, 1.5, null, 2.0\] **Explanation** MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = \[1\] medianFinder.addNum(2); // arr = \[1, 2\] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr\[1, 2, 3\] medianFinder.findMedian(); // return 2.0 **Constraints:** * `-105 <= num <= 105` * There will be at least one element in the data structure before calling `findMedian`. * At most `5 * 104` calls will be made to `addNum` and `findMedian`. **Follow up:** * If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? * If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
null
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
480,1953,2207
342
Hello ga today starting with the question power of given an entry we have to return power of it we have to return false soir n e 16 we have given power of a solution question with help of Ratio so in ratio if we get n e 16 and any of the numbers f then power of f then if dividing the number with fo then getting one at the last like n e 16 di 4 e 4 de 4 di 4 ev Similarly 64/4 16 Then 64/4 16 Then 64/4 16 Then Similar Now If We Get N E 8 So 8 Di Ba 4 It Ch I Not Equal And We Also Be Returning False If A Becomes Let Us See The Code Of The Question So Here Is The Code Of The Question If n becomes lesson i 0 we are calling repeatedly for n ba 4 and if n becomes lesson i it 0 we have to return false if n becomes one then w to return true and if any of the number we would get that d model with Four da gav is not equal to zero that is not divisible by four has to return directly false so this is the question thank you
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
279
hey everyone today we'll be solving lead C problem number 279 perfect sares as for the problem statement we will be given an integer n and we have to return the least number of perfect square numbers that sum to n okay so let's firstly try to understand what is the perfect square here so any integer let's say any integer K that is the perfect square of an integer let's say k d into k d is equal to K in the that case this K is a perfect square let's say 2 into 2 = is a perfect square let's say 2 into 2 = is a perfect square let's say 2 into 2 = 4 is a perfect square so it is a it can be achieved by multiplying two same numbers okay so what we have to return here is we will be given a number n and we have to achieve this number how we have to achieve this number we have to achieve it by taking sum of perfect scares and that uh the number of perfect scare we are taking should be minimum let's firstly try to understand it using an example let's say we have Nal to 12 so we have to achieve 12 using perfect sares so what are the perfect sares here let's say we are starting with one so for the one we have one as a perfect square because one can be achieved by 1 into one if I say let's say for 2 into 2 we can achieve 4 is a perfect square for 3 into 3 is equal to 9 is a perfect square 4 into 4 16 these are the perfect square because a number multiplied with itself coming out to this number so these are our perfect square and we have to use these perfect squares to achieve our Target you can say and the N number so let's say here we have to uh achieve Nal 12 using our perfect square it can go up to infinity or you can say up to big number and let's say now have a look on these numbers how many numbers we have to pick to keep trying on this I think uh 16 I cannot pick because 16 is already greater than 12 using 16 I cannot achieve 12 so let's say I take 1 4 and 9 4 9 and 1 I have taken these as a perfect square and our n number is 12 already given in the problem statement now the problem statement has reduced to that we have to achieve this target using these numbers any number of time so these are the three numbers we can use any number of time to achieve this target if you might have remember uh these this is a similar kind of problem as a coin change problem so let's say if I if we consider that these are the coins 149 we have coins as 149 and we can use any coin infinite number of times and I have to achieve a Target equal to 12 okay so this has become a standard recursion problem that we are given some number of coins and we can use those coin infinite number of times to achieve a specific Target okay so initially it was like we have n and we have to find the sum of like find the least number of perfect square numbers that sum to n that is uh using these three coins we have to achieve Target such that the coins are minimum number of coins are least so let's uh if I check the possibility if I use one and then if I again use one 9 99 10 11 12 coming to four 12 if I use 4 3 are 12 this is coming to 12 here these are our possibilities and I see that this possibility is having a least number of coins or you can say least number of perfect sare so this is what is expected from this problem statement least number of perfect square that numbers uh perfect square numbers that sum to n this is we have to return and we just have to show tell them the number what is the number here our answer would be three in this case for Nal to 12 and this question has been asked in many companies like apple Yahoo Amazon Google Microsoft adobi Uber almost all the big tier one companies and this is also a very good question to grasp the essence of dynamic programming especially for beginners and if you are an expert but you can just have a look uh to the basic understanding like how do we approach dynic programming in general by not cramming anything okay so now it is clear to us that we firstly we uh we will be given n and we have to achieve n using perfect sares so first of all we will get all the perfect sare which are less than n so how do we do that uh for that we can simply write a loop for I equal to 1 we have to start from one and I into I is less than equal to n i ++ in this way we are going to get all ++ in this way we are going to get all ++ in this way we are going to get all the perfect square what is the perfect square here this is the perfect square now you can say perfect square let's say perfect square is in list do add I into I okay we have captured all the perfect sares now let's say we have a perfect square list and what is our Target here Target is equal to n we have to get the minimum number of perfect square such that we can achieve this target okay in short it is a minimization problem usually I get an idea of whether we have to do the minimization maximization and uh if a problem looks like a recursive problem in that case we generally use dynic programming so this is my in int intuition okay now let's come to the same example where we were having Nal 12 for Nal to 12 what are the perfect square I can use 1 I can use four and I can use 9 after 9 4 into 4 16 cannot use because 16 is more than 12 okay or instead of n you can call it Target here to make it more clear and the perfect square was 4149 and we can use 149 any number of time to achieve this target okay use 149 to achieve 12 and use the 149 any number of time to achieve 12 so this is our biggest problem is this now if I try to uh break this problem to one level what this would be that we have access to this coin only this coin can contribute to two situation in my answer either this coin will give the contribution to answer or this coin will not be giving contribution to the answer so this coin has only two possibilities either to contribute to my answer or not to contribute to my answer if it is contributing to my answer it means that we are contributing we are collecting this coin and then achieving rest of the target from remaining coins we have achieved uh like we have accepted this coin and we are achieving 11 with 149 remaining coins because one coin can be used any number of time that's why we are using 149 here okay the other possibility is that we are not considering this in my answer if we are not considering this in our answer in that case the other possibility will be we have to achieve 49 we have to achieve our Target 12 using coins 49 any number of times we have only these two possibilities right if it is not clear you can just rewind the video okay so among 149 for the contribution of one either it is giving contribution to the solution or it is not giving contribution to the solution if it is giving the contribution our Target is reducing to 11 from 12 and we can further use 149 coin if we are not at all considering this coin in that case we have to achieve our Target from remaining coins only so this is one step and the rest of the thing is a small smaller problem that is our sub problem so what is our sub problem so in this case the we have two possibility that we have achieved one now we have to achieve Target 11 with 1 4 and 9 this is one case and in this case we have to achieve our Target equal to 12 with 4 and 9 this is our bigger problem we have 1 149 as our coins we have to of 12 and our sub problems are these two are our sub problems we have to achieve this target using these coins and this target using these coins so bigger problem is getting break down to smaller problems and ultimately let's say I have this the this coin set and I have to achieve let's say 19 can I achieve this 19 using empty set no but how many coins do we need infinite number of coins this I can use as a terminating case or let's say if at any moment our Target is equal to zero in that case how many coins do we need further if Target is already zero we can return zero that zero number of coins we need further so these will be serving as a terminating case so okay so now I can D I can say confidently that this is a recursive solution because it was involving this um sub problems solving the sub problem first and then moving to the bigger problem and then we have our terminating cases so this is a pretty much a recursive problem so we can try to find firstly write the vanilla region for this problem and then later on we will see whether we can memorize our it or not so if I write a solution for that firstly let's say I have I'm having coins or you can say perfect scale list and the second thing is we have Target so in the coins list we have to uh consider all the coins let's say we are starting with zero coin and then we will be moving further so to track the index I'm using idx so what would be my recursive function look like solution of idx in the starting it is zero and the second thing is Target so in the starting what is the target is given to us in the form of n as for the problem statement let's say in for our problem where we have 149 and T = to 12 let's say I just write 12 T = to 12 let's say I just write 12 T = to 12 let's say I just write 12 here okay so what would be my uh terminating case here so first of all we have to see all the our positive case which is if Target is equal to Z how many coins do we need further we want only zero coins this is our terminating case now have a look on our negative case where the target is remaining and the uh this one is empty or the target has reduced from not to Zero from five it has reduced directly to minus 10 like this so if idx is equal to our PS do size perfect scar do size that is it is going out of bound or our Target value is less than zero so in that case what we have to return is we have to return plus infinity that is you will need infinite number of coins that is you cannot cannnot achieve this part now comes to the comes to our recursive call and here we saw that we have two recursive calls every step let's say we are start we are at idx step so we have two possibility either we are considering the element at I idx or we are not cons the element at idx so we will get coins from this and coins from this so if we are getting a coins from this coins is not getting considered so the number of coins let's say m is the number of coins M will be the answer one possible answer and the other one is let's say here from here we are getting uh P so p + 1 one is that we are getting uh P so p + 1 one is that we are getting uh P so p + 1 one is that we are we have considered one coin so p+ 1 are we have considered one coin so p+ 1 are we have considered one coin so p+ 1 or M let me write the code it will be more clear to you so what we have to return is we have two possibility either I consider this coin current coin if I'm considering current coin okay one coin I have already considered solution of idx and the target minus perfect square idx okay so this is one possibility that we have considered the current coin and the remaining part I'm expecting from my recursive call or the other part is we are not at all considering the current coin so in that case we are giving idx + one and case we are giving idx + one and case we are giving idx + one and expecting the same Target so the maximum of this two so the maximum of these two coins is my sorry not the maximum should be minimum the minimum of these two coins are my answer so let's say from one call we are getting let's say if we um so in this case we have 1 4 9 if we are considering one so from this call it will give me that 1 one if I consider 11 9 I will be able to achieve 12 9 + 1 + 1 9 I will be able to achieve 12 9 + 1 + 1 9 I will be able to achieve 12 9 + 1 + 1 + 1 I will be able to achieve 12 if we + 1 I will be able to achieve 12 if we + 1 I will be able to achieve 12 if we are not considering one we will be able to achieve 9 using 444 4 44 is one possibility so 444 is having three elements so this is going to be my answer so the maximum of this will be considered okay so let me just show you the whole code we have this solution index Target positive terminating case Negative Edge case and this is our recursive calls one possibility is this whole section and the other possibility is this so minimum number of coin so from Whenever Wherever We I will be getting minimum number of coins I'm directly going to return those so in this way so this concludes to my recursive call but here we have to keep in mind that 1 149 we have couple of coins and we can use these coins infinite number of times and we have to achieve a Target say at any moment I'm considering one three times then the state would be that I have to achieve Target minus 3 or I'm using one for four number of times so it would be like uh Target minus 4 and I have to achieve it using 1 4 9 and after that I'm skipping one skipping four and I'm just left with nine so the current state would be 9 and the target Min - 4 so this is one and the target Min - 4 so this is one and the target Min - 4 so this is one state and let's say the uh let's imagine some other state where we have considered skipped one directly and consider one for one number time we have considered four one number of time and then we have skipped four as well so what is our state Target minus 4 because we have considered four only here in this case we have considered this is the state we have considered and here this is the state we have considered and now our index coming here and I'm left with this as a perfect square so this can also be a state after some time so at this time we will be solving this state and then later on we will be getting this state so it means our sub problems are getting a duplicate call that is overlapping sub problems against the same value of index and the Target in this case what we are going to do is we will be memorizing our solution against this index and Target so for that we can just directly take 2D array of first to store index the second to store Target value and then we will check whether we have already cached it or not so just cached this value we have to Cache against these two values so in this way this is concluding our memorization so here first of all we understood that this is a decursive solution because we were having sub problems and the later on we did the memorization because we were having overlapping sub problems now leading to recursion with memorization solution or you can also say top down dynamic programming problem this should be your usual approach when you are appearing for interviews like Google or Amazon if you are able to solve this problem in this way to the interviewer he would be very impressed and he will definitely get a strong higher in that round okay let's try to code this out let's start writing the code for this first of all we will be requiring a list to store our perfect scares so list of integer let's call it PS list and let's initialize the PS list is equal to new array list now we have to store all the perfect scares for that I will be starting my loop from one I into I is less than equal to n and I ++ okay now what is a perfect square ++ okay now what is a perfect square ++ okay now what is a perfect square this I into I is a perfect square so perfect PS list dot add I into I now we have captured all the perfect square and we can use these perfect square any number of time to achieve this value of N and we have to like uh give the answer what are the least number of perfect square we require to achieve this answer so for that what we have to do is just return returning solution function this is my helper function which is going to give me the answer and let's say we are starting with zero that is first of all in our bigger problem include all the perfect scares and what is our Target here Target is s sorry n now let's implement this function private int solution int indd idx and int Target so firstly let's cover our terminating cases so if at any moment Target is equal to zero it means we require zero number of coins further and the maximum value of n is going to be 10^ 4 so let's say you going to be 10^ 4 so let's say you going to be 10^ 4 so let's say you are given 10^ 4 so what is the maximum are given 10^ 4 so what is the maximum are given 10^ 4 so what is the maximum number of time maximum number of coins you can have to achieve 10^ 4 every you can have to achieve 10^ 4 every you can have to achieve 10^ 4 every single coin is of capacity one in that case so in that case uh let's say for our terminating case if idx is equal to PS list dot size that is we have covered all the coins or the target is less than zero in that case we will be returning plus infinity but you have to keep in mind that if I am returning plus infinity so there can be cases where the solution is appending one to the plus infinity and then can lead to overflow so in that case I will be returning some bigger number that is out of this range let's say a 99999 I hope that is fine 10 power it's bigger than 10^ 4 so I think it is going bigger than 10^ 4 so I think it is going bigger than 10^ 4 so I think it is going to work now our solution is uh return math do minimum of these two possibility the first possibility is considering that current coin which is considering one coin we have considered one coin and then the rest of the coins are coming from further sub problem which is for the sub problem starting with IND idx and the target is reduced to PS list do get idx okay I hope that is correct and other what is other possibility that we are not considering the current coin we will be starting from next coin onwards and then we have to achieve our Target so these are our sub problems using these we have achieved our bigger problem which is like considering the idx element okay now if I try to submit over sample test cases giving me compilation error why because I have put semicolon here which is not required Target was a there was a typo Target okay so our recursion call is working perfectly so as I'm thinking in terms of like a smaller problem bigger problem and then achieving the solution in a proper way so I'm following the proper recursion approach to solve a problem so that's why my recursion is most of the time correct and now it is a recursive solution and having load of overlapping sub problems we just have to do one thing cache our answer against these two values that is just a very minor thing to do so for that how do we have to store two values so let's say we take a 2d array let's call it DP and do we uh and by default the value will be zero can we have a zero and our as our answer no I don't think so because if even need the minum value of n is one so we will be requiring one coin at least so I have taken this DP array so DP is equal to new integer the first one is PS do size the first index the first uh first value or the row is going to store my index value is going from 0 to P perfect scare list do size okay that is fine the second value can go from till n so if it going till and I will be taking n+ one okay now just do will be taking n+ one okay now just do will be taking n+ one okay now just do one thing memorize our solution against idx and our Target done uh that was pretty simple to memorize our solution yeah and just do one more thing before doing the processing so this is the processing we are doing before doing the processing just check whether we have already cached it or not if its value is not equal to zero it means we have stored somewhere at that position something at that position let's say DP of idx and Target is not equal to zero it means that this value is already cached this combination is already cached and we already know the co answer of this call the specific call so we can directly return the SP same value the memorized value if I do not store it and try to submit it is going to give me dle that I'm doing the processing every time let's also check by submitting okay giving T if I do not uh like uh do the processing every time and use the cachier result and submit the problem it is reducing the exponential time to uh quadratic time and the problem is getting uh submitted successfully hope you understood the problem thank you guys bye-bye let's problem thank you guys bye-bye let's problem thank you guys bye-bye let's also have a look on the time and space complexity of this approach what is the time complexity after doing the memorization it will become quadratic that let's say um the target Target is order of N and for the Target n it is going root and iteration because we will be having a perfect square equal to root of n because in the perfect square finding the perfect square what we did is I into I is less than equal to n so if I say I sare is less than equal to n taking a log here is I is equal to less than equal to root of n so n into root of n is going to be the time complexity for this approach and what is the space complexity will also be the same because we are storing uh our solution in a 2d DP array where I'm using row as our idx and the column as our n so n into root of n so this is the time and space complexity for this approach okay thank you guys
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
199
hi everyone welcome to my channel let's solve the problem binary tree right side view so given a binary imagine yourself standing on the right side of it and return the values of the nodes you can see order from top to bottom so this is our binary and you are standing over here and you are looking the tree from here so what all the nodes we can see first on the top level we can see the node with value one on the second level we will see the node with value three and the third level we can see the node with value four so these two node two and node five will be hidden because of this node three and net four so finally we have to return node one values one three four from top to bottom in the result so how we will solve so as you already know if you have solved few of the tree problems like tree problem can be solved by either using bfs or dfs or both so this problem we will solve using both the traversal so let's start discussing first let's how we will use the bfs traversal so for the bfs traversal i have already video where i covered like multiple problems of level order traversal like level order traversal and zigzag label order traversal and reverse level order traversal so you can watch out those problem videos as well if you haven't solved those problem if you solve that problem those problem then this is very easy to solve so how we will apply the label order traverse a level y level so for this is starting what we will do we will use a queue data structure and if root is not null then we add the root node into the queue first then we iterate while until q is not empty while q is not empty q is size greater than 0 while skew has the node we will keep processing it then for every alternate level for picking at every alternate naval level what we will do for the result first of all we will take at every level the peak node like this peak node so on this level we will have node 1 only which is we can see from the right side so we will add into our result list so that is our let's say result is we will add this one in this here and then we process this level that many number of nodes so first level will have only one node so we will process one time then while we processing the node one we will look for the sec next level so for next level here the key instead of looking first left side we will look for the first right child so whatever the child right child we will look always first right if it exists we will add into the queue so three will add it here once cue pulled out in this then 2 will be added here 2 is the right left side of our root node now after that we will reach on the second level processing then first we will get the 3 from the queue so we will add 3 the peak element into the list result is and then we look for the right shell yeah right child of three like this four then we look for the left child of three which is not exist so is keep moving then we will pull the two just keep pull it and we will look for the right child of 2 which is 5 we will add into the queue that's it now we will again pull the 4 and this 4 is now we reach on the third level so this is our first level second level and third level so on third level this is our peak node we will add into the answer so that is the result final result and we will keep processing and after pulling these both the nodes from the queue will become empty and this while loop will be terminate so this is the final answer we will store into the list of indicator and return it back so i am leaving this problem code to on you can pause the video and try it code yourself that is very easy and straightforward so let's go for this tree uh like what will be the right side view so from right we can see first this root node 3 then we can see the root this node 1 and then we can see the on this level node with value 8 but we can also need to see the node with value 4 on the fourth level so the final answer of this three will be 3 1 8 and 4 so that's it so you can pause the video and implement the vfs solution if you have any difficulty in implementation you can ask in the comment section and i will also put the code in the github repository so let us now think how we can solve with the dfs traversal so in dfs traversal we will have three options like either use in order or preorder or post order so here for solving this as we go in every alternate level what we need to track on which level we have so we will in each pass the variable d which is represent as a depth b initialize from 0 so this is the depth of this level so whenever we go left or right side of this node we will increment the depth d plus one which is will become one similarly for here this become two so now we need to pick only the right side node so what we will do we will first go same as the bfs traversal we first visit for the right child and then left child because we need a right view so we will go for right child first and then lefl and at every level what we need to check first we will check if root is null in that case we will return if root is null we will just return from here other case like we will keep a list which will be our answer we will pass the from the caller method as a reference and we will check if list dot size is same as the depth we pass which means we haven't picked the rightmost node of this level d then we will add that root dot value into the list that's it so initially first list will be empty then we will add 1 then we will call this write of 3 then 3 will come and the size of list will be 1 and d is also 1 so we will add 3 then we keep processing for 3 then we go again for write the size of this node like here the size of list 2 and the d is 2 for the node 4 we will add 4 then we come back to back there is no left here then we come back to this left we will see the size is greater than the 1 so we will not add we just keep processing we will call for write and size of the list is over already here 2 so we will not edit it so let us take another example here if i increment another node let us say or instead of here just say this 5 has another left child that says 6 so in that case what will happen after processing all of these node we will reach to the node number 6 which is on the d c d equals to 3 and so far our list has only three elements so size is equal then we will add 6 into the list as well so this will be the answer for the if we add another node here so this is how we will solve the def dfs traversal so you can pause the video first and try to code it yourself so let us implement the dfs traversal so for the dfs traversal what we will do we first create a list reference which will be represent as we will pass as a reference into the dfs method so let us say this is and call the dfs method by passing root and d like depth initial depth from start from 0 and the list reference of this list node after that we just return list now let us write the definition so private void method dfs that will get the tree node root and the interdep d and the list of integer which will be the reference so here first we will check if root is null then we just return this is a base case for our tfs method second condition if list dot size is equals to d then we add the current node value which is root dot value into the list dot add root dot value into the list then after that we will call dfs for root dot write first so that is a same as the vfs we did and increment the depth y one and pass the reference as it is so let us call for left sub tree as well so root dot left that's it so this is a dfs traversal implementation let us compile the code and see so it is working fine now we can submit the code first so it got access let's understand what will be the time complexity of this code so as you can see for every node we are processing once so if there are n nodes so the time complexity of n and the space complexity what will be the space complexes so as you can see uh the if we do not consider this will be separate out and the recursion call stack will be go in worst case o of h where h is the height of our 183 so in case of a skew tree this can also go off and so that's it if you like this solution hit the like button and subscribe to my channel thanks for watching
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
1,846
Hello and welcome again so today's question is maximum element after decreasing and rearranging so before proceeding further in the video if you are new on this channel then please subscribe and if you like this video then please like this video then let's problem statement. You are given an array of positive integers perform some operation so that it satisfies this condition so the value of the first element in array must be one the absolute difference between adjacent elements must be less than or equal to one so we We have been given an array, what is the first element in it, we have been given a condition that we have to satisfy, then what is the condition? The condition is that the first element of the array should be one and the rest should be one. There will be adjacent elements, the difference between them will be one or less, meaning it will be one, otherwise it will be zero, so to reach there, we can do only two operations, one can do that we can decrease the elements. People can decrease and or we can rearrange the elements of the array. Okay, so here we start noticing this thing, we can rearrange the elements of the array, after that what to do, we have to find the maximum value. After arranging or applying the operation, we have to return it. Let us understand the example well and then we will code. In this example, the element we have nearby is 2 1 2 and that is its meaning. The output has come, it has come to how it has come, let's see what we have been told that we can decrease the elements and the first element should be one and the difference of the adjacent element should be. There should be one thing, we understand that the element will be sorted, so for that we sort it, so first of all we need sorted, so we understood that we have to sort it, so sort. Now what we have to do after this is that the first adjacent element has to be made one and the difference of the rest of the adjacent elements has to be made one and smaller than that or Adjacent can be equal or it can be adjacent, then the first element is already one, so there will be no change in it, then what is the second element, if it is one, then we will look at the one whose first element is then the first element is one. So if this element is bigger than this, then what will we do with it? Whatever element will be this, we will add one to it, only then its element which will be adjacent should be concatenated because after we have to maximize it also. In this, if both are equal, then what will we do, we will let it remain one, so here it will be one, this should also be one, right after that, the next element which is two, then what will be the difference of two and one? One must be smaller than one, meaning one is smaller than one, we do not have to change it will remain two, after that what is two and two, then what will be the difference between two and two, if it is zero then in this also No change has to be made because it is smaller than one, so we will leave it as two, then what will be its difference will be two only, so then we will leave it as two, then the maximum element which will be after it will be the last. The first element will be the maximum, so what will happen in it? The first element will be the answer. The answer will be two. After that, we have another example in which we have given 100, 1 and 1000. Now let us understand 100 and 1000, so what is there in this? What has to be done is that if you first sort then short it then what will become one then 100 then 1000 just after that when it is shorted once you will see that the first element is one then it will not be there so make it one nothing to do with it. After the previous element in the array, our pointer will appear here. If any element comes here, then we will compare it with the previous element. If the difference of both is more than one, then what will we do with it? We will update the previous element Psv and if the difference is less than one, then nothing, then 100 and if the difference of one is more than one, what will we have to do, we will have to change it, how will we have to change it, we will have to add one to it, which will be the previous element. There will be an element, we will add one to it, whatever will happen, this element will be the key to update, what is our change in this, what has to be done in this was one, now it has to be changed, this one happened, then now this happened, okay then we will come to that green. The pointer came to Y, then if we compare it with 2 and 1000, then the difference this time too is more than one, then what will we do, which element is in J? If one element is added to it, then our last array which will be formed is two and th. If this is formed then what will be the maximum element. If the last one is maximum then our answer will be exactly one case, which can be b case, we are array. Suppose there is only one element in it, let us assume any element, then what to do in that case, first of all, what we have been given is that whatever is the first element, we have to make it one, we will simply make it one, we will return one, let's quote. So let's code what we discussed, so first let's settle down, if it is equal to one, if it is equal to two, if it is one, then what to do, return it, right here, let's solve it, if it is not there, what to do. First let's take an n, it will be equal to the size of a dot, after that make it short, er dot, begin comma, a dot and after that, what to do is make the first element equal to one, then make it equal to A0. Do this, after one, we will run the loop fo and aa iv i lesson a plus aa right inside that, what will we do, we will check that if the difference of the adjacent element is more than one, then we will update it, we will check r aa minus i myve if. What to do if there is a greater number and update it then a i equal to what to do a i - 1 + 1 Well, give to what to do a i - 1 + 1 Well, give to what to do a i - 1 + 1 Well, give one to the previous element and then what to do in the last one, simply return a of n-1. Now let's run it and see if n-1. Now let's run it and see if n-1. Now let's run it and see if our code has been run. Now let's see after submitting it. Our code has been successfully submitted. So this was today's code. So if you liked this video then please like this video. Like subscribe my channel and see you in the next video till then keep learning and keep exploring bye
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
10
hello friends today that solve the regular expression matching problem given an input string as and a pattern P implement a regular expression matching with support for octet and the asterisk the dot matches any single character the asterisk matter is zero or more of the preceding element and the matching should cover the entire input the string not partial so let's see some examples if the given s is a and the PE say we just return false because it doesn't have their dot order asterisk so we just compare it whether these two strings are equal they are not equal so return false example 2 if the S is a P is a as asterisk we return true because the asterisk should use with its preceding element and these two characters represents the a repeated twice so the whole two characters means a so is the same as a so we return true see this example if as you got you a ap PE ho to see asterisk B will also return true because this is the asterisk we can see it as the see represented as 0 times so these two characters just means empty string and this a asterisk means this area repeated twice so a asterisk means a so it's the same as a and the rest is the B there are the same so return true this example yes is a B and the piece dot asterisk we also return sure because we can see the dot and the asterisk atom the dr. represent repeated a twice so that means the dot in a daughter matches ending single character so there should always be the same so return true and see this example am i as this four characters are matches because this s and the asterisk you can see it as them s repeated twice so this should match and is s also match is s this s asterisk also means that this is repeated twice but as then it becomes this I but there is no I in the P so we return false as we try to get the ends of their examples we can see one in twitch if solution is just her check one by one and they see the rest of whether they are match that means if the first character of these two strings are the same we compare the rest because the difficulty actually is how to handle their asterisk if we only have their care their lowercase characters and there's a dot we just needed to compare whether a whether they are equal but preventer has their asterisk we do not know whether they repeated their atoms all once or multiple times so we needed to think about all the possibilities so the first solution is just to try to compare the first two character of these truth dreams if they are the same or just it has a compare the rest but basically we will first handle their asterisk if there are second to character of this P is asterisk we actually have two cases one is we use the proceeding elements zero times or we use the proceeding elements multiple times if there are seconder of this character of this piece not a asterisk adjuster written the is match the raised to a part of these two streams so let's see this algorithm we definitely need to compare the first character of these two streams check whether they are equal but as there is a dot so if the P tried to zero is a dot they should just means they are equal then this case means we do not use the first two account if we do not use the first character we just needed to check whether this string as a match is the P or the rest part of this P so start from these two or we use the first character so the first two characters should be the same and we match the left part of this s and this is the P because let's see sixth example if s equal to a and P go to a asterisk the first part is the same so we need to we just because this a estrin no asterisk oh can I use this a multiple times so just exclusi that is a and we compare the rest of this else see whether they are equal to the um that's the reason of this P and if the second to a character of this pin not equal to the asterisk oh we just it just like the regular case we do not have the asterisk which I see the first character whether they are match in the match arrestor all the SNP okay this is the algorithm since very straightforward let's see the summary again the whole idea is just a check Charles one by one we first to check whether the first character of these two strings at the same or the first character of the P is a dot and the day I will check the rest if there's seven part of this chart of the P is a asterisk we can either use it zero times so we try to match the rest of this P or we can use the first characters multiple times so first to match the first character should be match and then we can measure rest part there should be s substrate start from one or we do not have this difficulty part just to see the whether the left part are the same so it's very intuitive now let's write code but first do not forget you do an edge case check if the pattern is empty 0 then C 0 we return as the lens you go to 0 then we will check the first match there will be here we'll just check whether the P is empty here we must check if the else is empty otherwise we cannot do the eschar at 0 so as dollars really are greater than 0 and then we have to test one is eschar at 0 equal to peach at zero right or pH are at zero equal to the dot okay then we see whether we have an asterisk in the pit but we should make sure that as the pedal as a grid or you couldn't you otherwise who cannot use the picture at one so doll events great oil cadential and their picture at one eco Judah yes that's true risk asterisk or just return either true cases wrong is we uses a zero times so we just needed to check is match as in a piece of string start from two or we use it so the first touch to be the same and the rest that will be s substrate start from one and there will be P ok if not is just the easiest case which I'll check the weather the first character is a cell and is match substrate I will be one right well then there will be peace upstream what okay hmm oh sorry okay then let's see the second solution which is a dynamic program if you have a see the a tick the distance before actually this solution is a little bit like the editor distance because we also use a to use a 2d array that means DP the boolean IJ means that the length of this s and the length of P whether there are matches so we use the lens that's the reason we use M plus 1 and n plus 1 m is the length of s and is the length of the P oh we can't like save them save the state of the previous sub problems DP 0 means that all these qu empty strings matches so there it should be initialized the to chew and also we need because the Esther risk is very complicated so when we initialize we do the initialization we can see whether the peak can match the empty string the astral risk or Campisi has 0 preceding element this is what we do in this initialization we start from the 2 because that means the lens and I less oil content and if you are at I minus 1 which means the kernel chart is this asterisk we will we'll see whether we can see the preceding element and the current astral risk as repeated 0 times this whole idea just to see whether the last this P can match an empty string in the s this is very essential if we do not do this initialization we will not get a corrector also for this case if s equal to a Pikachu a at risk we if we just do the rest part o we cannot get a correct answer so we muster check whether the length of this peak a match at empty string so in the rest parts that we just needed to check whether it term use them multiple times okay let's see the remembered we iterate these two strings we match one by one for every length of this is as the wheels teach you match it so basically we have two for loop the outer loop is start from 1 to M and then the inner loop is start from want you and we get this choker current or chart the easy stir case is that the same or the PC is equal to the dot actually the same means the first resolution so they are state is a transitive the DPI J just equal to DP I minus 1 J minus 1 if the previous is matches now that the other length of IJ also matches case 1 is if not notice them and the PC which is a char in the P is equal to the asterisk the first things that we do not use the proceeding charm so if the DPI J minus 1 a minus 2 which we do not use the proceeding element that is true we can let D be idea coach which ego to chew also transit otherwise um otherwise we will see whether or we repeated many times because at least you will repeat her once so that's the reason we use I minus 1 if s is 0 2 pitch are at J minus 2 which means the preceding element is equal to the current HR of this s string or the preceding element is a dot so that D P IJ equal to DP I minus 1 J this is the example see why we use the DPI minus 1 if the given string s is a AAA and piece a asterisk this is a deep heel array we first the initialization we know the 0 is this true and there's a 0 2 is also true because when we do this initialization we know DP 0 q you go to TP 0 because here is a asterisk so we get this church this to place a true then this a is the same so we know DP a 1 equal to TP 0 so also get it is true then this is a asterisk let's see it's the example we know I is equal to 1 J is equal to 2 and the DP 1 0 2 is not true so we go to this condition in case this is a go to picture at 0 which is a so DP o 1 2 you go to DP 0 2 which deep here to issue so if you want to also echo choo-choo-choo-choo that means they're a extra risk repeated once so this a matches a asterisk as a reason we get it is true then we go to the second to one a second to eight we do the same see we get this value transitive so we also get a true here okay in the time complexity is best compared see just a big om Thompson okay let's see it again we'll just use a DP array and sizes and sorry is very slow okay so this is a DP m plus 1 M plus 1 and we do the initialization one since DV 0 equal to 2 because 2 empty strings are match and then we check whether the prepare the match is the empty string if it has a asterisk we just do not use it there aren t see them member twitch iterate these two streams check whether they're currently two characters are the same if the same or PC go to the dot with a deep heap IJ equal to the previous on two lengths and the if in the asterisk if we do not use a preceding char and it's true so currently DVIDS should also be true otherwise we check whether the LC e go to the preceding element if ego which are transitive the value under I minus one J okay now let's write the code what the length of this tube amico qu s talents and you go to appearance in the boolean deep he you go to boolean M plus 1 and the initialization DP 0 equal to 2 and the 4 into I equal to 2 and s equals n and I plus if the pH are at I minus 1 II go to the asterisk the DP 0 we match the empty string ie go to DP 0 I minus 2 then we do the main part I start from 1 and I less oil cosy and I press plus the 4 into J equal to 1 J less or equal to and J plus would get a current at you chart which is as CEO gos chart at I minus 1 and the chart P is equal to P chariot J plus 1 if s decode your PC or PC you go to the dot right there are the same then the DP IJ equal to di minus 1 J minus 1 the very active transitive else if their P the PC hot shooter at risk we have to case one is if the D P I J minus 2 is true we do not use it so dpi J just a ho to true else if s is equal to P chareyre 2 J plus minus 2 or the basis sm h rh j minus 2 is equal to a dot the DPI q were just equal to deep here I minus 1 n J that means that there were repeated many times the finally will return DPM thank you for you see you next time
Regular Expression Matching
regular-expression-matching
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "a\* " **Output:** true **Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ". **Example 3:** **Input:** s = "ab ", p = ".\* " **Output:** true **Explanation:** ".\* " means "zero or more (\*) of any character (.) ". **Constraints:** * `1 <= s.length <= 20` * `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. * It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
null
String,Dynamic Programming,Recursion
Hard
44
211
hey guys how's everything going this is Jay sir who is not be good at algorithms I'm making the Beast making these videos to prepare my interview in this video I'm going to take a look at two one ad and a search word data structure design we are required to design data structure that sports the following interpretations add word and search word such word can search a little world word or a regular expression contain the only one alphabet or dot that means want anyone later select bad dad man yeah I think I've met some met similar questions before it must be I think it should be a tree right this tree is T or this tree a try I don't know how to pass it but basic idea is three like four we're getting or we are getting all the words we can just organize them into a tree like this is root right if there is a Apple an Abe Apple we should say ah pull right say this is an application so app pull here is the same and here should be yeah I write Apple II and a they keishon something like this so there's neither for example there's neither one like about like a b and then a right Oh something like this of course this is an there might be some other words like bag right it's a G so we are adding word we just have searched the word from root like for adding a new word like bus we found a be okay and then go to you but there's no you so we add a you right and then there's no s we added s and that's done and when we do doing a search we're doing the same we search from the routes and doing a BFS way we push the next max children next uh yeah children the next note in took you and then dupe to loop through B notes and to see if it matches the letters right we search from search one by one if you met the dot we just push the next one all the nodes could be possible so they push the next round of nodes into our queue if it is not that we just searched for particular dot right property particular node and that push the children in and there's a case that if there is a bus and there is a bus what well with the two words but in a in the same tree pass how will define how would we define how do we determine if there is a word or not for a normal case which refers check if s has any children right if it has any children then it is not the end we can check if it is the end but we cannot check if the bus like this right it has children so how could you see if there is vas or not so for this case I think not only we need to add a children map what so that lead add a special identifiers not as if some if there's a word like bus actually will be something like a dollar this is used usually used in expert you regular expression to as a nd Edifier we can do like this if we have a tree like this it means there is a bus and there is a bus right we add also we add an and here now bus and bus if there is no ended dollar here it means there is only one we're caught booze hmm so things are good getting clear let's try to let's do our implementation the first we need to create our node right the note is first simple he has character and had its children not children I think next right next is a map right is a map of node something like this okay for when we are creating a word dictionary what do you do we actually create a node right start with huh I don't mean to like this it's this one doesn't matter for the route okay now we're gonna add a word root is called declared with the will actually get search the existent us layer by layer so I'll say the layer would be first layer would be these routes next right and we loop through the word if layer has the character what do you do like for you bus we have for B we find the B then we just move it to the next layer right he's here so Claire would be yeah if not for like B doesn't have you okay we can create a and create a node add to it right so layer set factor new node actor cool and then we move layer to the next one right well these two actually could be merging to 2 into 1 so we write it yeah this would that do and at the end the word is Travis and layer will be gonna be on the next one right next layer so what do we add a ending AB did fired this is very important set thought it's one is okay so now we coming to the search while we're doing the same we do is that BFS way for BFS always remember we create a cube so what we gonna be the initial well the initial would be the next of root sure the queue would be array of map string of note now let's try to loop through the word because there will be might be multiple map in this cube we need to loop through the queue right okay so let's say factor equals word I we do through the cube for a for this BFS are always I wanted to push it know as an ending identifier and I create a head then I'll head while head equals Q shift this head is actually the a the map of a B right cool so if character is thought what does it mean that means the map that all the characters of the map would be available will be valid so we need to push all knows any right and if it is only capture only one character me okay only if this laptop we need to search for that character and push it in right cool if it is star so we say for let key note off head remember the head is map so this is the character this is the note okay this is the character this is the note right so for we now dot a be will be also always valid we don't need to push a PP a you all in so Q would push note and if the character is not we will like for a we just pushed a in right so Q would push work you push head again character right but it might be undefined so it will need to be checked if it is this exists or not if it has the character then we push it into the Q so then we can go to next one so this is for each word we will go to the next possible layer which has all the maps like BP and a you but if the Q if the queue is empty we could stop right if Q even a wait a minute there is an ending or ending right like this I think we should say if key is not ending identifier we could push it remember that for a note if even if this last one it has a map even it is empty it has a map containing it I ending identifier right so if we found anyone we found any word a letter but the next could not be and wait a minute forget next push queue will push note next yeah remember that it could not be empty so if it is empty we should break and now when everything is done it might be two cases the first one the word is now Travis buddies break ahead of the word the for-loop break ahead of the word the for-loop break ahead of the word the for-loop breaks before word is Travis the other one word is Travis but it like the case here there's no ending added fire so I'll move the I out of this for loop and then I'll say if I going on anyway it will if the queue you want to end at empty cool okay this doesn't matter I think if the queue is empty it means nothing is found so it must be something in the queue and we can find search on the Lana on the map to see if there is a dollar in it right EXO forward it must end at like word and then a daughter at the de fire yeah the queue is a map okay if next map past outer we just return true and then if not return false right let's try run a code hmm layer has is not function 38 layer this is new next this route is new node layer ah god this is next cool try to submit yeah we're accepted and actually there's not so much improvement I think this is clearly a tree create a node pay attention to actually there is a these are there's this node but there is a map and this is the children right we're using a map so there is a node there's a map and there's another node this is a little complicated pay attention to that maybe children will be better hmm maybe children you're better okay we push the next into layer and add the letters now remember to add the ending identifier so to the search we do it BFS and for each word we will check all the map in the array if it is dot push all the next round a map into the queue yeah if it's a specific is a specific letter we push the map of that specific character next write into the queue if the queue is empty we break okay and it's a search this is enough this is not like how to say DFS or something it is not we should not use queue at the are outside and they at last if we found the word like for find the bus then the recursion of the for loop will stop at this layer if we've passed bus and oh yeah with next should be dollar NS okay or batter itself like we flew on if we found this bus so you feel if we there is something in EQ and one of them has daughter it means we can we have this man we have this word and then we will learn true if not we can force so it's very it's pretty straightforward that play pay attention to the detail implemented well hope this video helps see you next time don't forget to follow subscribe my channel hope to see you soon bye
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
221
foreign Matrix filled with zeros and months find the largest Square containing only ones and within its area so what is same the given question is they are given a 2d Matrix uh it's a binary Matrix that means it contains only those and once and we have to return the maximum square that is present maximum Square form is the boxes with only Parts you could see here one so this is the maximum Square you can find this is what we need to so what is the approach to solve the problem we'll see so first I just uh take an example like if you have a box like this okay 2D Matrix and we have zero one zero so a single box can be a square yes it can be right because equal length and breadth square is nothing but both length and width are equal in that case so if is if you see here this cannot be a square okay this is one yes this single box can be a square here also it's one this single box can be a square no this cannot be a square how do you find the biggest Square so let's take another example okay where all the elements are if we take this signal box yes this is a square this is square but when you have it this is a square but can there be any bigger Square than this if you see the above part this part diagonal part and the upper part all the ones that means this can be a square right let's say we have 3 cross 3 Matrix in this case let's say all elements are 1. so in this case the single all the single boxes are squares and 2 cross 2 square also we can form this is a two person and 3 cross 3 is this one so how about how do you get this 3 cross 3 biggest Square so for that what we do is will keep in another 2D Matrix of same thing foreign okay and here I'll check this element is 1 yes if this is one and just initialize to zero one if this is a corner in case okay on the corner image this is one that means the first row and First Column you just fill the values as in if it is 1 then make it as one otherwise zero when you come to this box now here this alone can be a single Square the other Square can be 2 cross 2 for this either this is one square or this is one square but how do you get to know whether you have this bigger square or not for that you have to check whether it's neighboring elements your neighboring element is one so these are one that means what if all r one and this is also one that means this can be a square so in the DP array you check DP of I comma J will be equal to VP of I minus 1 comma J and DP off 9 minus 1 comma J minus 1 and DP off I comma J minus 1. so I minus 1 comma J means one row about this part I minus 1 J minus 1 diagonal I comma J minus 1 will be this so if all these three are one then and this is one then only this is this will form of Matrix so if DB of I comma J equal to 1 so the Matrix even Matrix is equal to one will be equal to minimum of all three so why am I taking minimum because so minimum of all three all these three is how much one that will be one so one plus this one so there should be plus C equals to minimum of so DP of I comma J will be initialized to 1. this month maybe five comma J is equal to one why is it equal to 1 because the element is portion is one and you find the minimum of all three so I'll just rewrite the Matrix again so why am I taking minimum I'll explain that okay I'll explain that So currently we have 1 here one here two so in logical we have to move like this next is this the next row but okay since as I said for the first and First Column there is no Square above this or below this or diagonally to this so just you take this and now you move to this position again you check here we have one so dpfi comma Z will be one plus minimum of all three how much it is one so total of this will also be 2. so what does this two indicate is at this question you will get these two cross two Matrix at this position you will get two cross two Matrix okay once you are done with this now we have to motor this position again secure it is one and DP of uh all the three diagonal append on the minimum is one plus one will be two here so that means here two plus two Matrix can be formed that is this maximum Square Matrix at this position and if you move to the last element here we have one and the neighboring are all three the minimum of all three is two only two plus one will be three so now you can get the maximum is how much you are getting three cross three Matrix so we have to return this 3 cross 3 so you have to keep a variable called Max size and each time TP of I comma G and I'm access you have to find the maximum so why are we taking minimum you could say actually if here it was 1 how can this be one here so in this position we will have one let's say this is zero where you see Zero so this is zero all three are one then is there any Matrix uh possible in this okay not zero let's say this is 0 and this is one so if this is one you have to look for the neighboring things here one so this will be 0 because no Matrix can form because here it is 0 so 0 1 2 what is the minimum of all three that will be zero only so the answer will be 1 here why here you cannot form two plus two Matrix because this is zero right so that is the reason we have to calculate the minimum of all three if we take maximum like two if you take 2 plus 1 will be three can there be three plus three Matrix formula flow so you need to take minimum apparently we are just looking at this position is it an up low diagonal no so it will be one okay then you move here up diagonal nothing but uh low this side we have what do we have one so but minimum is nothing so that's why I said all the first and First Column you just initialize to whatever elements present but when you come to this position you have to check whether this is one if all are one then this will be one if all are two then this will be if this is two one then one only will be taken one plus one two will be taken x 2 cross 2 matters can be formed so this is how the dynamic programming approach will be implementing here so you're just looking for the diagonal Limit Up element uh next element if all are one then only this can be a matrix that is a basic logic file so if this calibrary this will be initialize it to 2 because this is a two cross Dramatics next when you come to this position here also two plus two Matrix here so the here is a necklace here two customatic spacing here two customizing present and here one more two plus two Matrix present so 2 here we have and here we have one if we have one see this can be two close to Matrix this indicates what does this indicate this is a two cross Matrix what does this indicate this is a two cross two Matrix so when you come to this position can this be entirely three across schematics so that is where we are looking minimum of all three what do we have 2 that is two plus one so we get frequency logic behind the problem so we shall program this so let's say end m equal to Matrix dot size similarly columns we have to know Matrix of any one of the row 80 next what we need to do will have a variable called Max size initials to zero and just as you know 2D Matrix so we need to have two follows one inside the another is a let's initialize it to J so let's say that n j plus okay so how to check if Matrix of I comma J if it is equal to 1 then DP of I comma J will be equal to one then uh to check the previous image when do we check for the previous elements only if it is not a first row and First Column rate so here we have to check if so this foreign that means only for The Insider image we don't take into consideration first and First Call so if that is the case then DP of I comma J plus equals to one value already one plus the label square whatever you get that will be minimum move KP of I minus 1 2 J comma DP off I minus 1 and J minus 1 then DP of ID then J minus top left and background so yeah and each time what we need to do we have to calculate max size so max size will be equal to Max of PP of I quality Matrix and at last we need to return the Max size yes oh for okay I will initialize J so yes okay and DP off okay wait uh so this initialization should be Vector inside a vector that is 2D array PP of M comma for column again Vector int of n comma zero all initialized zero yeah so here again one more minimum I have to tell so since it's taking three parameters um any mistakes matrixo Vector in okay so since I mentioned this is a character instead of one this should be one and then anything else Max size okay return the area so area means Max size into max is because row and column size will be equal as you know in the Square is yeah and for Java also same logic 2D array create and same thing will be applied he is successfully submitted if you understood the concept please do like the video and subscribe to our Channel and then keep learning thank you
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
83
hey guys welcome back to our series on cracking the coding interview today we're going to be solving a problem called remove duplicates but keep a few things in mind versus this problem also happens to be a lead code problem feel free to pause this just to read them and make sure the only difference is lead code asks us to do it for a sorted list however this problem asks us to do it for an unsorted list however the algorithm we're gonna develop is gonna work regardless of if the list is sorted or unsorted and by at least i mean linked list also keep in mind we've solved this problem before using a buffer meaning we ignored this follow-up buffer meaning we ignored this follow-up buffer meaning we ignored this follow-up saying we're not allowed to use a buffer and we also ignored this saying to use two pointers meaning we only followed this saying hey use a hash table today we're going to use an actual hash table in a previous solution we use the set and we'll see what the difference is without further ado let me go ahead and explain how we intend to solve this problem some people including lead code assume the head of the list to be right here however i don't like that i like to assume there's always a node in front that contains a value called none and that is well another valid control contains the value of none and that is the head so we're going to implement it this way for our solution however for lead code we're going to implement it the code's way that this is the head of the list so here's how we're going to do it first i'm going to define an empty hash table called items and i'm going to set him equal to an empty hash table first but as soon as i define it i'm going to initialize it with this we're going to use a variable called current as soon as i create my hash table i'm going to put in the value of current and map into the value of 1. so every element in my hash map is going to be matched to the value of one okay then we're gonna start iterating through this current at index okay he's got index zero okay so which is right here where current is index zero keep in mind link please really don't use the concept of indices but it just helps this explanation be a little bit smaller and also you know the fact that i'm using a sorted list for the example again this algorithm is going to work together so either this is sorted or not sorted i just think sorry lists look slightly cleaner when current is at index zero we're going to ask ourselves the question every iteration we're going to ask this question is current dot next the value is the next value of current in our dictionary is here in items in this case the next value is this guy is current the next in dictionary so yes obviously one is here so the answer is yes in the case of yes what do we're just simply going to say current the next equals current dot next so what this line effectively does is every time you see a next on the left side of the equal sign it breaks the pointer and points to something else so what this does is it breaks this point right here on current.next and points it to current.next and points it to current.next and points it to current.next.next current.next.next current.next.next so this is pretty much what the linked list is going to look like after executing that line of code so now current.next points to current the next current.next points to current the next current.next points to current the next points right here so effectively that deletes this guy technically from our list although he's still a memory but he's the definitely because nobody's next pointer is pointed to him then we're going to go on to the next iteration in our next iteration current is still at index 0. okay current hasn't moved yet his next point is just moved we're going to ask ourselves the same question we asked in the previous iteration is current.next the previous iteration is current.next the previous iteration is current.next the value in our dictionary in this case current.next we broke the pointer so the current.next we broke the pointer so the current.next we broke the pointer so the next is now this guy is this value is 2 in our dictionary the answer is no what do we do when the answer is no the first thing we do in the answer i'm just going to save vowel here but just whenever you see this file just know if it represents current.next.value so we're going to add current.next.value so we're going to add current.next.value so we're going to add into a dictionary and set them to a value of one so pretty much we're going to do two math one again it doesn't have to be one we keep setting this value it can be anything can be infinity it can be 10 it can be 12. it's just something to know that hey we're adding these values into our dictionary so after this then we're going to move our pointer we're going to say current is now equal to current.next so this effectively to current.next so this effectively to current.next so this effectively moves current from right here current moves from current to current of next so now current is right here so now we're gonna go to next iteration so now current is at index two current that index two we're gonna ask ourselves the exact same question it's called the next value in our dictionary so this is correct now this is current the next his value is 3 in our dictionary the answer is no what do we do when is no the same thing we did in the previous solution in the previous iteration ways no first thing we just add in terms of valve cannot be equal to one okay so keep in mind valve just means current dot next to that just don't write it all so we're gonna add three mapping to one again it doesn't matter what you're mapping to you can map it to wherever you want it's just easier to do to one so now we've mapped it to one what do we do next same thing we did we're gonna say current it's gonna be equal to current dot next so this is looking good so first chronicles current the next so what that does effectively is move current from right where he is to his next guy now we're on to the next iteration which also happens to be the final iteration so now i'm going to say occurrence at index 3. okay so what do we ask the same question we always we do we ask the same question we always ask is current the next value in items does he exist in our dictionary in this case current.next.values3 is three in our current.next.values3 is three in our current.next.values3 is three in our dictionary yes three is already in there in the case of yes what do we do same thing we did in the previous case of yes we just said equals we just said equals we just said equals current.next.next anytime you see a dot current.next.next anytime you see a dot current.next.next anytime you see a dot next on the left side of the equal sign it just means we're moving the pointer so we're going to move the point of current.next to current. so current.next to current. so current.next to current. so effectively that breaks this pointer and moves into current.next.next which happens to be current.next.next which happens to be current.next.next which happens to be none at this stage we close our hashmap so this effectively deletes this guy so we have only returned one two and three without further ado let's put this solution to code we're gonna have to create our node class which is a building block of a linked list created our linked list created the append function which is how we're gonna build there the link is obviously we're just appending different values to it and created the display function which is how we're going to visualize our link list so this is the function remove duplicates we're going to edit to work so right now we've created the linked list of just random numbers we're going to call our function right here we're displaying the link with before we call him and after recording so that we'll see how he's changed right now he hasn't changed right if we run this there's no change because we've done nothing to the linked list actually it's giving us an error because we have this function let's say pass so if we're running right now it's not going to do anything right it's going to return the same because we haven't done anything so i'm going to go ahead and call him right now even though we haven't done anything my list uh remove duplicates still not gonna do anything because we just passed him but let's go ahead and edit him kind of like we just explained on the whiteboard which is why i like the whiteboard um coding because it's in a lot of software interviews they kind of make you call on the whiteboard let's go so first we're going to initialize our dictionary we call it items okay we're going to send him to an empty dictionary first okay then we're going to define our current she's going to go to self.head.next the reason why we're self.head.next the reason why we're self.head.next the reason why we're starting from head.next is because again starting from head.next is because again starting from head.next is because again i like to assume our head is in non-node i like to assume our head is in non-node i like to assume our head is in non-node most people including lead could assume the head is this so we're not gonna say current equals we're just gonna current equals we're just gonna current equals we're just gonna say current equals head so let's go next so next like i said we're gonna populate our itunes dictionary with the first guy so items with a key of cur current.value so items with a key of cur current.value so items with a key of cur current.value so the first guy we're on which is which was one or in the case of which was one or in the case of which was one or in the case of this example it's gonna be zero we're gonna set it to value of one okay creating a hash map a key value pair so now this is where the actual algorithm begins so while curve and curve the next occur the next is driving outlook both of them are we want to ask the question is current this curve the negative value does he happen to be in our dictionary okay is he in items if he's a yes we're just gonna say current dot next equals current but next up next it's exactly like we did in the paper for all the yes cases current the next equals current the next dot next and then if it's a no we're gonna add him and then set current equals the current.next okay else which is the case current.next okay else which is the case current.next okay else which is the case where it's a no he doesn't exist in there we're just gonna say items of current.next the value equals items of current.next the value equals items of current.next the value equals one key value pair then we're gonna say current equals current dot next simple and that's it for our algorithm let's go ahead and run this and see what happens oh there's an error what is the error the arrow says node has no attribute value oh okay this should be currently there let's try one more time okay boom you see how it removes all the duplicates so it works fine let's go ahead and also test it and lead code so this is the exact same code only difference is like i said current.head difference is like i said current.head difference is like i said current.head is what we mentioned here rather than in my code where i say self.head.next right we don't need that self.head.next right we don't need that self.head.next right we don't need that because lead code doesn't assume the first node is not like i do and the second difference is we added a check for if the head node is none in my case in here we didn't have to add that because again i always assume the first node is none little doesn't do that so in the case where you're giving a link list of only one node none we need to add this check but for my code that already takes care of it so let's go ahead and submit this and see how we do bam this code was good in terms of space which isn't so small memory but in terms of time it wasn't as good but however it was successful so that's it for this video i hope it was helpful and i'll see you in the next one you
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
1,362
Uh service barbell page can change the hands of that trouser hanger hey this is where it on tv nas tweety nang to file such as sms dst in law ah 2 sub there o in touch esd find a shovel star diver yes In sc Seongshin Girl Tao's Basic Aria Oh Jesus 5 Squalo Last time, lv-d was taken out, but I left it as it was. 5655 Ishmael's Kurz lv-d was taken out, but I left it as it was. 5655 Ishmael's Kurz lv-d was taken out, but I left it as it was. 5655 Ishmael's Kurz Seoul Star Brown went and wooed me on hold a nail art because I had a nose and gnawed mr Chiu out. n dennis code theme there is a child cut am i company's fender list adi dia look at our zone of frozen dry masa also lee junsu's computer is going to be gd right people's place as if x on mice 5 monsters still files so the explorer xlo bye orf needs and write x word sex lon SM clinic sm yg lower man uh that now defense 10x hair solvit movie of resource summoning ah sa se Aion computer and won tax evasion 2e side job introduction Ah Ha Hae You can become a monster, you can get cancer, the stats are just base SOS service isi, and there is a protected Izzy at home.
Closest Divisors
airplane-seat-assignment-probability
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. **Example 2:** **Input:** num = 123 **Output:** \[5,25\] **Example 3:** **Input:** num = 999 **Output:** \[40,25\] **Constraints:** * `1 <= num <= 10^9`
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
Math,Dynamic Programming,Brainteaser,Probability and Statistics
Medium
null
344
hey everyone nitissa's side hope you are doing well so let's start with the new challenge so let's see the question so the question is reverse string okay so you have given a string array and you have to convert basically reverse that string and you have to do it in place basically you can't take any extra space so you have to do in order of an extra memory okay so like this is pretty simple straightforward question so like the first approach we can use is basically use the inbuilt reverse function but that will not uh this question asking for so we have to implement it okay so the other approach what we can go with is basically take a extra error so if i take the indexing from here so this is 0 1 two three four what we can do we can take a new array and we will take from the last of we will fill this fourth position at zero then we'll fill sorry this o then we fill this l similarly we fill this l then e then h okay so this way we can get the reverse string but sorry so but by going with this approach this will you can say taking extra space okay so let's see how we can do another approach so what we can go with this is basically one okay so what we will do we will take two pointer basically you can say so we'll take a two pointer basically one is pointing to start at start of the array another is pointing to the end of the array so what we will do we will swap this position and this position okay so what will happen this o will come at here and h will come out here okay so this will be like os at this point and h will be this point after this will increment rl so l will come here similarly we will decrement our h so h will come here by this way we again swap it so this l will come at this position and this e will come at this position okay so we'll do basically while l is less than h so we'll swap the element okay so by this way we can reverse the string and it's a order of one extra space you can say so let's write the code for this so what we will use we'll take two pointers uh we'll take low and let's take a high so it's thought l length sorry for the voice while l is less than h so what we will do we will swap it so we'll take the current oh sorry it's a character so character s of l swap s of l with s of h so it's just a swap function that i'm writing and s of h is equal to c and we'll increment rl and we decrement our h okay so finally we got our updated reverse string okay let's run it so this is giving the correct output let's submit it okay so i hope you like my video thank you for watching the video
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
85
Hello friends, I am Vishal and I am going to question the state primary tractor, largest area sub matrix with all once. Okay, have you heard of this meter, I am just going to tell you which is the matrix which has the largest area and one of them is coming out. Okay, so look here, these are many verses of the matrix and inside it, the biggest area is the biggest which is the rectangle, the first semester is this, which has the highest with all once, so this is Islam of F-35 only 5th with all once, so this is Islam of F-35 only 5th with all once, so this is Islam of F-35 only 5th April 2015 Multiple honey will be kept inside which are deprived of sides like you are seeing, this is six bittu's whose help is inside one dynasty, so this is you only and the sale of this one is also 512 and sir will remain inside 282 also many notifications ref Jeff is being made but the largest one which is closed was yours this was yours 15 f5 so this is the question now one more thing happens inside it and the nutrition element is largest area square submit sum on the score of vacancy or largest square meter solve this That is a question, tell a little about its symptoms, the way to do this would have been to your DP of God but he has not seen our nutrition is of a slightly different type, our sub-matrix is nutrition, our nutrition is of a slightly different type, our sub-matrix is nutrition, our nutrition is of a slightly different type, our sub-matrix is mother's rectangle, it is ok, triangle can also be made like this, when it was square, it is a bit easy, but difficult. By doing this, we can do it a little bit differently here, this method becomes a little bit different, see this, we call it rectangle, how can we do this 4G SIM, I will give you a little bit only if you need your ears. This question is a gift, some of the last ones are waiting, I show faith in the last, largest area histogram, those taking admission in the same, just imagine how they are going to do it again, if I go to play store, then it is very correct, Ganeshotsav test means very good method on 19th. good, very good method on 19th. To tell you also, what to do, basically in this you have to do it in the largest area histogram way but how to do it Bhairav ​​Bhairav, you know the trick, okay how to do it Bhairav ​​Bhairav, you know the trick, okay how to do it Bhairav ​​Bhairav, you know the trick, okay first let's go in this row, in the superhero and this person, if this was the base. This line, if this line is the base, then it is okay, if it was the last date, then how many buildings and from those buildings we cannot make blouse stairs, here I will make the first one, this is one of your ads which is only top-10 beautiful. Tax is there and which is only top-10 beautiful. Tax is there and which is only top-10 beautiful. Tax is there and for this book, if I have not given you anything of ours, it is okay for you and for this one, let us tell you the largest area in this program for this, then how will you guys do this question, then it has become like the earlier Kashmir. That we have kept you from hybrid and told you that if I tell you the cylinder stairs, then the height of all these is one and here the zero festival is ok, then what will come out is one by one or if I give this then here is the answer, two is ok. If you want to keep quiet, then from here, if you are okay, you will say, then there is a tour from here, let's do this, let's go down a little, now consider this point as the base, okay, now don't even consider a friend, this line is the basement, so like it Base people here, how much height is there in the building, so here is the tattoo here, idol-2, but here is the height, the tattoo here, idol-2, but here is the height, the tattoo here, idol-2, but here is the height, one fix above, something like this, nothing above this, here is hit one, you have to do this till the first 108 moons. Because you were the wind here, I bring it to you, I believe in it, so we can keep global live, we can prevent it, if we believe, then it is okay, then it is created here only, you are the giver here, so now this has been done, so karma is the same for this. If you fold it in this manner, then what will be formed is 212, then this will be formed from the broken one, and if one will be folded into weekly, then it will be fine, then how is our face from here, just imagine, something like this is being formed: 22122, imagine, something like this is being formed: 22122, imagine, something like this is being formed: 22122, tied from here, this is being formed. Whereas after ordering it from here, it is 22212 K, it is coming from here, so in this way, I will review the Abhishek done by this person, now think about this electricity, what will happen after selling this one, now for this gas, see here either. Zero is like if you are born in zero, then by agreeing to the cat above it, here the process cannot be done in that building itself, neither here I pick up the phone, sodium will be considered, there is their height activity, when we meet hero, we put 20 On the other hand, if it is being made then pay for what I asked, it is ok for you, but you go to do 221, if you got three one, you will get more increment, you got 121, it was said above, make payment for these, they will be free, activate here, then our i20 will be free. 225 special yoga can be formed on 323 dead bodies or it can be limited to Baba to Shakal, so we are 8181, this one is for this country, this is 18, now for the next subscribe, this is only for this that neither this one is here nor This is your again increment will give all the Dhanvantari treatment for free and take it 4 so now from here this ruler this free deficit well can also come or you can increase former 228 then toilet one is more so take twelve festival official this for Let's go till Africa only friend and your ₹ 50 from here to friend and your ₹ 50 from here to friend and your ₹ 50 from here to even Nifty either you guys answered logically in it this logical will go and I will go to the court but the one with some importance is basically attacked inside the court in the previous question which was lights. The one doing S2 will use the same point, grind the same function, here I will take the plugin and he will get our answer, okay, it is very setting of interest, I can do anything to you Singh Dhindsa, here I have coded the same logic. Give me a moment how the logic should work, so first of all a controller, this is the control which I have marked here on duty, then write the mantras below which is the giver, the first AC patient is ok, this is our matrix, after that we removed it from Maxima which is I have read this article from Maxima that my problem is Maximum Histogram. According to SAIF, show this one to Kondagaon completely in the World Cup. There is brother code written in the last part, there was a question about basic reflection histogram inside it, then he basically passed the depth, he told that this face If a histogram was made then can I find out the maximum edge? It is the same code. This one is fine. That's exactly what we are going to call here. So our current is 30. Hey, basically we have called this one cord. So it will attack and return, okay all to him, this is our current bread, this is the current, I will attack here, that four, okay, so the damage we will get from here is only one more government, so it has brought us, seen before, okay, after that, now next time, zero. We will start with this one, Rohit Sharma, and what will we do, we will go to all the elements one by one and we will update our current stop, okay, control someone's subscribe that if this index is the money element, then that element will come and talk. Stop the current and pay them. If it is zero then don't do anything. Okay, so let 's see. Since it is one, we will 's see. Since it is one, we will 's see. Since it is one, we will delete it, which I have already done. Before the value is incremented by 300, it becomes Tyagi. So this was your When your I 07, it was something like this and when you will be oily fast, then it is saying that current, then use the increment here, if I make it here also, then the increment will go to 22922 by taking online payment from here to here, nothing will happen which we give and If it is made here, the increment will go and if it is 150, then we will have to do it, right, if this is one then it is okay, the Alps were the current has come till 2030, this one is written in the chord, first just put this line of Bloody Mary, if this is one, Getting it done any minute then you improvement comes progressively if serial at any place then you will be attracted to that you were zero so I ignited either you it has become and for it hey you call the same and do the current answer The one from Nehrugram is fine, I wanted to find a cure for 10 grams, this one has the same cord, if you have a chance, you can come for one, you must have one for that sport, the glass is October 2016, the answer from here is six high cost to attack. Because of this, the next one can be taken for gold, so if our current one is made first, we will update how it is fitted because here I have updated it, we will increment it, okay 21082, here also we will ask in the cabinet, what is the free thing here? So we will make it zero here, we will give this increment on the other hand, Meena that here it is become, so we have to increment it so that one here too, the cartoon to make the last one, so basically this became Papa, if this line was there, if you had it, then you See, here you have fit length, here you have some length, here you take more of it, you only have enough length here you will make it neat and clean and with this, if you look at your body, then this year's Shraddha is more for two, then more 410 Which is your free leg here MP four is okay from here the answer you have is that then and till the maximum they are still going to come to your C which one is for education service is okay that your this period one can be stopped due to Microsoft As soon as we see it is made again because if it is made then we will update it, the last over has just turned 30 for one, it is not updated, we will just lahan and update, it will be fine, this former scientist volume to receive new updates, coriander heads that now so much money Where do the pilgrims come from? This is 2016, so this one becomes your six, this is the phone, then it will be against Money Rafi, it turned out to be yours, and this five step is fine, so five or you can make it for me, it is fine. So this alarm set up is four for two or the power of your mind is five, from here you can get the Maximus, husband's six, this one six, transfer from here, the last one overall, the second one from here, Bigg Boss from there, two summatives, one. Do you like this of f22 or here is this of 312, it is ok, this is Asha 500 600 golf course, it will be injustice, very simple votes of all the activists, if you want to comment, should I comment on moving against him, I am telling what is his nature at this time. Is back the tractor is included in this list like this, okay so this is a very interesting question of you people, this is that, we go with this, after this we will see the green chilli, the prefix posted in slip of expression is on the epistaxis right there. Tiwari, if you understand the flash light then please like it, I am the one who I can tell you with
Maximal Rectangle
maximal-rectangle
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 6 **Explanation:** The maximal rectangle is shown in the above picture. **Example 2:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Example 3:** **Input:** matrix = \[\[ "1 "\]\] **Output:** 1 **Constraints:** * `rows == matrix.length` * `cols == matrix[i].length` * `1 <= row, cols <= 200` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
84,221
293
how's it going guys today I want to go over another leak code question and say we're gonna go over a question called flip game and this is a question that's currently being asked by Google all right guys today our problem is called flip game again it's a questions being asked by Google and our problem ascription says you're playing the following flipped game with your friend given a string that only contains these two characters plus and minus you and your friends he turns to flip two consecutive plus signs into two consecutive minus signs the game ends when a person can no longer make a move and therefore the other person will be the winner write a function to compute all the possible states of the string after one down move okay so in a nutshell we're playing some random game with our friend where we have to flip plus signs to minus signs we're given some initial state of this game and it's our turn and we have to return all the possible board States or game states of this game after we've decided to make a certain move and so basically we have to simulate making all the different moves we can so it also tells us as a note if there's no valid move return an empty list okay so again that's really kind of the logic we're going to go with we're giving some string we need to find all the possible moves we can make so what does that boil down to well we know a move is required to is it requires a move requires having two consecutive plus signs so this really boils down to is us going through this string finding every single place where there are two consecutive plus signs flipping them two minus signs right so making that new board state that we would get from making that move in adding it to our list okay so that's all it is it's not that complicated it's not that bad let's start writing our code so we're gonna make just a list of strings to return and we're probably gonna call that possible States because I think that's what makes the most sense that's what it's going to fold trying to say lists of string possible States equals new ArrayList and again possible States is just going to hold all the possible states that this game can be in after we decided to make any of the moves that we could potentially make so now we need to actually go through this string and find those two consecutive plus signs and simulate making all those different so I think it needs to wait to do that is we could just have a while loop and say well we haven't reached the end of the spring keep looking for these consecutive plus signs so we're gonna have a pointer right we'll have I that starts at the beginning in the string and moves through the string finding those potential moves that we can make so we're gonna say int I equals 0 and now we're gonna do is just have that so Wow I is less than s that length we need to keep looking for these different moves that we could potentially make right so now when we have to do well if this is the very first time that we're looking through this string we need to find the very first occurrence of any two consecutive plus signs and simulate making that move but and this is the little like the tricky thing about this problem is if we're on any other subsequent iteration of this loop we need to make sure that we're not gonna simulate making that same move so let's say it was the second time this loop runs we don't want to try the first pair of plus signs we want to try the next pair of plus signs so to do that we're going to have a ternary so we're going to say int next move and this is going to represent the index or the starting index of those two plus signs that we're gonna simulate making that move for so we're gonna say if I we're going to set this equal to if I is 0 we're just going to say give us the index of the first two plus signs in otherwise we want the index of the next two plus signs so we could just add another parameter I and all that saying here in the second call is if I is greater than 0 give me the next two consecutive plus signs so meaning after whatever our current index is of I right so from where we just were look past that start looking past that great so now we're hopefully going to have a next move to make now we just need to check that we actually do so if index of can never find two consecutive plus signs next move is going to have a negative one which isn't a valid index in Java so it's basically telling us like hey I couldn't find what you asked for so if next move is equal to negative one then we simply know okay there are no other consecutive plus signs we have no other moves to make so we could just finish our problem right here right let's just return or possible states in otherwise we don't trip that if statement on line seven guys that means we definitely have a move so now we just have to simulate making that move so to simulate making that move we needed to take the two consecutive plus signs that we found and flip them two minus signs and then add that resulting state to our result right are possible states that would result from us making that move so now let's build that next state so we'd say string it's probably something like next state right because that's we're computing what we want to do is everything before us is going to stay the same right because we didn't touch any of those plus signs or minus signs or anything so we could just add whatever was before our move so S sub string from 0 up to our next move so that's gonna get everything from before wherever we're trying to make that move and just throw it into our string and then we want to add the two characters that we're changing right so the next two characters were plus signs and we need to change them to minus signs to tell you know our opponent or whoever we're playing that this was my move and then afterwards we didn't touch anything else on the board so we just need to add whatever comes after those two plus signs that we're not changing the minus signs we need to take that and also throw it into this next day so we could say plus s substring and now this is just going to be our next move right so everything from the index of our next move or the move that we now have now just made essentially or our making but we want to say plus two right because we don't want to get those two plus signs that we're changing the minus signs so you say plus two and now we just need to add that next state that we created to our possible States so we'll say possible States dot add our next state and now we just need to make sure that we update I write because on the next iteration of this loop we need to make sure that we're moving forward through the string so we're going to set I equal to our next state plus one right so next state is going to be the beginning index of our next move we want to make sure that we're moving one past it so that we could then find a next move in the next iteration of this loop now finally when this loop terminates guys all our work is done and we really just have to return our possible States so now quickly is talking about a run time and it's a little bit convoluted it's a little tricky but I'm tempted to say that the run time is o of n here but I think because we're going through all the characters in the string that seems like it's o of M but then I think this substring coil these two here really just one of them is enough to do it I think is gonna make us degrade this runtime to o of N squared I'd love to hear what you guys think in the comments but I think that the runtime is probably oh of N squared because of the substring call inside of this loop in terms of the memory complexity I think it's basically o of M I think it's technically a little bit less because for any of these different strings right regardless of how big the string s is it's basically maximized or it's limited by however many moves we can make right and we need two things to make a move so I think the largest possible states could possibly be is like n minus 1 strings so it's basically go of n so I'd probably say that the run times o of N squared and I would basically say that the memory complexity is over N so let's run this code let's make sure that works next T plus 1 incompatible types o because I meant to say next move sorry next movie plus 1 this frantic nature works awesome in books so guys that's how to solve flipped game in Java again it's a questions being asked by Google I hope this was helpful if you guys found this video helpful and enjoyed it do me a favor leave the video like and subscribe to the channel for more I'll see you guys next time
Flip Game
flip-game
You are playing a Flip Game with your friend. You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return all possible states of the string `currentState` after **one valid move**. You may return the answer in **any order**. If there is no valid move, return an empty list `[]`. **Example 1:** **Input:** currentState = "++++ " **Output:** \[ "--++ ", "+--+ ", "++-- "\] **Example 2:** **Input:** currentState = "+ " **Output:** \[\] **Constraints:** * `1 <= currentState.length <= 500` * `currentState[i]` is either `'+'` or `'-'`.
null
String
Easy
294
1,704
hey everybody this is larry this is me going over to one of the code contest victory 221. uh hit the like button to subscribe and join me on discord let me know what you think about today's problem uh determine if string halves are alike so during the contest i got this very quickly but i still got an wrong answer the wrong answer is just that um i didn't consider uppercase or lowercase i actually did during the uh the contest but i um basically during the contest my code was like this so i had s lower on the length but for some reason i thought that was good enough um because i was rushing it because i was trying to go as fast as i can um otherwise um that's pretty much it i mean i think this is a very straightforward problem uh in that they tell you exactly what to do and you could write it in long wait a short way this is the way that i wrote it um and that's pretty much it you count the rows on the left rounds on the right and it did the same then you return true um you could see me doing solve this during the contest next uh you'll see me being sad about it and of course this is going to be linear time because we look at um we look at each constant uh each character once and uh you could say it's linear this is the way that i did is linear space because i'm trying to do it fast during the contest but you could definitely do an over one if you just do it more easily um and you all want space if you do it easily uh let me know what you think and you can watch me sub it live next one you oh what already made a silly mistake that's not a good oh i put it over here ah oh man what a silly mistake indeed uh hey yeah thanks for watching the video uh let me know what you think hit the like button to subscribe and have a happy new year and i will see you next time bye
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
969
Very short tour when the viewers are watching it is very interesting we are Pandey shopping What is What is What is this question then most of the time you will get a disgusting where dry ginger once click on the perform subscribe button and choose it. Revising forces me every morning, so this is our whole, it is okay to subscribe, then you subscribe that the collective worship is fast, Bluetooth turn, you will join 0210 which is available, this equal to Indian 1600 has become 123 and Now it has become soft, so we have to use such packets. Now what is the condition of our return. If we do not have to do the shot, then what is this purification? Digital library of only use corresponding to sequence of scientific research. Short hair tips, you have to return all the only use ones. All these are only for the readers, which we mean that you have hit them one by one to make quips in the sequential hotel so that your relative will become my son. Okay, so I mean that this is only the plan, as many as you want. If you are returning, then what will you do for this, you have to request, now you will read to use something only for shooting, cost banqueting, if you read to do for this, then despite everything, you will get their set which sequence and notice, then credit. It's okay to do which, if we like it a lot, then its that and prank with them according to them, if it is yours, it will become soft, okay then it is okay, this was our whole concept of scientific, it is okay and we have questions. So let's see what to do, let's take the bus, Tesco Singh glass the question, after that you can take the solution, if you had this, I will explain these rights, 32443 for free 214, okay, now you are doing such a raid. In which you have to select global sales, then you will have to set only to remove tanning by juicing the pan and which is used only in the country from late to three, I reduce, 2012 and employment portal's - Those who will be in the 2012 and employment portal's - Those who will be in the 2012 and employment portal's - Those who will be in the morning will be golden. Here it will be 1234, okay, so it will be soft, so I have about 3 among the same, you have the same confusion, so that's why we will do this question and now how will we do the dance serpent, so what will we do, we will do this from the net. People are there, let's take a good discus, some take it is MP3, short duration, let us cancel the test match, let's ours, 1532, I am free, a flower, 160, so what will we do now, we will start one by one till the last indexes 40. Subscribe Kaisa 12345 66 Sexual Now what we have to do is that if we are in our right place then we should not do anything about it Subscribe and what should be there in what should be on this here, how to do it by doing it see here on the phone If it should happen, then we have an invitation, you come here and sit, so what will we do now, stay in Ludhiana, we will reverse it, then Africa or 5123 46 and after that we will click once, this one is early in the morning and we will shift it to the plant. That's why we will give Tiger Shroff, start the dowry, wait for someone else, if he has a request then we will tell him to the family, now we will shift the fabric to it, now it will be made East 3515 6 Now see that the fiber has come to its right place. But it should happen, okay, so this is our basic opinion, how can we achieve this, okay, now this is a little more left in the question, okay, now the solution is completely known, that's just a few things, so I said that Note down the answer yourself, you will do it and now I will do the entire portion of it laughingly, he will do this tempered glass work, that is the thing, see, then we have to leave the gesture and not always request and I, the bank people have this admission, this LMB Lucknow, now we have to request. Look , I will request you, after doing the last test, I will , I will request you, after doing the last test, I will , I will request you, after doing the last test, I will say, brother, please tell me what is the maximum limit, all the people behind us who have exported this, have the maximum element, now we will give them 108 earths on medium, now what we have here on online payment. That's our maximum text message quickly completed so you have to do this our so we do it in this way this modern that we are sugar so this is absolutely scoring of this show this side don't know that will be on some right side with differences am okay you left side In we have suite na messenger singh will go to that element will have to program outside that it joins the name of that pimples subsidy and as soon as show good alarm second do it right Anshul that so what happened is that it also leaves its effect hospitals in brightness rubber If you add it then it is okay then we will achieve this. If you do that then it is okay then the time for this would definitely seem like a waste of time. You have this inactive fast that who will sit on this seat and which dull skinned person has the requirement of being printed? So what about me or just ask? Has it not been there? Has two posh bade climbed up to five? Yes brother Paushbade, when it is 157 no, we have to meet with Milana percent. Man has broken God and is sitting, you will draw us this fast element, he is the former head of you, he has gone. Those who are in a hurry to complete, where are you? I am just Alpesh Shah Rajesh. In the future, you will use so much time in this way and will fall behind it. Okay, so here it is, now that this is done, you will start understanding that your You will take it is important where we need it but from here we need it on gas then we will get this whole city then we will do it okay toxic hair in the leg effect it is written in happiness that it has not changed then in the pension by doing that we will do strange That if you are taking the year away then that operation then he said that then first there is the missing so now we all mean that if you have the coordination then you will go, this time you will be able to spare 1 minute time and then we will do it okay, by the way if you keep it this year then 4321 5 By taking zee5 from zee5, some organization has related to this by making us some agro complete 8 month, you click and mix to so that the group will be engaged, if it is strong, it is Amazon, then it is Amla by bringing it from here, I always fry the message minute, then you are big howdah from the mind. So we will start determining the sugar, okay, I will do it once here, okay, this period is good, then remove the habit and it takes ₹ 2 again, we remove the habit and it takes ₹ 2 again, we remove the habit and it takes ₹ 2 again, we will get it in the morning and evening time, it is like this, so okay, coming. Yes, my Ko's acquisition is estimated. Okay, so after all, we covered that big machine and slowed down the machine. Is the policy time too big, so taking it on full moon, Na Song is okay. Now our oil is over, so we can give this prize to the rest of the table. Entitled under the former, he will do this potato pancake terrorism. If you give sugar candy or radio, how to increase caller tune, play is already open, it is simple, so what will we do now, whatever alarm we have set, the followers will go out of there first, after that we will fix the money. And your team has a strong middle order, there are questions in the exam, there are some numbers, there is time arrangement, so we have to chant the rosary, we have to call Nakul, we used to get it done again, most of them are in this app, and K - done again, most of them are in this app, and K - done again, most of them are in this app, and K - Mantra Bhaghe Four Wheeler Thoda Ne White Sunge So what happened 12345 6 Your agreement is valid ok keep it complete Varnawal religion will be more First of all innocent loot time at that time place take four drops from cycle then blind the element in it previous Rs Dhaneshwar ok after that match that By drawing and picking up 100, where is our side, which has happened there, okay, this is very soon, now he lives in school, who is this person and if you subscribe on the contrary, then in our group, we do not give that fashion [ __ ] planet, so fashion [ __ ] planet, so fashion [ __ ] planet, so first of all we will remain basic, this If you keep it on the occasion then like electronic police and NDRF is a new day i english bf cat's us cross mark ruffalo leadership are able to see us taking quarter inch egg it is note that this point is hybrid 2016 on youtube channel we back we will take we Take it so that then we will mix it further and now we know that these are gas hydrates, so let's consider this as the average. Let's take the front part. Okay, now one came to us in this manner for the whole week. 0261 Festivals, Unko Jail - - Festivals, Unko Jail - - Festivals, Unko Jail - - We have this, I, Guddu, what is ours and X.N. X Has it been X.N. X Has it been updated otherwise this side is straight line like in this case only one judgment and till has not been updated till this maximum complete you who is this path and this reminded swelling is perfect and on the other hand this youth is like this If it is on tuition, then it is nothing, okay, this side will be safe like this, in this maths, it is not good bye, if that is not at all, we have our definition here, Begusarai destination, we will try, then we will try, Chandrakant will again resonate with us, the mess index It is a plus, its videos and definition is grouping prohibition day program, just that we will see in this where you already know Bigg Boss, from zero to maths class 7 and this match of our answer is also in this is a plus. I am fine and the officer and you, this strange new appointment is always a blessing, you are doing the second one, it is natural, he will simply give the opportunity, friend of Jio, when the time comes, when the bride will come, get this end answer done, get the virus done, it is okay, so this is complete. Time will be done, how does 100 gram withdrawal from here, how much should we find, duration is always according to our economy issues, next boy husak-husak-husak-husak hindi arghya Indian rice made illegal, will take it and it's complete like do it for To Ajay, I always finish the garlic koi ghagra hua hai, how does it end? A Sacrifice and you audio songs, Simbu Doosri Tasty 3D hai, so do it, okay, and together, you understand it, you are okay, egg wave, now that I don't have to do at all. two waves
Pancake Sorting
number-of-recent-calls
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. **Example 1:** **Input:** arr = \[3,2,4,1\] **Output:** \[4,2,4,3\] **Explanation:** We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = \[3, 2, 4, 1\] After 1st flip (k = 4): arr = \[1, 4, 2, 3\] After 2nd flip (k = 2): arr = \[4, 1, 2, 3\] After 3rd flip (k = 4): arr = \[3, 2, 1, 4\] After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted. **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[\] **Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as \[3, 3\], would also be accepted. **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= arr.length` * All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
null
Design,Queue,Data Stream
Easy
null
218
yeah under there today I want to talk about question 218 the skyline problem so the question is super law let me try to give a summarization about the problem so basically we're taking a picture of the city from are far away and there are a bunch of buildings on the picture each building can be sort of roughly represented by a rectangle so to encode the rectangle information on this image we use a triplets that's going to be the left x value right by right x value and the height the Y value for this building so now our input is gonna be a list of triplets each triple Eight's corresponding to a beauty now this buildings collectively form a skyline though that's just unlike the outer contour for formed by all these buildings and to encode this outer contour we can use the we can use a list of tuples each typo here is corresponding to a red dot here that means from this exposition and all until you see the next topple the height is gonna be the given value here so in this particular example you will look like to 10 for the first topple means that front x position - and all and here you see x position - and all and here you see x position - and all and here you see the next atop of the height is going to be 10 so that's the way we use to represent the outer contour in this problem so the question is basically given the left hand side you want us to output the right hand side how we go about solve this so if we so I basically just copied that example from question over to this software so that I can do a little bit more exploration interactively so just say imagine that we have a line that we can swipe through this province space from left to right we do this from left to right because the rolling encoding the bump our Kanto encoding is in this format sorted by the X so I just imagined that we are swiping the slides through this picture when we encounter a left hand side of the view we might need to deal with this situation because if the building has a height that's higher than the prior skyline as shown here we see the first building which is at the exposition to have a height of 10 or just higher than the prior is basically ground here on the left-hand basically ground here on the left-hand basically ground here on the left-hand side before this part there's nothing so we have to update the Skylab so we insert a to 10 topple into the output so then we'll keep swiping the line then we find another building that has a height of 15 it starts as 3 so we put a top of a new top of 315 onto the stile and now when we encounter this little building here it starts as exposition 5 has a height of 12 we will remember the height but we will not update the last I am because 12 is less than the current highest height so we just remember that but don't do any kind of update to the output just keep swiping the line and we encountered the right-hand side meaning encountered the right-hand side meaning encountered the right-hand side meaning that the building and here and since this building particularly building we're looking at the red one is tallest is the current tallest once this building finished that we have to drop the skyline to be the fire second possibly the prior second highest building or the current highest abelian which is going to be the green building with height off so we insert 712 onto the Skylab 7 here is the end point the right-hand side of the tallest the right-hand side of the tallest the right-hand side of the tallest the previous tallest building and the 12 is the current tallest the building's height so basically just kind of swiping the line and to dealing with those kind of events so very intuitively we would have to type of implant which is going to be triggered by when we encounter a left hand side which is a starting position for a building and the other type of invent is going to be when we swipe the line out to the right hand side of the building which means the height can potentially drop the end of that height the building side so we basically convert we can convert to the input Triplets into a sequence of invent and now our problem now just becomes you know process all this events in sequence depending on whether it's opening or it's closing will do some kind of logic and to try to populate this output so as you can see here based on the prior kind of illustration at any given time we want to keep track of the height the active buildings height so you know if because that we have the highest building ends we want to drop the height to be the second highest because basically going to once the building ends we want to remove that possible height and use the new highest amount and so for that we have to basically keep this building thing here that's representing let us help us to keep track of the current building that the line has the line is in the middle of that building basically so we that's going to be the building we haven't 100% sure be the building we haven't 100% sure be the building we haven't 100% sure that we have already processed so that's what we want to keep track of when we processing those events so just going to do some kind of a little bit animation about how we're going to process this two different type of events so the first thing one that we're gonna encounter is X equal to two the height of the building is 10 and there's a starting point for building so we just gonna remember the building's height which is 10 and put this to 10 topple onto the spine and so we originally it's a the ground the height is zero and we see a high building tall building we upgrade in our skyline to that position from this particular x position so that's basically transferring to a code is that if we are processing a starting event and the height of that building is taller than the strictly taller than the prior or current tallest at 0 by default because the ground line the horizontal line is 0 for rising like I don't know how you call it if it's taller than the prior taught us the point we're going to append the top o X and H into the skylight and also add this height to the building to the current buildings we our line has interacted ways so that's a processing this first event here the second event before we talk about the second event let's talk about a special case when we have two buildings starting at the same exposition but of different height because look how the code logic here works is that when we see a height that's higher than the prior tallest the fight we're gonna put that onto the skyline so if we have buildings that starting at the same decision we want to process them in a way that's top from tallest to smallest so that this test here can guard us from inserting duplicates value into the skyline but the reason that we still want to care about the shorter one is that the shorter one can all lasted the longer one so once we finish the longer one we might need to reduce the skyline so that's why we have to process both of those two buildings but we want to do is do so in an order that's tallest the first so that's this or we can do is to check the previous check for the X the last element on the skyline if they have the same x value we try to update to the H to be the highest in that way we don't care about the order but the owner can be really simply done by sorting so I prefer just do a sword instead of you know checking the weather we have the same axe to determine the we insert or update the top of on the skylight so that's about inserting for this first building height here then we move the line towards right in contour the starting point for the red building so the process is as similar to the prior we find now it's a starting event and the height is larger taller than the current tallest that the current tallest is 10 so we find something that's sorry the height is 15 it's now 7 so 15 is larger than 10 so we want to insert this couple 315 onto the skyline and AB 15 onto the building heights then moving the line further towards right we encounter the same point for our third building this is a typo the new building has a height of 12 starting at the exposition five because the height is not taller than the current tallest is 15 then we don't do this append but we would definitely add this to the building height so the indentation for this logic is wrong anyway it's just adding that to the building list basically the height of the all the current active building heights so that's the how we handle the third invent here now just moving the line even towards right within contour now arrived first ending event so how we handle that the logics is laid out here basically we the ending event means that the building of that high has to end here so the thing we do is to remove the height the current the building's height 15 from the active height active buildings height so basically get rid of 15 from this list or data structure so that the result will be 12 and 10 12 is the height of the green one and the 10 is the height of the blue one those two are still there because the line hasn't completely swipes through those yet a 15 has to go because we trigger the event by the endpoint of we're building so we have to get rid of 15 and then we do a simple do a really quick test to see is the removed building the current a high-polished so building the current a high-polished so building the current a high-polished so we can don't do so by just testing the relationship between 15 and the new tallest one which is going to be 12 since that the 15 is larger than 12 that means once we've removed at the red building we have to insert a new skyline point into the skyline so we append X the position where this happens and the current tallest the building fight on to the skyline so we insert seven or 12 is the height of the green building so that's the how we handle the ending event here is another side track that is to show if we have two buildings or multiple buildings and at the same position how are we gonna do this what's the order we're going to process them will be better we want to process them inertia from the shortest to the tallest because notice that we get rid of 12 and then compare out get a get rid of 15 and compare 15 with the new tallest so if we process this removal if we have multiple building like a 15 and 20 or 30 or and at the same time and we if we do that in the tallest to shortest step we're gonna insert the second shortest onto the asylum because we get rid of the red one and put the height of the blue one onto there but what if blue has to be removed too so if we do this in the tallest to the shortest then we're going to end up with unnecessary duplicates on the scale so we have to process them in the shortest to the tallest away so that's a that's the order we're going to do process the ending in bands so all this you know from the tallest to the shortest when we're dealing with the opening from the shortest to tallest when we're dealing with the ending all this can be handled by sort sorting of all this invents so that's telling us basically when we convert all those triplets the left hand right and height into two type of events the exposition the height and the type we want to sort them by first X that's corresponding to the line sweeping event triggering kind of an order we process from left to right so we first assault by X then we sort by the type we want to process starting first and then processing ending the reason being that if we processing ending first we might insert you know something like let's say that we'd have a let's put it onto the back if we process ending first the red building ending here we can put the height of a blue one onto the skyline but then we have a purple one that's even higher then we're gonna insert another topple with the same x value but a higher Y value that's gonna be problematic so for that reason we want to for the same x position we want to always do the start invent first before we do the end event the rare loss the thing is to sort by the type multiplied by the height if we use a negative number for the start and positive number indicating the end event this will cause us to basically if we have the same position if it's all starting position then we're going to deal with this front tallest to shortest because the tallest one multiplied by negative one is going to be negative number and we saw that in the increasing order that's corresponding to tallest the building first if we if it's ending event the height is going to multiply by a positive number so that is going to be from shortest to tallest so yeah so that's pretty much the this super important when we convert the input into a sequence of events we do this sorting then the main logic is basically here so now there is only one thing that's remaining what's going to be the data structure we use for this temporary kind of memory to keep track of the active buildings basically means the buildings that the line still it's in the middle of that building we have some choice let's look at the what we will require that they are structured to do we needed to remove by a value so that's unfortunately linear time algorithm linear time for most of the you know sequential kind of a container kind of a data structure and what else do we need from it we want to get to the current tallest from this container so we want to do constant check for the current maximum so that leads us to think about priority queue and also we have an addition we won't add things into the collection so if we use the prior to q-max prior queue the current tallest q-max prior queue the current tallest q-max prior queue the current tallest the one this query will be in constant time the ad will be log in time but the remove is going to be linear time there could be some modification to the priority queue that solved the problem and that can give us a linear time removal of a given key but it's doable so basically just going to add a couple dad who is a some kind of a map to access directly to our element on this priority queue if we do the removal we can use that key value pair to access that element on the private queue and do a swap with the terror element on the priority queue and after that we're just going to remove the tail so if we do that there are there going to be some serious modification to the priority queue data structure to enable a login time remove of the given key value here but that's doable so if you use priority queue just to summarize if we can have them very efficiently implemented priority queue for this button it's going to be constant time for getting the current tallest and log in time for remove and out I'm not going to do that today so just going to code this solution out but this is the first solution I think it's pretty intuitive basically we have two types of events and we see a building that's can potentially need we need potentially needs to update at the height of the skyline when we encounter the end of the building we can we need potentially drop the skyline and for all the building that hasn't ended yet we have to keep track of their height and any given time what we care is the current polish the run so that leads us to use our maximum priority queue yeah so that's a that's pretty much the analysis that's code it's gonna be quiet field code so the first thing is to convert the triplets into events for left right and height and buildings we want to insert those in their left height and negative on that means it's starting and we're going to do the similar thing for ending events indicated by a positive one in the end so after that we want to sort the England the sorting is let me grab the sorting water we sort by this we sort by X and by the type and then by type x height so that's X 0 X 2 and X 2 multiplied by X 1 so that's the order we sort this so we want to process them in the front left to right we want to deal with the starting first and then ending and for the starting we want to deal with the tallest to shortest when it's ending we want to deal with and deal with all these buildings in this short from the shortest to the tallest so that's this year this disorder is not trivial then let's code the lot metallurgic part for generating this wrong I'm wrong I thinking sort of structure for the output we can I have a skyline initially it's empty and we're gonna have a prior to kill which is gonna hold the active building's height initially inside is empty too and you get a process invented by an inventor given the exposition the height and the type so what's the logic gonna be looking like if it's a if it's starting if it's ending that's going to be separate two blocks so if type is equal to negative one meaning that it's a starting position for building what we want to do is to test the if this height of this new building with C it's taller than the current tallest the building we have we always going to do this ad why it's not indented correctly in my notes anyway so if this height is higher than prior to Q dot front I'm gonna cut up on maximum private you for this if it's taller I append it and I would also push this on to the upright EQ else is going to be the event is going to be ending event if it's an ending event we were first to remove this height then we would test it do we have to chop the skyline if we do have to drop the Skylab we do that here so it's gonna be PQ door remove the height and then we're gonna do the similar test if it's the removed height is taller than the current to highest one that means the skyline have the job jump from the previous site to the new highest and we were just return the skyline now the thing is just to implement this Maxima priority queue we just have a list of all the in container and we will need France need a push and remove for the front we will need to output a default zero if there are no active building so if there is no active building we had to update the skyline to be the ground level meaning that's going to be zero and also in the beginning the skyline is zero so the way that the reason that I'm doing negation is basically I'm gonna using the hip kill from Python and that's only mean prior to kill so I have to do the negation to make the hi to make this maximal prior to kill so the push is gonna just be this it could be push we're gonna push this connective body of the height onto the priority queue and remove is to remove the value from the container I'm not gonna do the most efficient implementation so it's not gonna be long time this will remove is a linear time and just to keep your fight after remove I want to have the priority queue to remain the to still retain and remain the people property meaning that the front is always going to be the largest one so that's that yeah let's quickly check if I have problems so that's a basically a wrapper on the hip queue to turn it into the maximum Q maximum priority Q and here is the conversion front tablets the building information to enhance we have two type of events the starting and ending of a building and we sort that by the exposition then by the type of the event than by the height in the correct order for the starting event we want that to be highest to shortest for the closing we want that to be the shortest to highest and then is the processing of England by indent if it's a starting event we check if the building is taller than the current tallest if it's taller dumblings we have to move this skyline up and after we move the skyline up we push this no matter whether we do this push are not in a change of the insert of the skyline or not whether we do that or not we always insert this new building's height onto the prior to queue if it's our ending event we remove the height associated with this building that's ending and then we see do we have to drop the skyline if we do have to drop the skyline we append that information into this pride onto the result so that looks okay so it's accepted but it's pretty slow let me try to move over there and see ended up to illustrate why it's so slow as you can see here the inefficient implementation for this data structure that holds the active building the height of the active building here I'm using a priority queue and the remove here is a linear time because you have to traverse the container and find the height it will remove after that you have to do a law you have to also do a HIPAA fight I think heapify is also in the worst case going to be linear so the remove here is linear and we have linear number of events so the total run time for this is going to be n squared if we have efficient implementation for this remove it will be true in log n it's gonna be faster but not super faster the reason being that is and we still have to pop the all the shorter buildings here let's just talk about this picture here basically we have a bunch of buildings that's going to be ending at the same exposition so when the line swipe over to the right-hand side of all swipe over to the right-hand side of all swipe over to the right-hand side of all this building we're going to pop them out from this active building data structure one at a time so every those every one of those little box gear would trigger this else branch and to remove and to a test and to append so only the first building being removed would trigger this event because the second tallest one is taller than all of those only that first one would trigger a update in the Skylab and we are doing a bunch of seemingly unnecessary removal there because if I'm lazy you know or as a human intuitively doing this skyline join ourselves learn a bunch of building pending at the same time I don't really care about those little really short buildings that's got buried by this second tallest one so I don't really want to do this removal one at a time if just to remove one I can get to the updated version updated a new skyline height so how it deal is we still have to get rid of those little buildings in some time but it seems that in this particular time it's not the best idea to get rid of all of them and all of them in sequence so that is asking us to that is suggesting us to rethink about the definition of the invent and also that we really want to use pop a priority queue part to have it to be true login time instead of having to hack you know the data structure have a map to somehow be able to directly access this element on the container it was swapping and you know try to avoid doing that so I'm just gonna show the real last picture here so the way to do that is we modify the implant and modify what's on gonna be on the active building for each active building will keep track of not just the height but the ending position as well so that when we trigger invent you know like this invent here we'd get rid of the tallest one that's the ending event we do that and then as long as the new tallest the height is higher than those little ones we postponed getting rid of those what's gonna be the time when we have to get rid of those little ones it's when let's say we have a building far towards right after that building purple building is ending when we're processing this building here will look back to see do we have any kind of finish the building that's taller than this one if it's taller we want to get rid of them we can do so by looking at the right-hand side of that building if that right-hand side of that building if that right-hand side of that building if that taller building compared to this new shortest one and you tallest the one if that building ends before this I can pop that out that time so that's why instead of just putting a height there we have to explicitly managing this very aggressively doing a bunch of processing when we really have this kind of worst-case scenario instead of doing worst-case scenario instead of doing worst-case scenario instead of doing that we're gonna keep track of two things the height and also at which point we don't care about this building's height so to do that we have to do this invent differently that event is going to be the exposition the height and until what x value this height is still valid so that's gonna be the new invent and each building will basically be converted into potentially to invent these starting the inventor that's keeping track of describing the building and also the we have to remember to close those so for every position that we need to do a closing we just have one thing for that there are multiple building can end up to the same place so we can potentially just using one of this closing inventor indicating that so let's say that those two buildings and at the same place and the same 7th position instead of doing three individual invents to get rid of the older buildings and decrease the skylight here if we do this invents in this way we will just do just trigger the invent once so just summarize if we rethink about what's invent and what we keep track of when we have buildings that can potentially affect the skyline to be this couple it's basically going to be when whenever there is invent triggering we want to make sure that the car is the tallest the building here is a still valid so we're going to do potentially some popping to test the exposition and the tallest buildings valid property the second element if the current tallest the building the it's no longer valid compared to the invent triggering exposition we pop that out so it's a actual prior to keep pop so it's a guarantee to be log in time it's not going to be this remove so that's the first thing we do we make sure that the active buildings tallest the height is still valid and then if this new invent this is putting a building onto the is the starting point of the new building and we push this onto the building if one until cost the tallest of building change that means we have to update the skylight so we do this update of the skyline in a third step so that's summarization about if we reframe the definition about the invent and what we keep track of about the active buildings this is the man logic yeah and last thing to mention before we jump to the code is going to be the orders how we sort this invents of course the first thing is going to be the exposition we still do left to right and the second thing is we want to deal with the building's front tallest to shortest the reason being that if similar to the reason for in the prior setting when it's a new building here we want to deal with tallest to shortest because if we do shortest to tallest we sequentially push those onto the active building and the tallest the building is going to change multiple times and we don't want to do duplicate an update to the scale and so we sort by in this order yeah so we start let's get back to code and do some modification to the code so that's the old young man owed the master just get rid of this so that there we have fresh nicer looking code if you want to look at the not so efficient implementation solution you can check out the github for the code so we have two kinds of events we have the starting events which describe the whole building and how long the height is going to be about it the closing event is going to be the summarization about all the end points and we do deduplication by using a set in advance for left right height where you put a top over here at the left hand side the height and the right hand side and closing ends at zero the right hand side 0 and some dummy number zero and be fine so we can tell where the event is a closing or opening by looking at the height if the height is some positive number that means it's an opening event starting event if the height is zero that means we have to trigger some kind of a closing invent so that's that we're just going to add the closing band to this opening emails the reason we don't add this directly to invent is that we can use a set to do some deduplication so if we have a bunch of buildings ending at the same position we've got to only do trigger this ending event just once I have to rush now so this is the order when we sorta in Venice we're still gonna use the same maximum queue do some modification to it I don't need to remove anymore I need a pump so instead of just putting a height I will put a topo which is going to be the height and the valid information and top is going to be just that so the front has to be changed a little bit of swamp so in the case there is the containers empty we also want to still want to output zero but now it's a topo so what we put on the right hand side the value the location this zero is valid throughout the number line so here we put a very big number so I put in the maximum here otherwise I'm just outputting this topple so that's a modification to the pride queue we can potentially accepting the initial data do we need that no we don't my daughter's crying so I have to get to her so that's a that's modification to the prior to kill we removed at the remove operation now out in the pop so and did some modification to the push and pump because the elements on the gonna be on this maximum here is going to be a topple the height and the validity until which exposition this height is still available front here will output 0 until the end of this number line if it's empty otherwise we were just outputting the currents the tallest building so let's just put this on very quickly so here is the popping we have to make sure that this is still valid so if this in Van triggering X is far too far towards right compared to the current tallest buildings validity we won't pop it off so after this value but we make sure that the current after building tallest one is still valid then we just test if this is so if this is the you know opening event we will push this what's this information to the prior to Q so H I'm just gonna talk to myself talking now yeah so this is it I listened while ricotta position teeth I don't need that yeah so this is said the code I have to run
The Skyline Problem
the-skyline-problem
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. **Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]` **Example 1:** **Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\] **Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\] **Explanation:** Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. **Example 2:** **Input:** buildings = \[\[0,2,3\],\[2,5,3\]\] **Output:** \[\[0,3\],\[5,0\]\] **Constraints:** * `1 <= buildings.length <= 104` * `0 <= lefti < righti <= 231 - 1` * `1 <= heighti <= 231 - 1` * `buildings` is sorted by `lefti` in non-decreasing order.
null
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
699
1,721
look uh today we will be solving liquid problem 1721 swapping those in a linked list uh you are given the head of a linked list and an integer K return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end so they give us this example here uh we have an array of one two three four and five so they give us k equals two so they want us to swap uh the second note with the second to last node so we'll be solving the values of four and two so it'll look like one four three two five because this linked list does not have an inbuilt length function we'll manually run through the um the list itself so we'll do a while loop and we'll check the next the will continuously check the next node so while the next node is not a nun type or a null type then we'll continue so while I'll just short hand it here well not none we'll increment length right so we have our length variable right here so uh I propose the solution of have having two pointers within your linked list so we'll have a temp head right here so when we have this array right here so we'll have two defined heads right here right so we'll increment one head to the end so length minus K so the red head will be right there and then we'll increment the second head to be at k so one two so once we have these two heads positioned here we'll just simply get the value of this node of the second heads node and then obviously swap it with the value of this heads node so to do that we will first Define our temporary linked list to find the length because I'm defining at zero this temporary list right here the one two three four five will have a length of four um so we have that so there we go and that will give us our length variable now we Define our two heads so temp will be head number one and we'll have a uh let's node and we'll just call this swap uh equals head and the swap will be head number two we'll Loop through the we'll go through the list the linked list for the first for temp so I equals zero I is less than K minus one because um as I said before length is four but you we count this as five notes so we'll just count it as one less since we already start at node one yep there you go that'll give us the right head for the first head and we'll do the exact same for the second head but instead of having K minus 1 we'll have the length so we have a length amount is K which will put us at the fifth node subtract by 2 which will put us at 3 but we're not switching the third node we're switching the fourth so we add one so it'll be the fourth note right here so then we'll just switch the values and I'm sure you guys all know this swap dot val equals SW and return the head because these um temporary values right here are still pointing towards the original linked list which is referenced in the uh arguments here so just return head so if we submit this you can see that we've solved the problem and we are pretty average
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
1,603
hey guys today we're going to solve lethal number 1603 design parking system so this is a beginner friendly problem where maybe you can use this to teach somebody how to use a hash map or a dictionary so we need to implement the two functions the constructor of our parking system and we're given the capacities for big cars medium cars and small cars and then we need to implement the add car function or method which checks if there is space for the car type and if there is then you park the car in that space but if there is no longer any space then you need to return false so the way to do this is you have a dictionary or a hash map or an object with the capacities for every type of car so initially the capacities are given as a parameters to the structure where one is big two is medium and three is small so we just set those to the input parameters one is big choose medium and freeze mold and then when you have to add a car you can check if you have zero capacity for your current type of car then you have to return fulls because that means that you don't have any space for the type of car that is being added so yeah if the capacity of the current type that is being added is zero then you need to return false but if not so if you don't go down this line then you do have space for your current type of card and so you can decrement the space because you're consuming one you're using one to park the current car and then you can return true as for the problem statement so i'm going to submit this to show you that it works and that's it for me today thank you for watching and bye
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
976
um hello so today we are going to do this problem which is part of Fleet code um October daily challenge uh largest perimeter of a triangle so the problem basically is that we have a an array of numbers and we want to return the largest perimeter um of a triangle with a non-zero area um of a triangle with a non-zero area um of a triangle with a non-zero area that is formed with three of the lengths in the array and if it's impossible to find a triangle with an unzero area we want to return zero right so for example here well it's just three so we return them here it's not possible to form an area without a with value not zero because um there is a rule um just a mathematical rules with the triangle where you need um one the bigger side at the bigger side to be smaller than the sum of the other two sides right um if you yeah if you just play Maybe with drawing triangles or play Maybe with sticks you will get an intuition for that but it's just a known triangle rule which is that the larger side needs to be smaller than the sum of the two other ones and that's not valid here because 2 is not smaller than one plus one it's equal right so this is not valid right um but you may say okay what about this one what this one if we use two one well two is smaller than two plus one right smaller than three so this one is valid so we can return that parameter so that's the idea so what this tells us it should be pretty simple we just need since we want the largest parameter here um we need to maximize the values of the sides so we just need to Traverse the array from largest to smallest and make sure whenever we find any three numbers that have the property that one side is smaller than the sum of the two other sides we can just return that right um so pretty simple solution here so first we of course need to sort it we need to sort the array and then we um we want to go backwards so that we can go from largest to smallest we could also sort the array in reverse order if you want so here we want to go from largest so we and we need three numbers each time because that's what the parameter of a triangle is so we need three numbers and we go back on sorry um and the property that we set is one side okay a larger side of course needs to be smaller than some of the other two right okay so let's take our large side which is at position I plus uh two right so the one towards the end we need this to be smaller than I plus one plus uh at I so basically this tells us that this is a valid rectangle so the area is not zero sorry about triangle uh which will be area different than zero right and if this is the case well we can just return the perimeter which is um the sum right so the sum of the three numbers and so to return that well we can just start from I and go to I plus 3. this will give us the sum of i plus 1 and I Plus 2. and then if we Traverse it and we didn't find such a valid triangle we need to return zero so I'm pretty sure if I was there I'll submit okay so that passes this cases now in terms of time complexity we are doing here over login and then open here um and this is of three because at most we do the sum of three so overall it's um over login that's the higher term um and in terms of space no extra space so one space yeah so that's pretty much it for today's problem thanks for watching and see you on the next one bye
Largest Perimeter Triangle
minimum-area-rectangle
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three side lengths: 1, 2, and 2. **Example 2:** **Input:** nums = \[1,2,1,10\] **Output:** 0 **Explanation:** You cannot use the side lengths 1, 1, and 2 to form a triangle. You cannot use the side lengths 1, 1, and 10 to form a triangle. You cannot use the side lengths 1, 2, and 10 to form a triangle. As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. **Constraints:** * `3 <= nums.length <= 104` * `1 <= nums[i] <= 106`
null
Array,Hash Table,Math,Geometry,Sorting
Medium
null
35
hi everyone yeah so earlier we have solved this problem to some problem today we will try to solve the search insert position problem so let's open the um question now we have given a sorted array of District integer and the target value return the index if the target is wrong if not return the index where it should be okay so what it is we have four or three possibilities over there so let's define the array one three five six so we have the array one three five six and then we have fun when finding Target five two and seven so our Target is five two and seven and five we're getting as two one four so for five we are getting to so we are getting one two one four okay so that's interesting what this question actually is saying so we have this array let me quickly and draw it one three five six index 0 1 2 3. now let's say we wanted to find five now 5 is already there and the position is 2 so we'll return it that is perfect so let's say we wanted to find two now 2 is not there right so but if you closely see where to actually will fit over there so in this case all the elements should move to right and then two will fit over there and then it will return the position 1. so this is the case now if we wanted to see where 7 is exactly fit so 7 will exactly fit on the right most so here 7 will fit and then the position will return as 4. right so this is basically the problem statement you can say the problem statement now how you will solve the problem so to solve the problem basically uh so wherever you will find the started array let's sorted array then obviously you are gonna do the binary search so in binary search you need to quickly find your element in a binary manifest Manner and then you need to like divide the array in every iteration so let's understand how one initial research will work so now let's see what are variables so one three five six right variables one three five and six and Target is 5. so how binary search will work so you can clearly see that our Target is already there in the array so our low will be zero I will be 2 then made will be 2 plus 0 divided by 2 so that is basically one so here is a low where is our I and then it will be here so we'll check if made greater than our Target Element no 3 is less than 5 means meter is less than so in this case what we'll do mid Plus 1. plus 1 means middle shift over there so now new MID is 5 and then we will check if a of mat is equal to Target yes it is so what we will do will return the second index that is 5. now let's see the another example say variable the target is 2 this time okay one three five seven the array is three five seven and the Target equals to two now uh low will be here I will be here and then it will be here why because low is 0 i 0 1 2 3. so I think in this case let me go up here um I will be three I use three sorry for the highest three antimattered mid will come one only but yeah close the correction so right now a Target is two now what will happen without emit will be 3 plus 0 divided by 2 that is basically one so it is over here now we will check made it three is greater than 2. means r a of mate is greater than are low no not low Target is greater than the Target now in this case what will happen in this case our high will be um but -1 so what we'll do or I will come but -1 so what we'll do or I will come but -1 so what we'll do or I will come over here right so I have to start pointing through this now our low and I both is pointing to zero location right so our while loop was low less than equals to I if it will still work it will still run and then what will happen so our mid will be over here so net also will be zero location and then what it will try to find the um Target so a of mid means zero that is basically less than Target so what I don't do it below will be with plus 1 so low will be at first position and then this time this Loop will break because low is one and I is zero so this Loop will break and then what we'll do we'll return the AO flow so every time we will return the a of flow if it is not wrong and if it is found then we'll return the same Target element like the this one will run this element double element now let's try to understand the um border value like the corner cases a second here so what was the array our array was one three five six arrivals one three five six and let's say we wanted to find Target is zero now in this case as we clearly see that it is less than our first element so whenever we found this type of case then we will return the index 0. and then let's say we wanted to find the target as 10 then in this case it is obviously out of this amounts so what we will do return the array Dot length minus 1 we will return the last so this was the thing now let's discuss on the lead code I will solve this okay so I have written the code uh let me quickly copy this code in Notepad and then let me try to give the solution um yeah so I copy this code in notepad let me quickly explode it okay got it so how this code is working basically so we as we discussed we have the low just pointing to the lower index and then I responding to the last index and then this is our condition now your time material calculated with the low plus I my divided by 2. so every time we are checking if a of mid equals to be equals to the target element if that is yes then we will turn the index of it if mid is greater than Target that means it's in the like left side of the array then we'll keep our searching and left side otherwise we'll keep ourselves to the right side and then from this you can add the corner cases also like I discussed in this one so you can add the corner cases like this so yeah hope you enjoyed it
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
142
so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the problem let's start this problem so it is a very important problem and it involves a very important concept of fast and slow pointers okay so let's read the problem statement so it says that we have been given a linked list head node and we need to return where the point where the cycle begins okay so let's look at example so let's say our linked list uh it is just a modification of this linkless cycle detection algorithm and we'll look have a look at how it is so let's say this is our linked list okay and uh this is the cycle and the output that we need to return is this node okay so simply we will make some modifications in the original algorithm of slow and fast pointers correct so it is a very important problem at as it is a follow-up problem at as it is a follow-up problem at as it is a follow-up problem for the linked list cycle direction so let's look at the code and it will straightforward give you the idea of how we are solving this problem okay so in this case we will declare three pointers one is slow that is head another one is fast asterisk fast is equals to head okay and another one let's say called uh the start node called s start is equals to correct now what we'll do we'll write the base cases if head is equal to null or let's say head of next is null head off next is equal to null what we will return null correct now this is the base case correct and now what we'll do i'll just do a bit after this because why to initialize if it is already okay now i'll write the condition for the while loop while fast of next correct and fast off next stop fast of next up next and we'll open our brackets we'll move our slow pointer towards one step and our first pointer two steps like we do in normal linked list correct now if there is a cycle s will be equals to f now here comes the main thing while this is f no what we will do we will make sure that until unless s equals to this and this start mode try to think of how it will work it is already at the starting point it is already at the start is already at the head okay and while this condition will hold through what will i'll do just i'll move my one times and also i start to start off next correct and after this i'll just return start and if it is not the case i'll return so let's run this code okay this is not far this is f correct so so minor this should be semicolon now it will be good yeah so it got accepted and obviously uh try to solve this one also first try to solve the linked list cycle problem then come to this problem and there are some similar problems also for the cycle detection okay so you can try them out also thank you so much we'll meet you in the next lecture you
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
1,456
See, we are going to do questions in this video, the difficulty level of Late Ko is medium, Aaj U Know Lead Code has its own playlist, the link of which you will get the description and in that I am focusing on arrange only, there are basically three types of questions on Arrest. Sliding window 2.0 Sliding window 2.0 Sliding window 2.0 approach and prefix let's start with maximum number of vowels in a substring of given length. It is saying that you will be given a string and a number will be given. Okay like here there are three givens i.e. three like here there are three givens i.e. three like here there are three givens i.e. three lengths of which you will get in this. Sub arrays have to be made. Ok he is saying return D maximum number of vowel letters of other substance s with length. Let's see in Hindi. It means see we have to make three long sub arrays. We will make as many possible ones. We will keep it inside our mind and see which sub error has the maximum number of vowels out of all the errors and what will be the maximum number of vowels, we have to warren like here we will see what will be in the first morning, A B C, second morning B. C I Third C I Fourth I De I Di I F i.e. I have to make these sub-arrays and F i.e. I have to make these sub-arrays and F i.e. I have to make these sub-arrays and see which sub-array has the maximum number of see which sub-array has the maximum number of see which sub-array has the maximum number of vowels, so here I am seeing that there are three vowels here. If yes, then we will return answer three. Last video, he told you that whenever the question of sub error comes, what do we have to think, sliding un window, we have to think, what did I do now, what did I do, look first of all, this was fine, then what will happen? This is what I am doing, I have a window of three lengths, I am just sliding it is a simple thing, so I was making one less, I don't think anything, first of all I make all this error. BC Okay, so first of all let's make ABC sub string or sub Hey, give me two strings, it's the same thing, no problem, let's start, I'll take a pointer and I, okay, start from zero. Let's take one K, start from zero, take one, result, start that too from zero, let's take a window, start that from zero, instead of I and K, I take left and right, left Okay, let's run the loop for each and okay, there is no problem, we can send it like this, read it with r++, okay, that means read it with r++, okay, that means read it with r++, okay, that means we will run the loop three times, as if we are asking this question, and what will we do, check here. We will keep checking each character one by one, that is this character at the zeroth position, is it a vowel? If it is a vowel, then I will add one in the window. Now I have written the process of checking this vowel in this function, okay, what is there here? I am saying that if oval passes then this function will return one, ok it is written, it is a simple thing, either A is A I O U, if there is such a condition then this function will return one, otherwise this function will return zero. Okay, return anything, okay, I have to bid in, please do the bidding, okay, there is no problem, it is very good, okay, so let's do S dot caret, if this one comes, then I write this, if this vowel comes. So I am good in window, that is, I can write it like this also window plus single tu is vowel why there is no point in putting separate if condition because what am I returning in this only, I am returning one, okay so if this If that is the case, then obviously one will be added to the window automatically. It is very good. When this loop runs, the sub-spring that I will have will be ABC and sub-spring that I will have will be ABC and sub-spring that I will have will be ABC and what will be the value of the window. The value of the window will be my Van because it has only one vowel. Okay. Now let's move the start window, okay brother, let's put the loop, okay, which will be R, how long to run, I will tell you how long to run till the end, at this time, see where is L is my A, but okay. Okay, so basically what do I have to do? The character that is placed on L is A, I have to check whether it was a vowel, is it correct, was it a hole, what is the power to do now, what is it to shift, what does it mean that A is? Brother, kick and call I to you, this is what it means, the first character from the old window has to fly, the first character has to fly and from the rest of the string, the first character has to be brought into our window. Okay, now when you add the first character from the existing window, you will have to check whether it was there or not. Okay, I am moving the window, so a new answer will come for all the windows. Okay, so the old window was there. Its answer will be something else, no, it will be something else, then no, it will be something else, why brother, because the numbers and vowels will be different, okay, then we will see, make a new window, okay, there is no need to do anything like that, what is a window, I am waiting, just fine. There is no problem, window is equal, you make window mines, I make this vowel, okay and what is the character placed at s dot caret left i.e. cloth position at zirath position, see whether it is a vowel character placed at s dot caret left i.e. cloth position at zirath position, see whether it is a vowel character placed at s dot caret left i.e. cloth position at zirath position, see whether it is a vowel or not. If it is there, then mine it from the window, what will be the van which will automatically make it zero otherwise it is a simple thing, okay now what will happen here that the answer to the window was our van, for the same reason it will become zero, okay But it has become zero, but now what is the new window left, that is, we will have to add the weight of IF, weight means brother, is it a wall or not, okay, then let's add window plus it is equal, you make it vowel s dot care aate kya? Where was right and right? At this time it was on I. Do you understand? Okay, whatever R was after this loop was IP itself. Okay, and since I am running the loop, I will increment them. Okay, if I take This condition works, it's ok, the loop is running, there is no problem, it was a lot of fun, I am updating the result which is my own, I will tell you the result is equal to math dot max result earn window, what does it mean to say this? It means that I will check again that brother, in this window, it is a simple thing, in the previous window, in a way, whose array is it reducing, it is reducing the previous one, okay, when you come out of the loop, then do the return juice. Will give us We have initialized the juice from zero, so here what team will I give to Aryas, why will I give the window team, because here I have not even checked this thing, it is okay if I assume that this loop has not started then Aryas There will be an update otherwise the juice will be zero, that is not what we want, okay brother, let's try it and see if anything works or not. Okay, the spelling of Gair Aate is wrong, it is done, it is accepted, let's submit, everything is also erased. It is very good today see no brother here time complexity is big of n and space we have not taken so big of van is see there is nothing new sliding window is question last four punches we are doing from video nothing new In this, if you have not seen that video then you must do the sliding window questions, they are very important, you will get the link of the next video here.
Maximum Number of Vowels in a Substring of Given Length
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vowel letters. **Example 2:** **Input:** s = "aeiou ", k = 2 **Output:** 2 **Explanation:** Any substring of length 2 contains 2 vowels. **Example 3:** **Input:** s = "leetcode ", k = 3 **Output:** 2 **Explanation:** "lee ", "eet " and "ode " contain 2 vowels. **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `1 <= k <= s.length`
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
Dynamic Programming,Graph,Shortest Path
Medium
2171
493
Friends, welcome to my YouTube channel Kamlesh, today we are going to discuss so let's start and let's see what is there, satisfy the connection, okay, this condition has to be satisfied, we will give it to the one who satisfies this condition. Here we see that 5 is greater than 2 * 1. Here it will become 3. We will 5 is greater than 2 * 1. Here it will become 3. We will 5 is greater than 2 * 1. Here it will become 3. We will try to see if any leg satisfies this condition or not. Okay and first of all we will run the icon. Here you earn 3 okay here. But you will come in this van connection, you are here, our account has increased, what will be the complexity here, what is order of zero, divide and conquer, if you want to keep dividing and go to March, then you should come to do this question. So Eric, if we go to divide, then it will become 243. Right side will become 51. Okay, again how much will it become and I will do compression in the output, you earn four such van, so what will happen now, where will we get that, where will it be, you will get one and one. Quarter will be on three. Okay, so you are updated here. How to check on the reverse. Okay, this is important, so let's check. So, when we do shorting, then give us the condition which of our condition is greater. 2 * Fudge condition is greater. 2 * Fudge condition is greater. 2 * Fudge is We will check the condition, then how will we do it, let's take it back for us, what are you are four three five one, you four three five one, what we have done now, okay, if we divide it will be 243 51, again we will divide, we will get four. If we take three fives then we will keep counting what will be the return on what we have here, meaning if we do not get any reverse pay here then we will make 0 + in the account and what will be the then we will make 0 + in the account and what will be the then we will make 0 + in the account and what will be the result and here is what we will get. 234 This is our left side part completed. On the right side, if these two are compared then we will check the condition and do plus van because we got one reverse first in plus, we did one more and this is the result, what will happen 15 now. We have to make a comparison between these two, where is this one and this one, where is it, this one is on the point, on the van, you are the company, if the van is smaller than 3, then it must be smaller, it must be greater, right? If Karo is making it then will he make it with four also? So will he make it with S4 also? So with the okay, if he is giving one reverse pay, then he will give it with four also, then it will be plus van. Okay, so from here we will get two reverse pay. If one is ok and one is four then here the van is complete. We will advance the pointer of van. Ok where is the five. Now we will check again. So here both are complete. So the one who was last will definitely be returned. If you see the court while driving, it will become more clear to you and if you see, first of all we have divided zero, we have divided the left and right parts separately, we have got this inverter account done, it is okay that we had made 200. There is a condition, what will we do for that, we will take account, if it is less than 13, then it will be less than four, if it is less than 5, then this is the same condition, count is equal to mid-i+1, this satisfies the connection that the mid-i+1, this satisfies the connection that the mid-i+1, this satisfies the connection that the WAN Yes, if he is making it on reverse with three, then all the elements after that are free because it is shorted, hence he will make it on reverse with them also, hence we had written the condition, we have increased six points, okay if the connection is not satisfied. So what will we do, as we did here, like you did the connection search and JSS equal, you write, till the time the connection starts, what will we do? We have come, we will keep putting it inside the M which is made, so there is a sorter for it. I have done it, I have concretized the cake as it will come, I want their gold, so what to do, I have to put the K from here, we have applied here, so what will we do after shorting here, how will we drive the value, how far will we go from there. Till and all the elements which are shortcuts, we will shorten them. Okay, we will add whatever value is on the right side. That's it inside the cake, what did we do in the last, we copied as many and stored them all. We have copied the original program, so here is the account for that and the one which we have merged, okay, you liked the solution, I think you have understood, okay, so please like the video, subscribe, you will see me in the next video, thank you. Very Much
Reverse Pairs
reverse-pairs
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 3, nums\[4\] = 1, 3 > 2 \* 1 **Example 2:** **Input:** nums = \[2,4,3,5,1\] **Output:** 3 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 4, nums\[4\] = 1, 4 > 2 \* 1 (2, 4) --> nums\[2\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 5, nums\[4\] = 1, 5 > 2 \* 1 **Constraints:** * `1 <= nums.length <= 5 * 104` * `-231 <= nums[i] <= 231 - 1`
null
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
315,327
944
um hello so today we are going to solve this problem which is part of lead code daily challenge um delete columns to make sorted so basically we get a set of strings and we arrange them one on top of the other like this so we get ABC for example BCE cea and what we want to do is delete the columns that are not sorted so what do you mean by column here so column is basically going top down in those strings so for example ABC is the First Column BCA is the second CE is the third and so what we want is to delete those that are not sorted but by deleting here they just want us to give us the indices so just return the indices of the columns that are not sorted so suppose this is the indexing 0 1 2 um and so which ones are Now sources ABC is sorted BCA is not sorted so we need to return one and CE is sorted so we just return one and that's what we see in this first example so that's the idea now how do we implement it well it should be pretty sure for how many columns we have right we know we have the strings out of the same length so we have n the length of any string we take that's the number of columns right and so to get the character from The First Column we just take the first string and we take the index of the column right so this would be zero here and then the second one the index of the column the third one the index of the column right um and so yeah pretty much that's how we do it and once we have the columns in a list um each in a list we can just check if they are sorted right so how do we do this so first we need the number of columns which is just that length of the of one of the strings so let's just pick the first one um and then we need to go through for each column so this would be range of n and we need the list of our columns that we are going to check okay and then here what we need to do is um we just take a list inshallah is a list for each column that's the list we will be adding to so this will be a range of n and this here we will need to do columns of I and we need to append the string at that Index right this will give us for example for column 0 this will give us the first string sorry actually we need to go through each string and get the letter in that Index right so that would mean we will add here s of I so that would be the returns in that index and once we do that we can just now we would have all the columns in um so let's just print it out to make sure this is working properly so if we take a look here um you can see for the first example which is this one here right we get C D J which is the first column and then B a h which is the second column so that's working and then also the last one AFI right so that's working now we just need to check that it's sorted so we just need to go through every column and count those that are not sorted right um so how do we do that um so we just go through every column right um and then check if the sorted version is different than the column that means the column is not sorted in so we need to count it as to be deleted so we count zero and then we increment here and then we will return the count okay and that should be good let's submit and that works um now a slight modification we can do the way we are doing this here is basically just taking the other direction right we are taking this here and in Python you can do that with um with a sort of a transpose and to do that well you could just take zip with the star the list of strings and that will give you the transpose version of the string which will give you the column so if you have if you consider this a matrix doing this will on The Matrix which is a list of rows will give you a list of columns so that's what we can use here and basically just get rid of this and just check sorting like this um now just one thing here is that this column will be returned as a list but this one is a string so we just need to make it a list so that comparison works properly um so let's check this let's submit and this passes as well right um yeah you could also just improve this slightly or if you just want to do like a list comprehension sort of um sort of thing um you could just do the sum of these um like this instead of counting each time right and just return that so this should work properly as well and we can just return this and if we run this I submit um it passes as well yeah um yeah so that's pretty much it for today's problem
Delete Columns to Make Sorted
smallest-range-i
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Array,Math
Easy
null
278
we are going to solve the question called first bad person so in this question we are given a scenario let us first get to know what the scenario is so we have versions of all these projects so we are doing a project and we have versions of all these projects if let's say there are 10 versions of these projects if some version in between becomes a bad version because of a mistake that is being done in the project then all the projects that comes after this bad project will also become a bad project because it does not give us the desired output because there is a mistake in the project so we would have to find the first version which became bad which has the error so that is the given question for example here there are six project versions and let's say the fourth one that is the one that is being here is the first bad version then all the versions that comes after it is also a bad question and hence in this given input we would have to find the first bar version which is our fourth element so that is what we have to find with this given information so let us get to know what are the input and the output that we would have to get and also give to the user so the input is just a variable which is n is equal to Phi an integer called Phi so this represents the value or the total number of project versions that are available and we would have to return which version is the first bad version so without a series of array giving us which one is bad which one is not bad how do we find whether the fourth one is the first bad question or the second one is the first bad version for that they are giving us a tool which is a function called is bad version of they are calling this an API but let us just understand it as a function so this function is already written by our need code and we can directly use this function in order to determine whether a given version number is bad or good so using this function and the given input that is n we would have to predict the output 4 which is the first bad version so these are the inputs and this is the output now let's find out an algorithm to solve this question so here we have the example that we took as 6 Bad or six project versions okay so the obvious approach that we would think of is to check whether the first question is a bad question and then move on to the second one whether that is the bad version the third one and finally we'll get to the fourth in which we would get to know that is the first bad version and we would obviously return that value that was a pretty easy algorithm this uses the searching technique called linear search algorithm we obviously know searching every element whether that is the desired element if we find it return it and end the loop or continue until you reach the last element so this linear search approach takes a voice complexity of order of n this is obviously an easier solution but it takes an algorithm ah time complexity of O of n but are given a question requirement is to solve this in order of login so do you remember something we have a searching algorithm which such as a given element in order of log n what is that it's binary search we are going to modify our default binary search such a way that it gives us the output of whether the given a version of the project is bad or good and not just that it would return as the bad version project number which is the first in its uh array of inputs so it is written as the first pad version so let us take this example and try to solve this using binary search rather than linear search so for binary search we obviously have our boundaries right so these arrows represent our boundaries in our binary search so the left and the right pointer that we have in order to represent our boundaries which part of the array are we searching on that is represented by these arrows and the normal versions of the project is represented like this and the bad versions are represented in a pixelated colorful manner like this okay now obviously as we can see here this is the first bad version but we would have to make this algorithm find that is the first bad version how are we going to do that so how does binary search work we check whether the middle element is the element that we desire if it is we would return it if not we would check whether the value is less than the mid element or greater than the mid element and we would shrink the boundaries until we reach the final element so this is the logic behind binary search right so let us solve this example using the binary search approach for a binary search to work we obviously need three things the first thing being the array itself and we have that here the two other things are the left pointer and the right pointer denoting the boundaries of the array that we are searching currently so for binary search we divide the array into two equal halves after each iteration and will be eliminating one half such that we would have to search just the other half we are doing this so that we can reduce the amount of uh time that we spent on searching the elements that we know for sure the element is not present there and hence we have these two pointers representing that okay the normal colored versions represent obviously the good versions of the project and this pixelated colored version represents the bad version so let's get started first let's assume it to have zero waste indexing and if the question specifically says that we have to use one base indexing here let us just change that okay so starting assuming that we have zero base indexing here so zero one two three four and five so the mid value of course being 0 plus 5 divided by 2 we would get the index of the mid value being 2. so the index of the wind value since it's 2 this element would be selected as a mid element so what we do we check whether this given element is a bad version so we'd call that function or API that we saw earlier and that would return us that it is not a bird version it is a good version so it will return as false then what do we do if this version or the second element is a good version then we can certainly say for sure that all the elements that comes before it are good versions right because if let's say this version is a bad version then what do we say we also can say for shorten that this element will also be bad right because the first bad version will make the other elements that comes after it a bad version so if any of these elements were bad then certainly this element will also be bad but we know that this element is good and hence we can say that all the elements that comes before it are also good so the first bad version that we're searching for is after this element that is it is right of this element so hence we are shrinking the boundaries to just the below three elements so this is our given Arena so what do we do now again we calculate the mid value so 3 4 and 5 what is the mid value obviously 4 is the mid value so the index 4 would be selected now what do we again call the function named is bad version of so this function would give us true this time because this is a bad version so what inference can we come to uh confusion now we can certainly say that our first bad version is either the number itself or a number to the left of it can certainly not be to the right of it because this version is bad so the first bad version will be this a number or the number before it right but not the number after it and hence we can shrink its boundaries such that we eliminate all the numbers all the project versions that comes to the right of it so we have Shrunk the boundaries to just these two elements now so there are two elements three and four now again the process repeats applying binary search finding the mid value three and four so three plus four divided by 2 will give us the value 3. so what is 3 is the element that is present here so again we check whether 3 is a bad version we know that this is a bad version and hence again we would shrink the right pointer to just this number now because since this is a bad version either this number is the first bad version or a number before it will become the first bad version we can stop the loop when the left pointer and the right pointer both are becoming the same or both pointing to the same value here since the left pointer and the right pointer is pointed at the same value let us put this while loop into a stop so what inference are we saying uh can we say now if this element is a good version we know that left pointer and right pointer are equal now we are coming out of the loop if the left pointer and the right Point are pointing to the same element and that version of the project is a bad version then that is the first bad version and hence we'll return that value if the left pointer the right pointer is not same or they are same but the project is a good version then we can say that a first bad version does not exist because all the projects are good in that case we would return false or we would return minus one stating that the bad version does not exist so this is how you solve this question using a binary search approach so let us move on to our lead code and code this solution so as you can see here we are given up is bad version API that is it is defined as a function here so his bad version of intuition if you are giving it an integer it will say as whether it's a good version or a bad version so since we can see here our project version starts from 1 to n so it follows one base indexing and not zero base indexing so let us use a one base indexing here so first let's declare the pointers left and right so our left version starts from 0 sorry our left was in charge from left Point starts from 1 and our right pointer starts from yeah okay so with these two pointers being declared let us get to the while loop so left is less than right let us continue the process so what is the first step that we have to do we have to find the mid value so the mid value is the value that we use in order to shrink our boundary so that we would have to search or need less of an elements in order to make this such more efficient so first let's find the mid value here so end met is equal to the obvious solution that we would all think of is left plus right divided by 2. so this formula of the mid value or the finding the mid index will result in a problem at a later point of this solution we'll discuss that at a later point but initially just remember that we are finding the mid value here okay we'll change this formula later in the part of the video but just remember that this is where we are finding the mid value okay so what do we do next now we are going to check whether the given value or the mid value is a bad version or not so if R uh is bad version function so is bad version of myth so is bad version of mid can either return us to or false so if it is a bad version then what do we do if a given mid value is a bad version then we can certainly say for sure all the elements to the right is not what we are searching for because we know this resembles the structure that we saw here this is the case that we are checking so array of mid is a bad version it has written true then all the elements to the right cannot be the first bad version either this element is the first bad version or an element to the left of it right so we can shrink the boundaries ignoring all the elements to the right of it and that is what we are going to do here so write is equal to mid so we are shrinking the bounties until this mid value so our first bird version can be the right value or the mid value or an element before limit value okay so that is going to be a first case else if it is true or sorry in this case if it is false then we would have to increment the left value stating that it is not in the leftmost region of the array we have to search the right part of the array and why is that so this resembles the condition that we saw in the first case so this is bad version function it returns false when there is a return false if it is a good project right so we can say that all the elements to the left of this is also good and hence we are shrinking the boundary stating that the left pointer is equal to Mid plus 1 pointing to this value so that is exactly what we are done here so left is equal to Mid Plus 1. after the while loop what do we have to check we would have the left pointers and right pointers being shrunk and we would reach the end of the loop now when does this Loop when this Loop ends when left becomes equal to or greater than right so if left is equal to right and is bad version of left both these conditions are true then in that case we return true else we return false okay so this is the condition that we are using you can verify this condition with the example that we saw at last here the left value and the right value are same pointing to the same value and is bad version of this project would return us true and hence this is the element that we are searching for this is the first bad version so we should not return true or false we should return integer saying that left or minus 1. so left stating the index of the first bad version minus 1 stating such an element does not exist so this is what we are gonna return so this is a problem of first bad version of the project now let's run this code and verify our output so let us first check for the sample test cases that we have here so it got accepted now let's submit and verify it for all the other test cases that are given by lead code charging it and I think it's done time limit exceeded what issue might that have yeah okay I told you right there would be a problem in finding the mid value so that is what is causing this error so I'll explain you what the error is it is telling me that the time limit has exceeded because as you can see here the value of n is between 1 and 2 power 31 minus 1. so the left value could be 2 power 31 minus 1 and the right value could be 2 power 31 minus 1 so left equal to right in that case left plus right would give us a value that is greater than the maximum value that can be stored in an integer so this is the maximum value that can be stored in an integer variable but the summation of these two values would give us a value that is more than 2 power 31 minus 1 and hence integer overflow error occurs which gives us a wrong answer and that is what is causing this error so in order to you know uh clear this error what we can do is we can give a different formula for finding the mid value which is left Plus uh right minus left divided by 2. so this also gives us the same mid value left plus right divided by 2 but it's just a different representation of the same equation so that integer overflow does not occur so in this case if we use this formula to find the mid value integer overflow will not occur and hence our solution would be correct so let me explain why this and left place right divided by 2 is I equal so first what we are doing left minus right divided by 2 let us expand this left by 2 minus right by 2 we have hole left here so left minus left by 2 1 minus half of it what does we get what do we get out of it we get half of it so left by 2 plus write by 2 that is exactly what mid is left plus right divided by 2. so this is just another form of representing our mid value which is left plus right divided by 2 but using this version will not give us a integer overflow added now let's submit the score and verify now we have successfully passed all these test cases so this is how you solve the question of the first bad question so hope you love this video of our record series we have a separate playlist resolved for it you can always go check it out if you love this video please drop a like and see you in the next episode of our liquid series until then bye
First Bad Version
first-bad-version
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. **Example 1:** **Input:** n = 5, bad = 4 **Output:** 4 **Explanation:** call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. **Example 2:** **Input:** n = 1, bad = 1 **Output:** 1 **Constraints:** * `1 <= bad <= n <= 231 - 1`
null
Binary Search,Interactive
Easy
34,35,374
344
welcome back to the coding interview question reverse string write a function that reverse a string the input string is given as an array of characters chart the constraint to this problem is that you have to solve this problem in constant space complexity if you are given this particular array that represents these strings aclo hello we have to return this string o l e h and this is the reversed order of the given string okay now let me show you how we can solve this problem first i'm going to go through this array from left to right one by one okay first i'm going to declare to pointer first pointer will point to the first element and the second pointer will point to the last element okay then we're going to swap this two element so ace will be replaced with o and o will be replaced with h then we're going to move left pointer by one node then we're going to move left by one and right by one to the left so left will point here and right to point here and our condition is that we'll swap two element if we have left is less than right okay now left and right left point to this element e and right point to the element l so let's swap them so you'll be replaced with l and l will be replaced with e okay then left and right point to the same element and this condition left less than right is not true here so we'll not swap and that's how we can solve this problem now let's see how much solution might look like in pseudocode first i'm going to declare a function reverse underscore sting that sticks a string okay as character array let's suppose that this is the string hello that represent this array then we're going to declare two pointer left equals to zero so it will point here and right equals to length of this array minus one so it will point here then we're going to check if left is less than right then we're going to solve the two value and this is the code to solve the value okay so let's swap this is will be replaced with o and o will be replaced with h then we're going to move l to this element and r to this element then we're going to solve this two element so this will be replaced with l and l will be replaced with e okay then left and right point to this element since left is not less than right so this while loop stop here then we're going to return the string array okay in this sketch we're left with o l e h and this is my solution to this problem this solution takes big of n by 2 time complexity that's equivalent to big o of n and the solution takes constant space complexity here we're just using these two variable left and right all right guys hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video i'll see you in the next video till then take care
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
330
Loot Hello Everyone Welcome To Design To Liquid Channel Subscribe Toe 's Cutting Are Liquid 330 Blind Hard 's Cutting Are Liquid 330 Blind Hard 's Cutting Are Liquid 330 Blind Hard Questions Read And Oils Page Subscribe The Questions Were Giving Sorted In Treasury This Point To Hydride And Uninterrupted Element Subscribe Number One Dose In Form Of Elements Of Obscuritism And 120 b the subscribe to subscribe our a solar station example it will help in the turning point someone and not give what is the means all numbers from 1 to 6 af pm Remedy Plus Video subscribe combination of 200 complete the phone and listen to the sims one is body part of the important issues will pick one and subscribe midnight with 200 seeing limit for back is three layer and using free life but ironing element in to-do list on to do but ironing element in to-do list on to do but ironing element in to-do list on to do subscribe 202 banwali 228 visible subscribe to ko pure total elements of ban more android subscribe to now bread in it what is lexidi is screen 200 isi art free me appeal water element can reach side and video plz subscribe my voice elements that improve 123 lutab school se ki aunty day imported subscribe Video subscribe The Video then subscribe to the Page and other elements within that all the number do subscribe to play list a city and here in more joy subscribe suggest number track number subscribe 0 a flat settle recent post number device this way subscribe 361 581 whatsapp Research Wash Intermediate Elements From This Earn Loot All The Will Go Missing U Want To Meet You Will Be Amazed To Post One To Do Subscribe 2518 Let's Move Ahead And Share With GF Let's Move Ahead And Next Will Have It's Own I So Now Planning Tut Seervi Video Subscribe To I One Comment To Come Forward And Will Vote For Be Id Degree Holders Fluid Hello How Lamictal This Information Give One Officer Appointed Video Subscribe The Fifth Day 420 34 Number Day Water Number Id The Punisher 500 600 800 Aap Party Ke Corrupt 6 And Sit In To Look Into The Alleged Beating Of Drums Starting From Top To Entry Loot The Five 260 And Let's Move Ahead 200ns Marking Damage Bill Will Progress 720p Duel Number Five That Bigg Boss It's There In Reports Handsfree Subscribe must visit subscribe to and underwear mere number share to connect with he stand me itna yaar 10:00 today at least 20 itna yaar 10:00 today at least 20 itna yaar 10:00 today at least 20 volume increase but units twist French twist with synonyms and subscribe to tomorrow su appointed amazed of logic you will get and the way And number Gurmeet Singh and 5 minutes request for the number Veer wedding number two and number two now skin care number in to-do list mid-2012 subscribe and subscribe report Cambodia This One So Willard subscribe on 128 bit labs to-do List to-do List to-do List Will Increase In Subscribe More Channels Subscribe To 200 Degree Celsius Subscribe Number 999 Want Fight Alone In All States 09 To-Do List To-Do List To-Do List Number 2 Minute Subscribe To Hello Friends Will Pick Up 72 Marking 72 A Doubt The Best That Under Which Will Increase You Apne Dil Se OnePlus 6 Thirteen Sid Numbers From 130 Ko Unmute Sundha Thursday Ek Ansh Vishwa Is No My Dear Lord Nor Do E A Day Set Up Output Set N S2 Ko Madhuri Lukman 09 Amazing The Time To Subscribe Dhundh Nov A Boy Dishonor Dhundh Subscribe Withdrawal do that Aunty Allah will servi and what should we do you mean that this and output tax set up more convince and which will visit elements within next one India YouTube subscribe Video subscribe is hormone number second research is 2315 middle age video2019 subscribe Video subscribe Subscribe to this is so deposit labrate now school subscribe this to please remember given importance given a notification is a duty to sacrifice output elements of obscuritism the richest Ronit a slack start the process potential of beetroot and subscribe button to subscribe Video plz [ subscribe Video plz [ subscribe Video plz subscribe to subscribe our The Water Se Expected Next Person Elements 2.25 Vidra Next Possible Subscribe Video subscribe this Video Hai So This Is The Current State And Resettlement Of History And Reach All Three Idiots Subscribe A Dead To 8 Minutes Element * Avoid With A Dead To 8 Minutes Element * Avoid With A Dead To 8 Minutes Element * Avoid With U Busy Updated to three plus three idiots unknown with us next week house is not see the what is the value of reach plus one white video next element in which you will see the 0560 liked The Video then subscribe to the Video then yesterday Morning The Should You Wish That 728 At Least To Zid Two 's Tree Plus 731 And 's Tree Plus 731 And 's Tree Plus 731 And Vivid And Utilize These Not Are Next Week Half Inch 9 And Not Vidron It's Good To Three Plus 2 Indiscriminately Guys Element 900 Will Get 9 Votes That And Rigid 222 A Vivid and Investigation A View of 12 Status Limit Now What is the Next Mission Element If You are in the Middle of Twenty Three Loot 000 to Z F Ki and Sincerity 23rd Will Increase Video Subscribe Element into Consideration the Mid subscribe Video Subscribe To that without much electrification and doubling of leaders names of these questions only ride point pimples account for holding number of verses with important for decorating the reach of doctors and nurses and what do Subscribe My Life is Life in the Mid and Deep -Dub Skin More Bill Progression The Voice Of Instruments The Volume Is A Counter That Is Not Give It Means A Missing Elements Needed For Watching In This Info Which Element Do n't Forget To Subscribe And Subscribe My Elements In Urs Video Subscribe Elements Open the settings of these to-do lists Ludhiana Champion The counter was on the left side of a letter updated on which print media and definition of width of mid term and subscribe
Patching Array
patching-array
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array. Return _the minimum number of patches required_. **Example 1:** **Input:** nums = \[1,3\], n = 6 **Output:** 1 Explanation: Combinations of nums are \[1\], \[3\], \[1,3\], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: \[1\], \[2\], \[3\], \[1,3\], \[2,3\], \[1,2,3\]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range \[1, 6\]. So we only need 1 patch. **Example 2:** **Input:** nums = \[1,5,10\], n = 20 **Output:** 2 Explanation: The two patches can be \[2, 4\]. **Example 3:** **Input:** nums = \[1,2,2\], n = 5 **Output:** 0 **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `nums` is sorted in **ascending order**. * `1 <= n <= 231 - 1`
null
Array,Greedy
Hard
1930
1,898
hey everyone welcome back and let's write some more neat code today so today let's solve another leak code contest problem maximum number of removable characters and if you find this video helpful don't forget to like it supports the channel a lot and this is related to subsequences so we are given two strings s and p and we're guaranteed that p is a subsequence of the string s and if you don't know what a subsequence is it's basically if we take the string s and remove some characters from it or remove none of the characters the string s can be transformed into p so p is a subsequence of s and the relative order has to stay the same so basically you know if we had a string abc and we had ac is a subsequence of abc because if we remove the b the relative order of these two characters matches this string this is the subsequence this is the original string and we're given an array of removable characters so each value in this array three basically tells us that index three of the string s is removable so if we remove index three of the original string s then the question is can p still be a subsequence of the string s so you know we're trying to find the maximum number of removable characters from starting at position zero that we can do and remove from the string s such that p is still going to be a subsequence of s so you know we start at the beginning so maybe we remove three and it's still a subsequence we removed the first two we remove three and position one it's still a subsequence but then maybe we get to zero if we remove zero then it's no longer p is no longer a subsequence of s that would tell us that we can only remove the first two characters from the removable right the first two indices from the removable array such that p is still a subsequence of s so the main thing to know is how can we determine if two strings are subsequences that's the pretty straightforward part of this algorithm and once you know that you can easily do the brute force so let's say we have one string s and we have another string p a b basically we're going to start at the beginning of s and we want to find every single character in p so we're looking for now we're looking for an a right we look at the first character it is an a great right next we're looking for a b and of course we find the second character as a b and then we're done right we found every single character in p therefore p is a subsequence of s now let's say we actually didn't have these first three or these first two characters is this still a subsequence can this string still be a subsequence of this yes it can let's figure it out so we start at a again we have a c right now so we have a c we did not find a so we have to skip this c next we look at the second character is this an a that we're looking for yes this is the a we're looking for so we're done with that and we're done with this a now we're looking for a b we find a c that's not what we're looking for find look at the next character yes this is the b that we're looking for therefore we found the other b2 now what if there was no b in this string if there wasn't a b we look at c okay c does is not the character we're looking for then we got to the end of s and so we never found this b that we were looking for so in that case we would return false p is not a subsequence of s so that once you know that algorithm it's a linear time algorithm basically at worst case the length of the longer string aka s then basically the brute force solution of this problem is not too difficult we're going to go through every position and removable look at the first one right let's say we remove three from this string s we remove this character and then we check is p a subsequence of that we do that in o of n time and we're basically gonna keep doing that right next we're gonna say okay remove position one so we remove position 3 and we remove position 1 and we do the same linear time algorithm check is this a subsequence so worst case how many times are we going to do it's going to be o of n which is how long it takes to find if it's a subsequence multiplied by k because k is the number of removable indices that's the brute force and in my opinion it should be good enough to pass this problem but for some reason it's not and the slight optimization you can do is to instead of being n times k we can make this n times log k basically by doing binary search on the removable array so we're finding the max number of k values the max number of indices from this removable array that we can remove from the string s such that p is still going to be a subsequent so basically just doing binary search instead of doing an iterative brute force we're doing binary search on the removable array once you know that the code isn't too difficult so let me dive into it now it's going to be n log k solution so remember the first thing we want to do is be able to check if a string is a subsequence of another so let's define that helper function here so let's say we're given a string s and we're given a potential subsequence we want to know is this subsequence an actual subsequence of s so we're going to need two pointers like i showed i1 i2 for each of the strings respectively they're both going to start at the beginning right and we want to continue to go while i1 is inbound so i1 is going to be the pointer for s and i2 is also in bounds which is going to be the pointer for uh the subsequence now remember we're going to be comparing the characters right so we're going to look at if s of i1 is not equal to s of i2 that means we did not find the character we were looking for remember we're looking for this character or not s but a subsequence let me fix that so we'll look in the subsequence string we're looking for this character if we don't find it in s then we have to move to the next position so we're going to say i one plus one and then we're going to continue to the next iteration of the loop now there's one other thing i'm gonna have to do here as well let me show you so if i won the pointer is in the removed pointers that's another condition where we're gonna have to skip that character remember potentially we are removing some pointers or some positions from s so i haven't shown that yet but we're going to get to it later we're going to maintain a removed set which is going to tell us what are all the characters that have been removed so far if we're at a removed character in the string s then we're going to skip that character but let's say the characters do match and the character hasn't been removed in that case that's good then we're going to increment both pointers so i1 increment by 1 and i2 increment by one that means we found that character we were looking for now we can look for the next character and once this loop is done executing that means one of these pointers has gone out of bounds how do we know if we actually found a subsequence or not well if the i2 pointer went out of bounds that means we were able to find every character we were looking for so basically we can return true if i2 is equal to the length of subsequence that means it went out of bounds then we're going to return true if it didn't go out of bounds that means we were not able to find every character we were looking for then we return false okay so that's great now let's actually get to the binary search portion so initially we're gonna define our result to be zero that means zero of the removable characters we actually removed and we're gonna be returning what's the max number of removable characters can we actually remove and we're gonna have two pointers because this is binary search so zero left is gonna be at zero and the right pointer is going to be at the length of removable minus 1. because remember we're doing the binary search on the removable array we want to know what's the max number of removable characters we can actually remove so let's continue this binary search while our pointers are valid so while left is less than or equal to right we're gonna compute the middle in python to do integer division we're gonna have to do double slash so left plus right double slash divide by two and the removed set that i wrote up here we're actually not going to be defining it up there we're going to be using it down here so this middle value tells us we're going to take the first m values from the removable array and actually remove them from s and we're going to track which ones have been removed in a set so we're going to have removed set and the first m values from the removal so we're going to take removable sub index it so from the beginning all the way to m plus one because we know python the second index is non-inclusive so the second index is non-inclusive so the second index is non-inclusive so these are the characters we removed from s these are the positions of the characters we removed from s so now all we're going to do is call our binaries or call our helper function is subsequence so we'll pass an s and we'll pass in the sub sequence now you might not like the style i'm doing this with the way i'm doing it is since this variable is defined here and you know this is a function defined inside of a function it will have access to the removed set that we just defined but if you really wanted to you could explicitly take this set and pass it into this function i just didn't do that but if you prefer to you can see the removed set is being referenced right on this line so we're going to call this is subsequence if it returns true that means we found a potential number of removable characters so we're going to take our result and set it to the max of itself and m but not just m plus 1 because we know that what we're trying to return is the number of removable characters we can actually remove not the index m tells us the index so we know arrays are index zero so we take m plus one and then the else case is also something we have to worry about because this is binary search we're going to be updating our left and right pointers differently depending on what the result was if we did find a subsequence then we're going to be greedy we're going to say hey maybe there's even more that we can remove from removable then we're going to set our left pointer equal to m plus one basically we're going to be searching to the right maybe looking for even more that we can remove from the removable array else case is going to be the opposite we're going to say okay we couldn't remove the first m so let's try even less maybe we can remove less so we're gonna set our right pointer to m minus one we're gonna be looking to the left in our binary search and eventually our binary search will stop we will have updated the result if we ever found a certain number that we could have removed and then finally at the end all we have to do is return that result which will tell us how many from the beginning of removable that we were actually able to remove okay oops i'm pretty dumb so when we're passing into this is sub sequence we're passing an s as the original array and p as the subsequence not actually that so hopefully you were able to catch that on your own my stupid little mistakes but other than that you can see that the solution does work and it's somewhat efficient i don't know if somebody was able to find a better solution than this but hopefully 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
Maximum Number of Removable Characters
leetflex-banned-accounts
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters from `s` using the **first** `k` indices in `removable`, `p` is still a **subsequence** of `s`. More formally, you will mark the character at `s[removable[i]]` for each `0 <= i < k`, then remove all marked characters and check if `p` is still a subsequence. Return _the **maximum**_ `k` _you can choose such that_ `p` _is still a **subsequence** of_ `s` _after the removals_. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. **Example 1:** **Input:** s = "abcacb ", p = "ab ", removable = \[3,1,0\] **Output:** 2 **Explanation**: After removing the characters at indices 3 and 1, "a**b**c**a**cb " becomes "accb ". "ab " is a subsequence of "**a**cc**b** ". If we remove the characters at indices 3, 1, and 0, "**ab**c**a**cb " becomes "ccb ", and "ab " is no longer a subsequence. Hence, the maximum k is 2. **Example 2:** **Input:** s = "abcbddddd ", p = "abcd ", removable = \[3,2,1,4,5,6\] **Output:** 1 **Explanation**: After removing the character at index 3, "abc**b**ddddd " becomes "abcddddd ". "abcd " is a subsequence of "**abcd**dddd ". **Example 3:** **Input:** s = "abcab ", p = "abc ", removable = \[0,1,2,3,4\] **Output:** 0 **Explanation**: If you remove the first index in the array removable, "abc " is no longer a subsequence. **Constraints:** * `1 <= p.length <= s.length <= 105` * `0 <= removable.length < s.length` * `0 <= removable[i] < s.length` * `p` is a **subsequence** of `s`. * `s` and `p` both consist of lowercase English letters. * The elements in `removable` are **distinct**.
null
Database
Medium
null
875
hey what's up guys this is John here so today I want to talk about another at least call the problem number 875 Coco eating bananas okay so Coco loves to eat bananas I'm assuming Coco is like a monkey yeah and there are powers of bananas the numbers the ice-pile has like pile ice banana the ice-pile has like pile ice banana the ice-pile has like pile ice banana and the cards have gone we'll come back in eight hours and so Coco can decide her speed of eating the bananas basically every eat the speed is K which means every hour Coco can eat case capable honest and each hour she can eat Capon honest and if the Power has less than K bananas she eats of them instead and but she won't be eating another pile of bananas right and Coco likes to eat slowly but still wants to finish eating all the bananas before the guards come back so basically this asked us to find the minimum K that Coco's can eat all the bananas in H hours okay so basically we have three parameters here right so were three variables here the first one is the pile of bananas right second one is H that's the total hours we have to finish all the piles are bananas and then we need to get the minimum of K right minimum of K so you know every time when you guys see I like us about around 3.30 variables like there's a like array 3.30 variables like there's a like array 3.30 variables like there's a like array of something and then there's like at second the factors and then it asks you to find the third factors right either a minimum or maximum so then it almost tells you that in this case you need to use a binary search all right I think that's a very clear signal that you need to use the binary search in this case okay so for binary search we need to find a lower bound and upper bound right so in this case what's going to be the lower bound basically the lower bound is gonna be the wisdom the slowest a speed possible right I think it's clear that it's gonna be one right regardless of how many bananas how many piles were how long the H is right the lower bound is always one that's the basically eating one banana either at one hour that's the slowest speed we can get right and then what's them was the high bound was a lower the higher bound right the upper bound sorry low and high right and what's the higher bound here know since one our since I like each hour we can only eat one pile basically right because basically what does it means it's like no regardless of how fast we can eat right we can only eat one pile per hour right so the speed per out product to the highest speed we can I mean we can possibly be using is the maximum around its a maximum among all those piles right for example did this one so the maximum speed we will ever need is 30 right because we're 30 we can finish each power within one hour that's the highest we need you like for 30 if 50s of course it's yes off with 50 or 50 40s we can also finish our powers in one hour but does it's not necessary right so that the highest we will ever need is the highest the biggest number among all those numbers right so then I think for this binary search problem we will also have a template right basically we will gather like middle right it's a lower bound upper bound and then we'll have like a helper functions to help us decide which this middle values can be satisfied I mean can we finish the job can we satisfy the conditions in this problem right if it can then we know okay we are fine we'll find a result in this case right so in this case let's say so basically our helper function in the in this for this problem it's gonna be with the with this middle speed can we finish eating all the other piles within eight hours right if it can then we know okay since we're trying to find the minimum value of this K right then we know okay we can try it we can try a smaller speed since at this moment we know it's it can finish then we want to see we won't find the minimum that's why we'll be moving then we'll be sorry we'll be moving to the left half basically and then we are discarding there at the right half right basically we're then assigning this right to the middle the reason we're sending the middle not me though minus one is because it's it can finish in eight hours but this and this middle might my house be our result we don't know that yet all we know is that middle can satisfy our condition and we need to find if it if this one is the smallest one right otherwise we just to a left he goes to middle class one right so we do a plus one here because we know with the middle speed we cannot finish eating all the bananas within HR s no me though is not our meter will not be our result then we need to try out a different one right okay so with that in mind let's try to code this thing right so like I said we need like helper functions right so what if I can finish let's just call it finish all the bananas right and then we kind of have like K speed right let's - okay here and we'll implement this - okay here and we'll implement this - okay here and we'll implement this matter later on but first let's to define our lower so I prefer using I prefer use the left and right you know you always use the lower and upper the name inclination doesn't really matter it's a trust your own preference so like I said the upper bound will be the maximum of the piles right and then while left is smaller than right that's basically our normal binary search template we do a middle equals to what left + right - left / - right what left + right - left / - right what left + right - left / - right then we try that so for those who do still don't know why we're doing this left + right - left + right - left + right - left / - instead of a left + right that will / - instead of a left + right that will / - instead of a left + right that will prevent the integer overflow in case the laughing writer they're both huge numbers they're almost like reaching the biggest numbers if we add this like huge number left to the right in might overflow that's why we use this a lot of class right miners left use this trick to prevent that from happening so can finish right so Mito if can finish if basically if it can finish with this speed right then we know okay we can try us even a smaller slower speed right that's why we discard the right side excuse me and then house right house we do a left equals to middle class one right like what we discussed before the reason we do a middle instead of middle minus one it's because the middle might be our rate might be our final answer we don't know that right but that's why we still want to keep this middle if we do a middle minus one here you know we'll be missing this we might be missing the real answer right that's why we will be doing this right here with closed inclusive the middle here and then in the end will return the right side actually in this case we can either return left or right because when this wire loop is finished and the left will be equal to right okay and then let's okay now let's implement this like finish can finish our functions so what we're trying to achieve here is we want to check with the case speed can we finish eating up all the other panels within H hours right so now let's hours needed right so two hours needed here okay and for freestyle right in piles here what do we do are we simply do what we can use power divided by K right and we can do a sailing here right the reason we're doing a sitting here is because let's say the K let's see the K is to speed is two and the P the power has three power 3 and the case - so how many hours we need to finish - so how many hours we need to finish - so how many hours we need to finish eating this 3 here - right because eating this 3 here - right because eating this 3 here - right because at one point 3 divided by 2 is 1 point 5 and then we need to do a ceiling of this because we need to we need how many hours we need right ok pretty straightforward and then 2 hours nearly right and then we do up basically which accumulate out hours we need right and then in the end what we do we return right we compares if the hours we need it's no it's not greater than then 8 right if that's the case we know ok we know this one is true we can finish otherwise we return false all right ok I think that's pretty much it is I think so yeah that's all about this it's probably ok let's try to run this okay this one passed let's run it cool so yeah it passed success successful all right yeah pretty straightforward like binary search problem I think the only thing is you have to be aware right is this kind of problem right like with this like array and the target and then ask you to find to calculate another firewall either of its minimum and maxximum is this kind of three factors most likely you will be using a binary search and all once you are once you know it's a binary search all laughs is to try to find out lower bound and upper bound and then how can you divide right how can you divide it into two and how can you move to the left half or the right half okay cool guys I think that's it for this problem yeah thank you so much for watching the video and I'll be seeing you guys soon bye
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
1,676
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1676 lowest common ancestor of a binary tree 4. let's read the question prompt given the root of a binary tree an array of tree node objects nodes return the lowest common ancestor lca of all the nodes in nodes all the nodes will exist in the tree and the values of the tree's nodes are unique extending the definition of lca on wikipedia the lowest common ancestor of n nodes p1 p2 dot pn in a binary tree t is the lowest node that has every pi as a descendant where we will allow a node to be a descendant of itself for every valid i a descendant of a node x is a node y that is on the path from node x to some leaf node so if we look at our example and we're given this binary tree here and we have the nodes given to us seven six two four we should return five why so as we can see you know we have our node two oops let me use a different color here it's a little bit easier to see okay one second okay so if we you know we have six two four seven and the first point where they all converge is going to be at this five so this is why five is the lca so this problem may seem complicated because now we're given a list of nodes but in reality the fact that all the nodes exist in the tree makes this problem extremely easy uh essentially it's going to be a carbon copy of how we solved lowest common ancestor of a binary tree one um where now instead of checking whether our current node basically equals to p or q we just have to check if the current node that we're processing is in this list of nodes and if it is then we can return true you know to the next level so for example you know we're still going to do the dfs in the same way right we're going to start at the root and we're going to say okay you know um you know does this node is it in nodes here okay no it's not so we need to go into its left trees so we're actually going to get to the five here and because the five is um well it's actually not in here sorry so you know we check okay is five in nodes no it's not so that means we need to go into its left subtree and right subtree so we're going to go into its left so we're going to be at the six is six in nodes yes it is so that means that we can return six to the five and then you know we go into its right subtree we see okay is two in here um yes it is that means that we can return the two we don't even have to go any further uh which is quite nice because in i think lowest common ancestor you know version two we had to make sure that p and q were in the tree this time we know that they're in the tree so we don't even have to go any further as soon as we find a node that's in our nodes here we can actually just return that node to its parent so this uh the five will receive six and two and since it received you know two non-null uh from its left and its right non-null uh from its left and its right non-null uh from its left and its right we can simply return five here and then what we wanna do is now we're going to go into three's right subtree so we go to its right we're at this one is it in nodes no it's not so okay let's go to its left subtree uh is zero in its nodes no it's not uh and then we try to go to its left and right obviously that don't exist so this would simply return none and then you know we go to the right subtree is eight in nodes no it's not okay um we go to its left we go to it's right obviously they're null so nothing to return there so we're simply going to return none here then you know since we have none here we can only return none and then from the three you know our global kind of recursion will spit out you know five here because it's the you know the non uh null element that i received here um from both the left and the right so five would actually be our lca so that's how we got it um like i said solving this question is extremely straightforward all we need to do is do the same algorithm we used for lca of a binary tree one except this time instead of checking whether you know the node is equal to p or q all we have to do is check if the current node is in our nodes here and if it is then we can return it and we're gonna do the exact same processing as we did in lca one and the reason for this is because we're guaranteed that the nodes will exist in the tree so we don't have to worry about things not being there which is really convenient and makes this problem a carbon copy of um you know the first iteration of the problem i don't know why leak code created this problem because it's really like it's the exact same thing um so anyway let's write the code and we can see how it's implemented i'll see you in the editor we're back in the editor now let's write the code recall that i mentioned that when we're doing our processing we want to check whether or not the current node that we're at is in our you know nodes here that were provided now notice that nodes is given to us as a list of tree nodes and you should know by now that doing any sort of lookup inside of a list is going to be a big o of n operation which we don't want to do because it's slow we want to do the lookup in constant time so the re uh to combat this what we're going to do is we're actually going to say nodes we're going to transform it into a set so that way we can do a constant time lookup to see if a node exists in nodes we don't want to be doing a big o of n operation every time because that's going to make our runtime complexity big o of n squared which we don't want to do so now what we can do is write our dfs function it's going to be basically a carbon copy of you know lowest common ancestor of a binary tree one so we're going to say def dfs and you know we're going to take in a node and we're going to say okay well you know our node has to be non-null for you know our node has to be non-null for you know our node has to be non-null for us to do any sort of processing and checks on it so let's make sure that we actually have a non-null node so we're actually have a non-null node so we're actually have a non-null node so we're going to say if not node we can simply return none there's nothing we can do here if the node that we have is null so now what we want to do is we want to make the check of whether our current node is in nodes if it is then we don't have to check the children because we can just return the node and the reason that we can do this is because we are told that uh where is it um all the nodes exist in the tree so if one exists we don't have to check the bottom ones which is quite nice so let's say if node in nodes oops we can simply return the node which is nice otherwise now we have to go into its left and right subtree to figure out whether or not the current node is an lca so let's do that we'll say left equals dfs and we'll go into node.left dfs and we'll go into node.left dfs and we'll go into node.left and we'll say write equals dfs no dot right oops uh okay now if both left and right are not none then we know that the current node is rlca and this is basically following the same pattern that we had in lowest common ancestor one so we're going to say if l and r then we know that our current node is the lca otherwise we just want to return l or r so whichever one is non-null if l or r so whichever one is non-null if l or r so whichever one is non-null if they're both null then obviously it'll just return nulls in the next level but if one of them is not null then it would return the one that is defined and that's our dfs function all we have to do now is literally just return dfs calling it on the root and we should have solved this problem so let's make sure our submission works here submit it and there we go so we've solved it before we go let's touch on the time and space complexity so the first thing that we do is notice that we transform our nodes from a list to a set so this operation is going to cost big o of n time because we have to um you know basically go through the entire thing and transform it into a set then this dfs you know we could potentially have to traverse the entirety of the tree uh in the case that you know the two nodes that uh that were you know we could be given a list of nodes which is only length one or maybe it's length two and you know those would be the last two nodes in a tree that was like very heavily skewed so if it was just like left um subtrees or just right subtrees we would have to go to the very bottom in the worst case uh if those were you know the two nodes that we were looking for so in that case because of that our worst time complexity is going to be big o of n for the actual dfs function here which means that you know this is going to be big o of 2n which asymptotically is just big o of n so this is a linear solution space um because we have to transform our nodes into a set this is going to cost big o of n and then for the actual recursion if we're counting the stack space then you know it's gonna cost big o of n uh space because we have to recurse potentially through you know the entire tree here in the case that it's heavily skewed and it's just left sub trees or just right subtrees so it's going to be big o of n or it could be constant if we don't want to count the recursive stack you know that's something that you'd ask your interviewer okay do you want to count this if not it doesn't actually change the time complexity of our algorithm it's still going to be oh sorry the space complexity it's still going to be big l of n on the space and there's nothing we can do about that you know we have to do this um this set transformation here and the reason we knew that is because if not you know we would be doing a big o of n operation here for this if node in nodes every time and that would take our runtime complexity to actually big o of n squared which is a lot worse than big o of n so that's the reason why we have to pay this space um complexity cost in order to get the set so that's how you solve this problem again this is super simple um i don't know why this problem exists this is like a carbon copy of you know the first iteration of the lowest common ancestor problem um i guess just leak code needed more problems or something but yeah it's essentially a carbon copy the only difference here is that you just check if node is in nodes except for other than you know uh whereas in the first question it was like does it equal to the node p or q that you were given anyway i hope you enjoyed this video if you did please leave a like comment subscribe let me know what other videos you want to see i'm more than happy to you know make videos for you guys just tell me what you want to see i'll try to solve the problems come up with a nice solution uh and try to explain it in a way that makes sense for you guys so let me know what you want to see i'll be happy to do that for you and in the meantime happy elite coding
Lowest Common Ancestor of a Binary Tree IV
minimum-number-of-days-to-eat-n-oranges
Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**. Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of `n` nodes `p1`, `p2`, ..., `pn` in a binary tree `T` is the lowest node that has every `pi` as a **descendant** (where we allow **a node to be a descendant of itself**) for every valid `i` ". A **descendant** of a node `x` is a node `y` that is on the path from node `x` to some leaf node. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[4,7\] **Output:** 2 **Explanation:** The lowest common ancestor of nodes 4 and 7 is node 2. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[1\] **Output:** 1 **Explanation:** The lowest common ancestor of a single node is the node itself. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[7,6,2,4\] **Output:** 5 **Explanation:** The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * All `nodes[i]` will exist in the tree. * All `nodes[i]` are distinct.
In each step, choose between 2 options: minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) ) where f(n) is the minimum number of days to eat n oranges.
Dynamic Programming,Memoization
Hard
null
387
foreign hey this is Topher with the lonely Dash and today we're going over lead code question 387 first unique character in a string given a string called s find the first non-repeating character in it and first non-repeating character in it and first non-repeating character in it and return its index if it does not exist return negative one so below I have two examples of an s that you could be provided the first one has two A's two B's and two C's in it and the other one is the word derived now if we were to look at this we would ask ourselves hey is there any non-repeating character and is there any non-repeating character and is there any non-repeating character and the answer is no a repeats twice B repeats twice and C repeats twice and therefore if we were going to have this as our example we would be returning negative one however if we didn't have that and instead we had the word derived it would be a little bit less obvious so the question oops the question would be okay is we have a d here is d a repeated character and yes it is repeated it's over here so the first and the last letter is both these so okay e is e repeated yes there's two e's is R repeated and the answer is no R would be the very first letter we have here that is non-repeated so we would have to say is non-repeated so we would have to say is non-repeated so we would have to say okay look there's an r in what index is this R of the string and of course this D is at zero E is at one R is at two so the answer we would be looking for of course is 2 because R is at the second or at the number two index so how are we going to actually figure that out and the answer is by using either a dictionary or a hash map whichever term you really want to use and here's the example of what the hash map will end up looking as for the word derived so as you can see I've got its name right here and it has key value Pairs and so the key here is D and of course the value is 2 because there are two D's in the word the key here is e there are two of them in the word r 1 I 1 and V1 and that's just basically counts the number of each of the letters here so how is this going to work because the numbers in our dictionary don't tell us the actual index and we're basically either going to use a pointer or we can just index ourselves through the word derived and we do it like this so let's say we took this very first point uh here oh let me do this real quick there we go so we go to this first Index right and this is the D and of course this D is index zero and we would say okay is D in our dictionary yes it is in our dictionary is the value of D1 if it is then we will just return r0 if it's not one which it's two we're going to move on and we move on to the next letter better and we'll ask ourselves okay is this letter which is at index one is it in our dictionary or our hash map yes it is the E value one no it's not so we not we are not going to uh return that one we'll move on to the next index here which is index two it's an R is r in our dictionary or our hash map the answer is yes is the value one yes it is which means it is the first letter that is only there one time meaning it is not repeated so our answer is going to be 2 because that is the index of the first non-repeating character in our string s non-repeating character in our string s non-repeating character in our string s let's see if there's any edge cases we need to consider at this point the constraints of the question basically just tell us that there is going to be at least one character in our string that is provided and that our string was only going to consist of lowercase English letters which kind of makes it a bit easier for us to understand we don't have to go uppercase to lowercase or understand punctuation or any other kinds of characters that exist so looking at these constraints I suppose it's possible that we would have a string that consists of only one letter so we could right at the beginning say hey if the length of our string is one we're going to return 0 or like index zero we may not have to since the way we're going to be writing our algorithm is going to take care of that anyway so let's just start writing some pseudo code our pseudo code for this is pretty straightforward the first thing we're going to do is create a dictionary or hash map that contains the let's see key value pairs representing the character and Times of rep repetition there we go I can spell that's pretty simple and straightforward depending upon what language you're in it could be very easy to do in Python you can just say create counter in Java JavaScript it's uh slightly more complicated but we'll go through that then we need to iterate through each character of s right and that's going to be either our pointer or our index but we're just having to go through each character of the S that's provided if the character is krak c-a-r-i-c Cara wow I can spell today c-a-r-i-c Cara wow I can spell today c-a-r-i-c Cara wow I can spell today care c-h-a-r-a-c-t-e-r character there we go c-h-a-r-a-c-t-e-r character there we go c-h-a-r-a-c-t-e-r character there we go uh if the character is in the dictionary or hashmap and has a value of one what are we going to do well we are going to return the index of the character that's simple and straightforward otherwise meaning it's in the dictionary hash map and has a different value we're going to move to the next character right because that means that it is repeated and it will not be the very first instance of a character that's non-repeated so then if the loop non-repeated so then if the loop non-repeated so then if the loop uh ends without returning a value what do we do well we're going to return negative 1 because that means that there is no instance of a character that doesn't repeat and that's all of the pseudo code it's very Bare Bones but we're going to go over how each one of these kind of sections works when we write our code so let's get going as you can see we just copy and pasted our pseudocode into the Java work area of the lead code website we're going to follow along so the first thing we need to do is create a dictionary or hash map that contains the key value pairs representing the character and Times of repetition now that sounds simple but it's a little bit more complicated so in Java we need to create a hash map right and what is the hash map well we're going to have a character and then an integer right because the integer is going to be the number of times that the letter or the character exists we're going to name it count and it's new and it is a hash map and it will have a character and integer okay there we go get ourselves all the way through it there we are so we've created an empty hash map here okay and so now that we've created our empty hash map we are going to have to fill it with some something right we're gonna have to fill it so we're going to fill it with let's see integer and we're going to use n we have to fill it with characters but we need to know how many of them there are first so we're going to end of identify the length of s first right for in Java we have to know how long this is going to be so we got to figure out the length of our string now we have to iterate through it right so we're going to iterate so for integer let's see I equals zero as long as I is less than the length of our string which is n in our case right because we figured out what the length of it is and I is going to iterate one time each time what are we going to do well we have a character called C which is going to be S Care at I okay so we're identifying so Char at is basically saying what is the character in s at this position and so we're identifying the character at all of the positions throughout s and we're going to call that character C just so we can give it a variable so what are we going to be doing with this well we're putting this character into our empty hash map here okay and we have to do that over and over again and if it repeats we need to make sure we don't continually add versions of it but we just increase the count okay so we know that our hash map called count we are putting something into it and we're putting the character whatever it happens to be which is C there and we are going to and this is somewhat recursive let's see let me just type it out first while I think about it get or default C comma zero Yap and plus one okay there we go so essentially let's tear this apart okay so get or default so we're trying to get C right we're finding C or the character which is already in our hash map right and we are figuring out what the number is in C how many of those characters are already there and we're adding one if it's repeated okay or we're just adding it so we're putting something into our hash map it is going to be the character which we are currently iterating on and if it's already there we're just going to add one to this number otherwise we're adding we're just putting it in there with a zero with zero all right so if a character is in our hash map only one time it's actually going to have zero as its representation if it's in there twice it'll be one if it's in there three times it'll be two okay hopefully that makes sense it gets a little complicated if not take a look at get or default and put and Char at character at a little bit more but for right now just know that this line basically adds whatever character we are on into our hash map up here and if it already exists we're just adding one to the number of the key value pair this integer is going up by one okay and that's what we needed to do in order to create our dictionary or in this case create our hash map that contains our key value pairs so by now we'll have our letter and numbers all worked out so I'm going to remove this line okay now since we are done with that we are going to iterate through each character of s so we're doing another for Loop so 4 and we're going to use the same kind of nomenclature integer I equals zero as long as I is less than n I plus okay so we're iterating once now we're iterating through it all over again and this time we're going to compare it to what is in our hash map so if count dot get s dot Char oh Char at I oops I there we go make sure I did all of that right chart I get count okay and that equals one there we go so here we go what we're doing is if the character is in the dictionary or in this case a hash map and has a value of one so we are getting the value of the character at I from our dictionary and if that equals one what are we going to do well if that's the case we know we have to return I right because I is the iterative unit we're using to Tran to go through S as a string okay other than that so otherwise we move on to the next character so we don't actually have to write anything beyond going Beyond or Beyond going past the next character all we need to do then is end the loop and when the loop ends we return negative one and that should be all of the code in Java and it's a little bit complicated for a beginner no problems there but let's hit run code and make sure that I don't have to debug anything oh hooray and let's hit submit to make sure it fits all of the test cases awesome not crazy fast uh use a pretty good it's pretty good on the memory but this is a really great way of solving this problem and it really forces you to create your own hash map out of a string of characters and then you have to iterate through those characters to find where the index is so that is how you solve first unique character in a string using Java foreign
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
95
hello everyone welcome to my YouTube Club today we will be solving another daily lead code challenge and the challenge name is unique binary search twist part two so the challenge statement goes like this given an integer and return all the structurally unique binary search trees which has exactly nodes and you have to construct those nodes from values 1 to n and you may return your answer in any order so the binary search is that you will be constructing these ones the order does not matter here so you can return them in any order so let's look at the constraints what are the constants constraints are pretty low uh and is of the order 10 enemies of the order it so as long as Your solution does not exceed 10 raised to power rate operations or it does not equal access it or reach is equal to it you will not get a clearly so constraints are not of a major value here so those of you who are not familiar with how the time complexity accepted solution varies with the input size M complexity of selected solution where is with input size I will provide a link prioritical describing this then uh you will understand what I am talking about here basically right now what I can tell you is in one second URL of 10 is to Power 8 operations and if your Solutions operations exceeds or becomes equal to 10 is to Power 8 then you may get a tle so it should be lesser than that and since the constraints are here pretty low uh so you will not reach that complexity and you have to also know that given for a let's say n numbers are given n numbers and you have to construct let's say a binary tree from these n numbers then there will be total number of metal and nth Catalan number three is possible number of we are still possible arteries are binary search tree uh number of binary substitute possible so what is the cattle line number Catalan number is just a sequence of numbers just like there are sequences like Fibonacci pardon me if the spelling is incorrect I hope it does not affect your understanding so this is just a sequence of numbers and nth Catalan number is generated by this formula uh two n factorial divided by n plus 1 factorial by n s factorial for example uh let's move to uh the sample input here n was given three now if you want to find out how many minorities will be possible uh we will put any in the formula or two into three factorial 4 factorial plus 3 factorial and it will be 6 factorial for factorial three factorial so which turns out to be 5 so I hope you are able to understand so we know how many times at least how many times our solution would run so that all the minorities are generated foreign complexity this will be the time conversion that the approach I will be discussing in the next slide so let's quickly dive into the approach what we will do is uh let's say here you let's say you are given n numbers 1 2 3 or five and those of you who are not familiar with what a BST is PST is a such a tree that it's root node the left part of its whatever is in the left part of the root node it will be smaller than the root node smaller than the root nodes value where it is in the right part of a it will be greater than the root greater than the not the value all the values here will be greater and now the values on the left side will be smaller so if you do a in order traversal those of you who are not familiar with what is the in order traversal I will also provide a link for these two so if you do any order types of VST you will get the sorted output so the numbers you will be getting the notes or the sequence of the notes you will be getting will be in the assorted convey and also all the sub parts or the sub trees of these nodes let's say these are the sub trees this will also form the follow the same property if these node will be smaller than uh these nodes will be these ones are smaller than this and this one these nodes are small greater than this so I hope you are able to understand what a BST is anyhow you will be provided a link where you can explore further what bsts and what in order to also be used so how will be constructing the minus history we'll do is for the root of the wire research P we will be having an options these end options we can pick any one of them let's say I pick fourth number I pick this number and so what will happen is since I mentioned that if you do the inorder travels you will get all things in sorted order so since these are the numbers smaller than the root is smaller so left of 3 is smaller so what you will do is it will be the root and these values will be in the left sub tree and these values are things greater than the current route that we have considered it as a root as of now and you were having n options to consider root so this option from 5 2 and will be in right subtree so this will be a uh binary substitute possible there are other various Services possible also for example if you take v as root then you will be having one two in the left subtree and uh from 4 to n in the right subtree so these are the options that you will be accessing now if I somehow give you and we will be doing so in a recursive let's say now somehow I give you uh let's say let's talk about this left part first left part will be one two three so you will again be having three options to consider root for this subtree and depending upon which ones are options you consider you will be having three different uh trees in the this generated from this particular subtree sub trees will be generated let's say T1 T2 T3 and this let's call this left part similarly for the right Port also you are having Choice 5 12 so let's call this right part similarly subtree is depending upon the Which choice you make for the current route you will be getting past even T2 PHP and so on so if I give you these two lists of our different sub trees Roots depending upon your soil what choices you will make when you are having the current choice that you have made F4 and you are having left part here as the list that is having list is having the roots possible for left sub trees and similarly whenever you will be making us up to you will be then again following this logic according to your choice available The Roots will be generated and a list will be available so this consider the this as a recursive function you are generating two lists uh one is of left part one is of right part and the list is having the possible roots for that subtree uh now let's say uh how we will be generating the whole trees what you will do is uh you fix root and the right subtree or left subtree depending upon your choice now here I am fixing uh two things uh I am fixing the root and the right subtree okay and then if I fix this I will be iterating over the left part based upon the output value I have fixed here each value each possible root in the left part D1 T2 T3 and so on we'll generate a different tree so I hope you are able to understand so you can also fix the left part and iterate over the right you can also fix the left subtree let's fix it and fix this also let me quickly change the color so that you won't be getting confused uh let's say right now this is not fixed what you will do is over these two fixed things for each value in the left part you will be making combinations with the right part so I hope it's clear and it will generate different sub trees and you will be doing this thing in or recursive manner so that each subtree uh the different combinations will keep on generating and at last when the recursion will what will the recursion return recursion will return you all the software is generated and uh you're going to be doing extra work in uh making same choices again and again because you are storing the calculated routes calculated roots of sub trees in left part and right part these are nothing but the lists that are carrying the possible number of roots based upon your choices which will be available in the left subtree at the right sub tree right part okay now what we will do is our time complexity of the solution it will be number of binary search field possible into work done or constructing them which is nothing but uh number of binary search is possible for with n values uh one from one to n will be and that Catalan number into work done what will be the work done it will be nothing but l and are the number of values or number of in BST so it will be our time complexity and since the what we will the space complexity here um what we will the space complexity it will be nothing but is used for storing sub trees left part plus right part paste your full recurs instead regardless Tech space so this will be your face complexity uh now let's quickly dive into the coding part of the problem there you will be able to understand the solution in a much clearer way now let me quickly zoom out so that you will be able to see more of the course part yeah what we have done is we have taken range of numbers from 1 to n for the range of numbers 1 to n V are considering the choices for the root of binary search please firstly possible so initially you will be having one-to-one choices one-to-one choices one-to-one choices which will be nothing but let's call uh one here is start and end and as what you will be doing this whole thing recursively that I have just explained you here uh this thing you will be selecting any one choice for the root and depending upon the root rest will be included in the left part and the right part so what we have done is if the start it happens to be greater than the end you will add null to it may happen that for example if let's say one is the current selection of the root and you are having initially these many choices only then you will consider its left part now left part you are having nothing uh so your uh left part will be of there is nothing here and for the right part also there is no option available so in these cases start will be greater than the end and U will be returning null you will be adding null to the lists I hope you are able to understand this list is containing nothing but the possible so the current subtree So currently you are having choices from currently for the root of current subtree by URL choices from start to end so depending upon your choice you will be adding those roots here this list will contain possible roots of the current subject so it happens if you reach an unload then you will add null value list and what will be the type of list it will be user defined data type it will be three node since we are still storing root values of addresses of the nodes so what you will be doing is you will be checking for the possible rules of current subtree and then you will be forming its left part and right part these are nothing but the line part of the current choice of the root for current subject and similarly this is also the left part of the current subject I hope you are able to understand it uh then what we will be doing is we will fix root Plus either left part for the light part loot Plus either one of them and making combination with the part that is not fixed so here we have text the right word of the program it's root and its root and we are making combinations with the part which is not which is the left part so according to the combinations made you will be um adding that node in the load to the as the left part and right part of the current according to the let me type it according to the combination important login and left parts to the current group of the clip and you will be adding that root to the list which is having possible roots of current subtree so this will over possible configuration folder for the root of current subtree and at last recursion will return you all the binary search is possible and time complexity and space complexity we have discussed so this is pretty much it this wraps up the solution for the problem now if you are having any doubts feel free to ask your doubt in the comment section thank you for watching thank you
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
1,673
Jhal Hello Guys Welcome Gautam Seduction Subscribe Must Subscribe More Competitive Exams Page Subscribe Tips to Torch of Clans to all in the subscribe Video Channel and subscribe the Video then subscribe to The Amazing subscribe The Video then subscribe to The Amazing Length of Beer And Play List On The Value Subscribe To Ajay Ko Had Tak Sequence Will Change Kar College Affair Lo Result Will Be Two Three Important Elements Use subscribe comment and subscribe the Channel Please subscribe and subscribe the A Love Minute Ego Vardi Are O Ka Ras Traction Gautam To Sides of Quiet to Ghaghare And Subscribe Kunth Lut-Lut Subscribe Now to Kunth Lut-Lut Subscribe Now to Kunth Lut-Lut Subscribe Now to Receive New Updates Subscribe Sikhe Element From Subscribe To Hai Is Din The Value Of Date Top The Stock Investors Meet Subscribe Pound Inch Subscribe Values ​​Of Values ​​From India Dance Values ​​Of Values ​​From India Dance Values ​​Of Values ​​From India Dance Little value subscribe to I store it standard size in the number of value Sameer and suggestion subscribe jhal hai na website content value in liver function will give 4u jhal that Edison way simply return result coming Soave code behind Google Plus is related that sugar Time Complexity for Limited Now Nomination forms in the scheme are used in the complexity of the problem button interviewer subscribe to have but the index 29 b cold you can call at student vivar ko civil services subscribe Video then subscribe to the Page if you liked The Amazing Queen Point An Element Value of the Statement School subscribe The Channel Please subscribe and subscribe [संगीत]
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
416
hey what's up guys chung here again and this time let's take a look at another medium level lead called problem here um it's called it's number 460 partition equal subset sum okay and you're given like a none negative only positive integers okay and it asks you to partition these two subsets uh this partition this array into two sub arrays which each of the sum of the sub array are the same okay for example here so this is 1 5 11 so this array can be partitioned as one five and eleven uh both of whom both of the sub both of them have the same sum which is eleven and for example this one two three five for this one there's no way we can partition this one to this already into sub arrays it's the same with the same sum okay so um so a few so how can we stop so what's the so this problem you know it's uh i think if you think it a little bit more it's actually a very typical uh zero one k nap sap knapsack problem or the zero one backpack problem why is that because um since it's all positive numbers okay and that's which means this the total sum is always increasing right so for this case for example this one you know the total of this sum is what is 22 right it's 22. so this problem basically if we have a total sum here and all we need to check if there's any sub array right if there's any actually it's not a sub array right it's uh um yeah you it's a subset because the sequence could be different right basically so now the problem converts to uh if there's any subsets whose uh whose sum equals to the 22 the half of 22 which is 11. okay and as long as we see an as long as we find a sub one subset whose sum is half of the total sum and then we know the other half is the same okay and since all the numbers are the uh positive numbers so there won't be any case let's say if the if in case we have 11 here so there won't be a case that uh this one sub one subset will use all the numbers because each of them is integer it's a positive integer that's why we can make sure uh once we find one subset whose sum is half of the sum there still be there's still some like some other numbers left for the other half of the subset right and then actually this problem is converted to a 0 1 knapsab problem right because all we need is the that's basically this half of the sum will be our capacity right capacity and these numbers okay the total numbers is going to be the items right so this is going to be the items so now we just need to find out from this items can we select can we use basically use zero or one right zero or one numbers whose uh sum is 11 it's exactly to the 11 right i think this is a little bit different because you know for the uh the truth the traditional or the uh the normal uh knapsack okay the backpack problem it's a it's the uh it's the max it's the you can use to you can use up to this capacity right not the uh basically you can use until this capacity but you can also use less than this capacity right but in our case it has to be the same as this capacity it cannot be uh smaller than this one okay so that's a bit different and so how do we handle this different variation here right if you remember for the zero one classic uh backpack problem uh when we defined the dp right so we defined dp here we define we first we initialize everything to equal to zero right we initialize everything to zero that's uh yeah that's when we uh that's how we get uh the biggest value up to these capacities it could be smaller it or it could be the same capacity and if we want to get the uh the back the max value only for this capacity that's why when we uh that so a changes we need to make is instead of initializing everything to zero we're only initializing the zero uh the dp zero to zero and for all the else dpi we initialize them to uh to negative the negative biggest number so that's the change we need to make here because we want to make sure right because we want to make sure anything that we get right is from the zero because anything else uh it's not actually will not be the exact capacity if we are getting the values from the dpi i is not zero right that's why we will basically initialize this uh the other elements to the minus max number here so and then when it comes to this problem it's the same thing right so the in this problem we don't need to store the value here all we need is a true or force flag okay so same thing here so for this one the dp 0 will be true here and all the others all the other dp's will be false okay so that's since we're only setting the dp0 to be true right and then when we uh when it comes when we reach to the end the last one which is the end right then we know as long as this one is true then we know okay so this one must have come from the dp0 okay so same thing for this problem so this is like a knapsack problem i'm gonna use the 2d uh two-dimensional dp first and the 2d uh two-dimensional dp first and the 2d uh two-dimensional dp first and then i'm gonna improve the basically compress flatten the 2d uh to the array into 1d okay cool so for 2d array right and yeah so first let's do a sum here right since we need to get the total capacity first which will be the total sum here some numbers okay so and then we're going to have like a capacity i'm going to just use a c here c equals to total divided by two right but i think one thing we might need we might want to check here is the since we're using the uh the integer division right i mean if the number if the total number is an odd number right for example this one right so the total what's the total for this total is the uh three plus eight is eleven okay since eleven cannot be divided by two right there will be a remaining number so that's why we can simply do a check here basically if the total right uh mod by two is not zero we simply return false right that tells us there's no way we can divide it because it's not an even number so after this check now we can fish we can make sure okay now the total is a the even number now it's safe for us to divide it by 2 to get our actual capacity for this backpack problem and okay um and then we're gonna have like an n here right for the numbers so for the two dp problems we're gonna need numbers here right length of the numbers now it's time for us to initialize initiate the uh the two ddps here okay at the beginning everything is false okay and the second dimension will be the uh will be the total the capacity right and then the first dimension will be the numbers of the elements which is the n plus one here okay so that and like i said so the first one the first uh we need to initialize the first element to be true so basically the dp 0 will be true so what does this mean it means that and so just follow the definition from the backpack problem the knapsack problem so dpij means the uh with the first ice items the total i mean to get with the current capacity what's the value okay and for this problem is the uh without any numbers right without uh sorry with so for this problem dpij stands for uh the first ice items so this uh it's not items it's like first k ice numbers and can it form to the j exact j number right so basically it's going to be either true or false right so that's how we define the uh the dp here actually the back the k knapsack problem the template it's the template itself is only providing you a way of um emulate of emulate other possible combinations and other than that it's for each problem the definition of dp will be slightly different and for this problem it's just this dpij will be standing for the true the value we're gonna be true or false so and when it comes down to the base case zero it means that without with zero numbers can it form to zero right which is true right because we don't do we don't need to do anything and the value is simply is true because if there's no numbers and the target number is also zero it's basically it's true okay and now it's the normal to the zero one k nap stack uh template basically the first one we look through the uh the numbers the items in this case gonna be the one to m plus one right that's the numbers and then we're gonna have like numbers uh we can do it and the second one will be the uh the capacity right the capacities from zero to a c plus one okay and then the first case for 2d right it's always the uh always uh not taking the current item not to taking the not to take the current item or the number in this case right so which will be results to a dp i will make dpi j equals to dp i minus j right basically we're not taking this number that's when we uh we need to uh use the previous state but with the same capacity okay and now for the second one right and we're gonna if like same thing if the j is greater than the uh then the what then the num numbers uh i minus one okay then the dpij uh will become to the sorry the so in this case it's going to be uh either true or false right because we want to check between all these things if anything is true or false so actually we can just do this and yeah since we already assigned because here i'm just following the original template here and in this case basically we want to check between all those two options if we can still get a true or false so which means we have to do a this one or right you know for the other uh scenarios we either do a max or minimum right comparing with the current one we undone the rest of it but now here we're doing we only get the true or false that's why i'm going to use a or here right and the same thing for second one so the second scenario here is we choose to use the current ice which we choose to use this i th number or item so that makes the dpij will be converted to uh dp i minus one still with i minus one because remember so i think i talked with you guys talk briefly talk about this one why we need to use i minus one here because it's a zero one case right so basically we have to rely on the previous state which have we never used the ice the item okay here and if we choose to select to use the card number and then the previous state will be the j minors right j minors numbers i minus 1. that's why i do a check here right remember c so because we otherwise this j minus 2 num i minus one will be uh will be what will basically be an active value which will be a invalid state right um yeah and um yeah see so there's not nothing else yeah so yeah that's the ver that's the basics to the uh zero one uh knapsack problem template and in the end we simply return what return the dp the last element which will be the end and the capacity okay right that's basically the true or false um yeah i think that let's try to run this code here okay so the test case passed let's try to submit it cool yeah it basically works right yeah very just very classic uh zero one k knapsack problem all you need to do is we have to some the only thing you need to make to be careful is to be you know to pay attention is you have to be able to somehow convert this like problem into a backpack problem and you have to be uh able to figure out to realize that we just need to find half of it right so once we find the half of it we don't need to care about the other half then it turns it converts this one this two subsets problem into one subset and the one subset problem is the typical scenario of the uh of the backpack problem right okay and yeah so like i said uh we can compress this 2d dp array into 1dp right as you guys see here so the dpij only relies on the dp i minus one a uh dpi minus one right so for the j we can't because for j we still for the j we still need to uh loop through everything so in for in that case we can simply just uh you know remove the first element the first array which will be the this um and plus one array here right so i'm gonna remove this first array and here right and then and we remember we still need to do this the first this two nested loop but remember i think i have already uh talked about this one so in order to make this one to make this 2d into 1d so the way we are looping through the we're doing the second loop it has to be from the biggest to the smallest so why is that right i'm gonna uh explain that one more time notice here we only want to when we calculate the dp i and j here right we only want to use the state from the previous state previously which means i uh dpi minor i minus 1 state okay we don't want to because right and if we are still if okay let's say if we're removing this first state right let's say you if we are removing the first item the first dimension here basically we don't have that the first dimension anymore right so basically both the i minus one state and i state will be using this the same one 1d array right and how can we make sure when we calculate the dpj here we're still using the previously state number right because when we use the this i minus 1 i at j minus numbers i minus 1 this here this number itself will be smaller than j okay and if we're looping through the loops from the smallest to the biggest and by the time we do the dpj here we have already calculated this j minus the j minus um num i minus one state right which means we have already considered to use this eyes in this case right i mean like i said if we're if this problem is a complete a backpack problem which means you can use the numbers or items as many times as you want then this is the correct way this looping through from the smallest to the biggest is the correct way but since for this time for this one it's a 0 1 backpack problem for that we have to be make we have to use the state from the previously state we have to use the value from the previously state which means to be able uh to make that happen we have to do it from the smart to the biggest to smallest so that when we define when we calculate dpj here this dpj miners and nums i minus one is still the old value from the previously state from the i minus one state okay so and uh yeah so that's why i have to do a c here right and the minus one and then minus one okay actually you know and it seems we already removed the first ice state the first one sorry the third since we have already removed the first dimension so there's no need to do this right since the j is the same we can simply remove this part and yeah i mean he'll so here see here right yeah basically that's it right i mean i yeah from we just need to revert reverse the uh the loop here and this should just work oh sorry here okay yeah okay code works and maybe another small improvement is instead of looping through everything uh looping through from c to zero and we do a check here we can even do this right we can since we're not going to process anything that's smaller than the nums this number right so we just need to do this right and we can see we can safely remove this part okay all right we just loop through from c until this number but anything smaller than this number we're not interested in that because that's what that will yeah because that will make this j minus this number be an active negative value okay this should just work cool yeah see you see it's improved the speed a little bit more but anyway so that's the basic idea of this problem just uh if you guys can don't having problem understanding this uh this one the space complex complexity improvements you can stay with the 2d uh versions first okay and then if you really and then you when you are confident about how this 2d uh template code works then you can try to improve remove the uh the first dimension of the dp array and then try to do this but remember when you do this for the zero one problem always do the second for loop in the opposite way cool i think that's it for this problem and another very classic uh knf knapsack problem i hope you guys enjoy watching the video and thank you so much all right stay tuned see you guys soon bye
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
79
hey what's up guys Nick white here I do tech encoding stuff on twitch and YouTube and this problem I've had my eye on a little bit lately just because I've been doing all these other problems and I haven't had time to make a video on it but it's very similar to number of islands I made that video so please go check that out it's kind of a category of problem searching so what are the some searching techniques right we have binary search breadth first search depth first search you know there's much searching algorithms but in this case it's very similar to the one we used in number of islands and I'll explain how this works basically were here's the problem word search given a 2d board and a word find if the word exists in the grid right so we have a grid it's a 2d array each of each right well let's zoom in right here right we have a 2d array right and with these sub arrays right 1 2 3 sub arrays in this case and each element of the sub array is a character right with ABC whatever and then we're given a word right so the word can be constructed from letters of a subsequent sequential e adjacent cell sorry I don't know I just kept saying subsequent for some reason the word can be constructed from letters of a sequential adjacent cell where Jason cells are those horizontally and vertically neighboring the same letter cannot be used more than once okay so basically what we're doing is we're given a word and we want to find it in this grid right so we're given an ABC CED right in this first case and then we see a we see B we see C we see e we see D right and this is valid because they're horizontally and vertically connecting you know we can't just go a let's say we're looking for a F we wouldn't be able to go a and then at fret we would have to the F would have to be here or here right we'd have to go a and then F or a and then F hopefully this makes sense I mean that's pretty straightforward right so in that case we found a b c/e found a b c/e found a b c/e d right easy then we look for c we look at this s oh there's no e here that's see below look there's another version over here how about es e and we don't find a second heap oh here's the e right so just intuitively we already know how to do this kind of right we loop through so we're just gonna do a regular loop through you guys know how to loop through a 2d array right you just do two for loops so we're just looping right and once we see an A we're gonna call our search method now so we're gonna separate these methods we're gonna have just a 2d loop so let's just write that out really quick so right we have board which is our grid so we're just gonna get the number of rows so let's say rows is equal to board length and columns is equal to board of I dot length and then we're gonna do our two for loops right so I less than rows I plus it's J equals zero sorry J less columns J plus and yes super straightforward I'm sure you guys have seen this before in this method is just a boolean remember so we're just returning whether the words in there or not we're not counting anything there doing anything crazy here so you know one would we start our search right and we're also gonna have this other method like I said we're gonna split this up so public pool and you know a search word right we'll do search word here and this will you know false so what are we gonna search for the word well we're only gonna search when we find the first letter of the word right so every time we find the first letter so in this case for C is a good example right so when we see an S here we're gonna call it because it's like that's potentially gonna be the word so we're gonna call and this separate the separate method is just going to do recursive calls on the neighboring adjacent letters right so we're gonna call on s and then we're I'm gonna be like okay we have an S so let's look for an e now right we're gonna look at index 2 we're going to increment an index we're gonna be like okay is there an e at the top the right or the bottom no so we're gonna say false then this met then we're gonna get a false here so we're just going to keep looping through and eventually we'll find the second S will recursively call the top and bottom and left we don't see anything here this leads to nothing eventually and then we found it here and when the index that we're looking at actually equals the word length that's when we're gonna return true so there here's the conditions right if word dot char at 0 is equal to 4 the current position that we're at in the board well then we're gonna search right so we're gonna do search word is going to actually return a boolean value so if search word returns true we're gonna return true we found the whole word so search word will tell us whether we found the word or not so we're gonna call search word with I J board word and then the one last thing we're gonna have to meet we're gonna need is we're gonna need a visited array we're gonna need a boolean visited array of because we don't want to search the same indexes right so we need to keep track of you know we don't want to go when we're when we call our search method we don't want to when we're looking at you know adjacent values it's recursive and it can go on for a long time we don't want to look at it we don't want to relook at things we already know that there's nothing there right so we're just gonna every time we call this method we're gonna do visited we're making visited you know publicly available to the whole class we're just going to do visited of I of J is equal to true so we're gonna take in int I and J int index you know string word and char board I didn't match those up very well but that's fine starting index is 0 so if we see the first character of the word will call our search method right here it calls it and if that gives us true we found the rest of the word this will look for the whole word then we get a true and then we were so if we found the first letter and we found the whole rest of the word we return true otherwise we loop through everything and we do that every time we found the first letter and we return fall so we get nothing so now all we have to do is implement the searching right so it's just like I said it's for recursive calls right so we're just gonna do and this is a bullying method so it's pretty straightforward we're just gonna rehearse on search word on I plus 1 to get the next row J index plus 1 to get for the next index of the word board right and we're gonna do we're gonna look for the word at every possible place so I minus 1 the previous row that's fine and then we're gonna go for the columns now so I stays the same and we're gonna look at the columns is very similar to number of islands if you want to check that out to get a thorough understanding I think I did or people really like that video that I made so if any of these finds the full word so if we find the full word at any point here then yeah we're good to go and we can return yeah we did find the word so return true right that's it return true we found the word and that's it we're pretty much done right there so this is the end of it we just have to do boundary checks that's the whole thing you just recurse on the next column so this recursive the column the next column to the right to the left up and above because you can see I plus 1 I minus 1 J plus 1 J minus 1 and why do we even have an index well here's the base case right if index is equal to word lane that means that we successfully found the full word right because we're incrementing index each time we recurse and find the next letter of the word so if index is equal to word dot length return true and all that we have to do besides that is boundary checks and then we're done so boundary checks are always annoying so if I is less than 0 or if I is greater than or equal to were bored dot length or J is less than 0 or J is greater than or equal to board of I dot length then that's the column or word and here's the main base case I mean main check if word chart index is not equal to board of I of J then that means that's not even the right letter so we just got to return false there so I think I did a pretty good job explaining that I might have messed up at some point in here board of I dot length what's the problem here Board of 0 dot length that's how you get the columns what else is going on here visit up we didn't initialize the visited public boolean array so we just got to do visited equals new and rows and columns just a boolean representation of the same exact board new what does an int cannot be converted into Bullen yep it's pool in so sorry about that these errors yes please ah what did we do wrong guys and this is definitely right okay this is all right what else do we do j-mo plus 1 all right what else do we do j-mo plus 1 all right what else do we do j-mo plus 1 J minus 1 IJ index plus 1 each time we pass in the same word and we pass in the same board that's fine if index is equal to word out length that's fine is there any more checks that we would do here I is out of bounds J is out of bounds word is not the word character doesn't equal to the current position what else then what else I mean what else is there really what do we do this why did I do that no I think that's right actually that's right what is it what are we doing wrong eh-eh dude I did the whole explanation or we freaking didn't even use the visited yeah sorry that's the solution that I went off or visited of I've Jays fault true yeah so if visit you have to check that you didn't paying a visited point in the visited array so that's the solution sorry about that checkout number of islands here I'll link this guy's this is the solution that I kind of learned it from I mean it like that's this is just the right solution it's very it's the exact same as number of islands but I'm sorry about all the confusion you just have to it's just long boundary checks and you have to make sure that you don't visit the same cell twice you find the word you return it I think it's pretty straightforward let me know what you guys think in the comments below check out the number of islands I'll link that one too I'll try and start categorizing the problems that I do but I really don't feel like doing I would do this again normally because I messed up at the end but I don't feel like it so please take it for what it's worth thanks for watching check out everything alright thanks see you guys
Word Search
word-search
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. **Example 1:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED " **Output:** true **Example 2:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE " **Output:** true **Example 3:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB " **Output:** false **Constraints:** * `m == board.length` * `n = board[i].length` * `1 <= m, n <= 6` * `1 <= word.length <= 15` * `board` and `word` consists of only lowercase and uppercase English letters. **Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
null
Array,Backtracking,Matrix
Medium
212
94
every one today we're gonna do question number 94 binary tree in order traversal we're first gonna go understand the problem and then I'm gonna show you three possible solutions but I'm actually gonna code the most optimal solution this question may seem relatively simple at first but I wanted to reiterate and talk about a more advanced algorithm to solve this problem yeah in such that you can actually achieve this in a very efficient manner this algorithm would be called Morris traversal if you want to listen to more stay tuned alright let's read the question given a binary tree return an in order traversal of all its nodes it sounds pretty simple right so but let's look at an actual example what they're trying to ask for alright let's look at an example so I have a very simple binary tree to find here where the leftmost nodes are of course smaller than your root node and anything on the alright is greater than things on your root node okay so couple of ways we can solve this problem when we look at inorder traversal the from the quick looks of things the in order of this binary tree is three four five six seven nine ten eleven right we know that's in order right however how do we actually solve this problem right one may think that okay since this is a binary tree what kind of attributes does it have we know that in a binary tree you're left most node or in this context here will be smaller and you're right note right side will be greater right that's an attribute of it so with that being said we can actually use this and think about okay why don't we just look in your left than your right and continue to look at your smallest number which is I'm just gonna go to my leftmost element go left and right and left and right up to the point where I can't go left anymore right and then I'll print the value and then I'll maybe I'll walk to my right and go down and continue this process right now the solution it gives a there's a thing that comes into mind right away and that is a very recursive in nature right I could always repeat the same small subproblems and recursively go over and over again to solve this inorder traversal however doing a recursive way it's not the most time and space efficient right so what other thing what are the ways can we think about to solve this problem it is don't get me wrong it is definitely a possible solution what we just talked about but you know we're a little bit better than that so we're gonna try to talk and go through something that's a little bit more advanced now another way to solve this would be more of a iterative approach right you can do you can you know create some sort of you know storage thing right a storage like stack or some sort and you could just as you iterate through here or as you go through all these elements you could pop and you know basically get a solution there too however that's not I'm not gonna spend my time on these two solutions because you know if you really want to know more detail about it you could probably look at you know a solution to explain it but those are not the most advanced and most now not the most optimal way to solve this problem right the problem we're gonna dive deeper today in is called the Morris algorithm all right let's begin so the first step you do is create a variable that points to the root node in our case I'm gonna initialize a very pole called tourists and it's gonna basically look at the root node right so you know as a tourist I want to make sure that I'm gonna do this algorithm up to the point where my tourists you know is still standing on something that exists right so that's my second number two I'm gonna make sure that while the tourist is not lost or no I'm going to continue to do a couple of things right so what do I need to do I'm gonna have to initialize a guide right I'm gonna tell the guy to go hey can you look at on my leftmost side and stand there and just make sure that you know what's the guide to look at the tourist left sub-tree and to see if tourist left sub-tree and to see if tourist left sub-tree and to see if that's cool or not right so the first thing I got to do is like okay well I have two variables now one variable that is looking at my root node and another variable which I called guide that's gonna look at my leftmost or left subtree right I'm gonna tell the guide first to go and look at okay you're looking at my left subtree the next step I want you to do is look to the rightmost segment of that subtree right so I'm gonna tell the guy to walk to the rightmost point right you'll walk the rightmost point in this case it's seven and then because I can't go right anymore I could go left Bob can't go right anymore that is our echo condition I'm telling okay can you create something for me right so as a guide when you read out reach up to the rightmost point I'm gonna tell the guy to create a temporary connection point to where the tourist is right so this connection point we're just gonna highlight it in orange and that pretty much says that okay hey you know we know that at least in this segment this is the final point on your right side from the left sub-tree cool you're safe to the left sub-tree cool you're safe to the left sub-tree cool you're safe to walk and I'm gonna create a bridge to go connect back into your where you started so I'm gonna tell the tourists to go and Traverse down to my left segment left sub-tree right tell the choice to left sub-tree right tell the choice to left sub-tree right tell the choice to go here that's great see we're haven't done anything yet we're just telling it to traverse we start to get to this point right so let's look what's happening here so once the tourist goes in here we actually you know repeat this process again okay and I'm gonna show you on I'm gonna exit this presentation and show you actually here it's more easier so well miss something I'm gonna grab this back in here well okay cool so I have this bridge I created right um don't read this segment yet I'm gonna put my head's too big don't read it yet let me just shrink myself a little bit smaller small so what we're gonna do here is simply do the same process again we're gonna make sure to tell the guy to go to the left most node okay and you're gonna the guards gonna do the same thing go down here to the right segment and I'm gonna create a bridge because I'm on the this is the most right segment I can go create that bridge up to here and tell my choice to go left right and the next step if you follow that again we tell it got to go my left subtree but oh no there's nothing on the left side here anymore right so therefore the next step I gotta do is well if my guide is lost which it is the case where my tourist is on no number three I'm gonna tell the tourists to walk you know tell the tourists and note that particular point which is gonna be three right I'm gonna note it as three and I'm gonna tell the tourists to go walk to the right instead because if you walk to left it's dangerous cool all right and now we repeat that process again tell my got to go left oh and the guy can't go left anymore so what do you've printed out all right and then you tell the tourists to go right and because there's a British here I'm gonna walk up that bridge and go to my number five on my guide to go and repeat that process again I'm a guy to go left and then go right but at this time the bridge already exists right so if the bridge is that's tell me that I've already visited this I'm gonna tell my guy I'm tell my tourist to go visit this again but therefore I'm gonna going destroy this bridge right and I will tell my tourist to go and just go to the right segment or go walk right all right but also before you walk right make sure you register your existing point which is this all right and then the tourists will go to the right repeat the same process they'll look at the left most node and then over here because there's nothing else in the right segment this is the rightmost I'm gonna create a bridge connection here this node right and then tell my touristical walk left right and as you walk left tell my guy to go okay King called my left side hope there's nothing here right so therefore remember what I said register this value there's the value and go right all right same process there's nothing one when you're gonna tell you're curious to go on the Left which is gonna be a six the bridge exists destroy it right and we continue on which is okay tell to go right but if I tell go right in this case is gonna go back into number nine right and take a register of this number seven pop it in here all right and then again tell my guy to go here which is gonna go down to the right segment this exists destroy it and tell my tourists that you've been at this point already nine and torture is to go right same process again go down here send my guide to go to the left create that bridge I'm just gonna copy this and create that bridge here make this orange so you can see and Tom like tell my tourist to walk left right can't walk my guide goes here and dies because there's nothing in here on the left side so therefore we create this again and you know you told you walk right up here tell the guy to go down here and destroy the bridge and tell the guide or tell the tourists to go right if they go right what happens well that's our exit condition right here right you do this until the tourist is not lost in this case if he goes down you're pretty much lost but have you noticed something that's kind of interesting what's over here well I have actually registered the solution that we're looking for right so this is pretty much the Morris traversal it really simply just tells you like you have basically two pointers one that signifies like the tourists and one that you could think about it as a guide and the other guide really does is look at your left mode node and then go traverse to the right boss point create a bridge to where the tourist is and continue that process over and over again until there's places where you've terminate and register the point right so that's actually before we get a better understanding if we start coding this so let's jump into some code all right we're back in code perfect so one of the first things I want to do is you know again make sure this is a function define this and delete this over here make it nice and clean like I said before I'm gonna create that variable I'm gonna create the tourist or tourist actually don't have to capitalize that tourist I'll make that equal or at least point or reference the root node and I'm gonna also create a solution alright because that's what they're asking for great now remember my rules that I had before I'm gonna make sure that while my tourist is not lost or it's not long all in this case I'm gonna do some stuff right but remember when we write these things I'm gonna return a solution here first so I don't forget all right so the first thing you gotta do is well let's create that guide right the guide is gonna be looking at the tourists dot left right remember one key point when we have a variable looking at an object or something that is not primitive it is actually just referencing that element it's not actually copying that element right you're given the ID of where that element is stored in memory and you get a you know reference that point right so that's very important I'll dive deeper later on other videos to talk about this little nuance detail but that's something to be very to be aware of okay so come back into the salt the cool animal I can't talk right now going back into the actual question I'm gonna set the guide they go on the tourists dot left which is essentially looking at the left sub-tree right and then when I'm left sub-tree right and then when I'm left sub-tree right and then when I'm there I'm gonna make sure that I go to as long as my guide is not right does not equal to null and the guide dot right does not equal to the tourist tour list okay there we go I'm gonna make sure that my guy equals to guide dot right all right so this effectively sets you to go walk to the rightmost point right so what happens if you're already at the rightmost point well if my guide is equal guy thought right is equal to null right that's where I met my terminal point I'm gonna create that bridge right so I'm gonna make sure that my right or guide right well equal to where the tourists exist right now tour or s all right so that's where the tourist is that spell Traverse right off you go I'm gonna make sure that in the tourist and then I'm gonna tell by tourists okay now it's safe you know you can actually go and go to tourist equals to tourists left right cool so that you know this is one process and then you go through it again and then they adjust for the other case which is well what if we cannot you know if the tourists or at least if my rightmost element is at the bridge point right so I'm gonna make sure I get adjust that scenario which is gonna be good dot right equals to no right so this one deals with creating the bridges this is gonna be destroying those bridges all right so as I destroy the bridges I make sure I've got to make write a solution dot push the tourist location wrist dot bow right and then tell my tourists do go tourist forest right so remember what I mentioned this is like creating of the bridge segment this is like destroying the bridge right that I was referring to earlier all right and one thing that we did not note here is that well this is only the case if my tourist this is the only case that hmm I think I missed something here right what happens I forgot something here which is well what happens if your tourist is on the edge we haven't dealt with that case yet right so I'm gonna look at here go saying like okay I'm only gonna do all this stuff if my tourists thought left does not equal to no right what does this mean is that okay this all works out as long as my tourist is not on the edge right so what if the tourist is on the edge remember what we mentioned earlier if the tourist is on the edge we tell them to pretty much all right you're at the edge and you're gonna make sure that you record the solution dot push here which is the tourist dot value right and we're gonna make sure that the tourist goes to a tourist all right cool all right so this pretty much I believe would solve the problem right so in this segment here I'm gonna run this loop while the tourist is sitting on a pot in a space that you know exists I'm gonna create a guide that is looking at the tourist this left subtree I'm gonna go and make sure that okay I'm gonna still walk until the point where I'm in a place where I can't walk anymore right at least this will tell me by I saved my life tourists out left right so on if I'm at a place where I can still continuously walk I'm gonna make sure to set my guy to look at the rightmost point on my left tree and create that bridge or destroy the bridge right okay cool so let's see if we submit the solution if it solves the problem oops wrong thing as submit Oh No I messed up something what did I mess up on all right I might have let's see ah okay right this closes that I might actually have too many I think create a bracket here alright cool like open to that and that closes this out and there we go cool and we solve the problem right hope this helps and stay tuned for the next episode if you want more and drop a little bit comment below or subscribe if you liked it and we could just go through another exercise next time see you guys
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
133
hey guys thanks for joining in today's video we're going to go over problem 133 on leak code clone graph so first we'll go over the problem description and we'll have a discussion on different types of approaches we can take to make the solution we'll talk about any edge cases which could get us into trouble we'll discuss what kind of data structures and algorithms we can use to make this as efficient as possible and then finally we'll go ahead and actually code the solution so we're going to be coding this in java in the video if you want to follow along in a different language that's fine the concepts will carry over so into the problem description the problem reads given a reference of a node in a connected undirected graph return a deep copy of the graph each node in the graph contains a value int and a list of node of its neighbors and scrolling down they give us a few additional details we'll come back to that then they give us an example where we have an original graph here with nodes 1 2 3 4 connected as if it were a square the first example on the top we can't return the same exact graph reference and the nodes themselves can't be the same reference so we can't do a shallow copy we have to do a deep copy or every node is cloned the example in the middle is good everything is cloned in the proper order and the example on the bottom they give everything is cloned but things are brought in the wrong order so we have to make sure we avoid those pitfalls then they give us a few examples of what the input output will look like the actual input to the program will be the node class this they just have here as something which will be convenient for the user to read so coming into the example two they just have one node that's a base case we have to account for example three there are no nodes at all the graph is empty that's a base case we have to account for in terms of implementing a solution one thing we can do is a break first search we can reuse that type of algorithm except instead of just searching for a value or returning when we find something we'll use it to iterate over the graph and we'll clone nodes as we go and we have to make sure that if we get into a loop we avoid an infinite loop there we have to make sure that if we encounter a node we visited already we have to grab that clone reference instead of cloning a new node when we already have a cloned node so those are a few pitfalls we have to avoid there so let's go ahead and write the code they give us what the class looks like for a node itself commented out we can come back and delete that but i'll leave it up for now because it'll be useful for reference purposes so the first thing i'll do i'll just bring a comment in indicating we're going to use bfs breadth first search then we'll account for the edge case where the node is no so if the graph is empty then the node will be null so base case graph is empty if the node is no return no so that'll account for the empty graph scenario now we can go on to do an actual breadth first search so what we'll do is we'll create a map which will map a node to its cloned version so it'll be a map of a node to node and we'll use a hash map as the actual implementation then we'll initially clone the entry node and put it in the map and the node in the constructor will take a value so at each point when we clone a node we won't actually clone its children at the moment we'll just clone the value and then we'll add the children later on then for the breath for our search we'll set up a queue and we'll actually be using a linked list as the implementation because java doesn't actually implement a queue class itself it's just an interface then we'll initially add the first node to nodes to visit after that we'll perform our dfs to clone and add children as we go if you're not familiar with breadth first search i do have an article which explains that in great detail i'll link that and a few other resources as well in the description but for now i'll just briefly describe the different aspects of it as we go so right now we are doing a while loop while we have nodes to visit remaining so in other words while the queue is not empty we're going to perform some operation first thing we'll do is get the node at the end of the queue and put it in current node so that's the node that we'll be focusing on in this iteration we'll do the same for our cloned current node at this point it's guaranteed that whatever node we pull out of the queue we'll also have a cloned version in the clone map so we'll put from there then we'll iterate over all of the node neighbors of the current node we'll initialize this cloned neighbor variable outside we have to check if it exists in the clone map or not so if it does exist in the clone map then that means we visited it already so we have to grab it from there instead of making a clone again so if it contains the neighbor clones neighbor let's you go to clone map dot get neighbor otherwise we have to do two things you have to clone the node and also put it in the cloned map and actually we also have to put it in the nodes to visit because we have not yet visited it since the cloned node does not exist so we'll put that in the clone map now and we'll add it to the nodes to visit notice we're adding the neighbor to the clones to visit not the cloned thing itself and lastly we'll add it to the list of neighbors in the cloned node and note that this will preserve the order of neighbors because we're iterating it in the same sense that we're iterating over the current node itself so at this point it's guaranteed that the cloned node whether it came from the cache or not corresponds exactly to the neighbor lastly we'll return clone map dot get node which is just the initial node reference so i'm going to go ahead get rid of this part now let's go ahead and submit that and see how it does so i've run this a few times for the first two there was a spelling mistake i had to fix here once that was resolved i ran it a few times it seems like it hovers around 37 milliseconds for the whole performance there is some variability as usual with leak code in the runtime in memory but overall the approach works and it is decently performant so we can accept the implementation that we have here so that covers the content for this video if you made it to the end please leave a like and subscribe for more elite good videos thanks for watching
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
598
hello so these questions range rotation.2 so you're giving an rotation.2 so you're giving an rotation.2 so you're giving an environmentary and then also the operation array so you have to count and return the number of Maximum so maximum integer in the measure after performing all the operation so uh this is uh quickly just back our solution so uh three by three metric operation uh is 2D array and then for every single up of array uh you'll have you have to increment from 0 to 2 but not including two so just one right and this is zero one two so you increment the size of two times size of two which is a list this little box by one and this one is size of three right three by three increment by one so you get this result after you perform all the operations um to the array right so you have to return the maximum value right which is this one which is list number so how can you find out this solution you can actually just using uh the traversal for operation and find out the minimum value for the row and column so I'm going to set equal to Max for Rule and colon and I would definitely write Traverse overflow operation to find out which one is the meaning about I mean I need to just keep updating my mean valve for the rowing code then once I have it then I will just return the row times column because this is the like a size like a match uh like a rectangle something like this right you can definitely return something else right so two by one is a rectangle two by two is a square so uh if the operation is empty you need to return the size of flow measure which is three by three and then they start coding so I will have y or equal to English Maxwell c equal to integer the next stop traversing operation array icon master mean okay as you are right so I would prefer to run like this right so C is also exactly the same thing see comma okay one so uh this is it right so if r is equal to integer.max which is unchanged right and also C is equal to integral Max now I will just return M5 and right and everything else is going to be returned all times C so uh this is straightforward so what in integer okay let's start around I submit all right so for the timing space it's pretty straightforward this is space constant this is time uh it's going to be land of the operational rate so all of what all of op you know and let me like set a breakpoint over here so I'm going to use in debug mode and to see if there's anyone is interesting uh the detail and then you just take a look okay so let's just keep watching so if this one is running the two uh two different example all right so basically like you just keep updating for sure but um but once you have the smallest value you won't change too much so probably you'll find all the better a better example and then you just keep uh updating so let me just like this so imagine I have what one by one and then I'm going to read one so say you go to default to Max so 22 is the max value mean value right now and then the next one is going to be 33 right now the next one is going to be one so you'll return one right yes guys I want to code yes so this is a solution so timing space are super straightforward so if you have any questions leave a comment below subscribe if you want it all right peace out
Range Addition II
range-addition-ii
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Example 1:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\] **Output:** 4 **Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4. **Example 2:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\] **Output:** 4 **Example 3:** **Input:** m = 3, n = 3, ops = \[\] **Output:** 9 **Constraints:** * `1 <= m, n <= 4 * 104` * `0 <= ops.length <= 104` * `ops[i].length == 2` * `1 <= ai <= m` * `1 <= bi <= n`
null
Array,Math
Easy
370
792
Hello guys welcome to another interesting videos refilling suggestion problem number of the thing subscribe The Channel Please subscribe and Share and subscirbe BCD Na Dheer Wa Next Seervi Subscribe Our ACP RCC CCCE Apni Petrol And This All Sequence Pet So S Subsidies For Distinct Mothers At That Time BCD And BC Something Like This Will Be Most Question Requested For Will Do In Order To Left Side Another Examples For Nation Will Discuss Route For Support First So What Is The Price Approach Finally Bigg Boss Character You Will Power Point At Which Word In World Tractor 960 Hai So It Folds All The Four Address What You Did You Kept On Increasing The Big Point Alarm Telephone Elements In The Small To Interpret Suggestion Simple You Understand That With Help From Forest For Example And Will Never Forget You P M Suzy Direct Subscribe You Will Have Pointed And Currently Doing What You Love What Is The Phone Is But What Is The Problem Subscribe To These Roots To Describe The Book Solution To Handle All Problems That Is The Time Limit Problems This Attack Is Simple Example Supoch Year S Something Like A K Samay Remix String And Inside View Of B And Supportive Words You Have Something Rank JB Pet Suv In Brute Force Of Which You Will Have A Small Pointer For Android No Problem Solve It Will Key Point Meeting Reminder To file b to find that particular b you how to your waste lord of regard to waste renu united overall these elements of vital role of time e saw this will give time limit and some cases very big screen rent and addiction more last medicinal time limit Now to group support system in problem how can you solve this to think what this logic you when lord of flying fighting for the position of but no rate option requested start the position of but its position of bq not waste time i trading corporation of but In the morning a simple injection and logic which is cut only a few words to the position how can you to the position of Victoria bushrangers informed and obscene news for this so that they can start the currency of one by one in this particular day special today Also Romantic Playlist On The Problem Using Back And Lag Increase All End Values ​​Pe Back And Lag Increase All End Values ​​Pe Back And Lag Increase All End Values ​​Pe Examples And Will Solve This Problem No Time Limit Exceeded To Bank We Shape Better Time Complexity Of Observations Made The Let's Go Back To This Example Not Interesting Let's See What Will U Are Let's start shot in this particular 2012 to all the characters in the app and corresponding and karan show first vihar phase statement next chief position 112 students peeth position tourist places in the history of co-operation for in the history of co-operation for in the history of co-operation for next egg position 5 tags page 6 tags Page 7 Tags Page 8 Tags Page 9 Tags Page 10 Meter Reader To All The Best Example 10th Paper Par Hai So Par Ko * And Take This Word SEC 23 So Par Ko * And Take This Word SEC 23 So Par Ko * And Take This Word SEC 23 Year Old Looks For Fancy Dresses For Girls In Map No. 01 2012 Very Good And Evil Resident Evil To Find What You Need To Know What Is The Current As See First To You Are You Pimps See Can't Take Previous Idly Can't Take These Those During Elections After The Question For You Are You Can't Wake Up Sid Hai So you can read this particular question subscribe that Redmi is less for less and lag increases blue color market share all possibilities for contributing for a that pokemon last stage Dinesh example2 hand straight let me point out straight for qualify for students of video chintu swift grade Next Date Funds Near Shirdi Circulation Six Poking No Where To Find A Way Which Prevents Will Take Its First Shift Straight To New Account Dr To Take Only After Did You Can Not Take All Is Well All The Subsequent To Know Where Only After 10 Spotlight 999 9999 next9news 1000 500 12th Nobody Can This Month's Punishment Comment You Can't Find Any Sach Current Time So What Will You Do You Will Share It Sweater Subscribe Directly But E Cold Not Find Na Dheer Wa Subscribe Latest Video On Karo Main To Abhi Aap Up So boiled iklera measure so map and it's going to be coming of chapter first parameter and a great way to restore order comes and tales pages college tempera on wood side over all the characters incidents and hold to shoulder value in innocents from axis character doing this point To subscribe to the Page if you liked The Video then subscribe to the That Idea To Where Is Best Offer It To Override Custom Fonts To Reach Word To Return Gift Love Current And It Will Give Me The Correct word for provide over 10 characters current suzy 100 current size chess player of the year after 10 minutes latest - player of the year after 10 minutes latest - player of the year after 10 minutes latest - 04 - 101 latest will change for you to find it decided to give its 04 - 101 latest will change for you to find it decided to give its 04 - 101 latest will change for you to find it decided to give its function will give oo hello friends good cancer tight after the killer whale In which value is latest and new year deposit and main to m is the map in the map of which is the current particular person character point to search for the values ​​of the latest content values ​​of the latest content values ​​of the latest content battery ke to Address Latest Hair Remove Well As After Latest Love You Say About Pollution Cricketers Values ​​Per This Pollution Cricketers Values ​​Per This Pollution Cricketers Values ​​Per This President And Not Know How Can I Withdraw His Research And Catering Service Centers Of Month Current Television Under The Latest Subscribe For Latest Videos Star Values In interior portion in a notification you are to check and account night she was found correct loot check and don't know how can you do it is jain is equal to correct size - 110 021 Simply to correct size - 110 021 Simply to correct size - 110 021 Simply Institute vendors who lost in this world to leave later On imposing excise on it, submitted unseen images are accepted, the indicator of time was the same, patient and listening to
Number of Matching Subsequences
binary-search
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\] **Output:** 3 **Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ". **Example 2:** **Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\] **Output:** 2 **Constraints:** * `1 <= s.length <= 5 * 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 50` * `s` and `words[i]` consist of only lowercase English letters.
null
Array,Binary Search
Easy
786
367
Ajay Ko Hello viewers welcome back to my channel and doing great prevent subscribe To My Channel Please Share subscribe Hafte Take Some Places For Various Categories All Problems Bread 10th Programming Binary Search Tree Is Graph And Take Off Please Like This Problem To The Page Want To bring the description of this video please do you live long jump in today's problem solve they give positive number do torch light function which returns through itna mishra find perfect square of moles tuesday ne british library functions sach ssc 800 basically were given with number and wheat To Find Out What If It Is The Perfect Square Solve And Give Positive Integers All Fall Into Tiers From One Right One To The Number Of The Language Basically We Are Not Support Use The Year Award Function And Subscribe Must Subscribe And Subscribe The Channel With Us That enter basically the perfect Ron for 96053 Number subscribe The Amazing Celebration In Mid Day Meal In Paris Masters subscribe The Amazing 2018 Gas Nath Maurya Sudhir Online President Mirwaiz Umar Farooq Madder In Between 2106 Vidron In More Dooba Reverse Engineering Basically Number Ward Number Four Drops Of Number Subscribe Like This Is Equal To Hanuman is done properly for Fida Hussain I plus price a in products waste is equal to is toy rights spread difficult-2 this product is equal to name difficult-2 this product is equal to name difficult-2 this product is equal to name and birthday will return to draw finally will return gift card here check the year maths show May Not 5000 Become Soft Member We Can Do And CEO Of The Giver Number Is Perfect Square And Not Back But Sudhir Web And Little Time Complexity Of Order Of 0001 Number One Officer Number 90 Time Subscribe To Is This Is Not A Patient Wait Year option wrong reduce problem members have central hot example this problem subject in the northern more will withdraw cases against what will not only give number list thursday civil liberties the composed for the giver has duis atm in stand into terror outfit and entertain not fog true When You Can Reach To Do We Call The Giver Number One Act's Vid Oo A Times Right Times Will Go Through A Post More Than 250 Subscribe Next subscribe and subscribe the Video then subscribe to the Page if you liked The Video then Dhaal Responsible for The Band Singing Competition Live Show Width Number One Will Find The End You Will Find That subscribe The Video then subscribe to the Page if you liked The Video then subscribe Yes sorry for the now handed over this number symptoms and equal to zero and inspiration for its okay and the number 213 ₹10 Don't Have Really Check for number 213 ₹10 Don't Have Really Check for number 213 ₹10 Don't Have Really Check for Woman President 10851 Subscribe and the giver number one number subscribe to subscribe our Channel And subscribe The Road Thursday The Subscribe Liquid This Product Will Also Be Important Alarm Clock Of The Product Is Equal To The Number Don't Forget To Subscribe Behavior Cutting Specific It's Great Thursday Subscribe Cutting 2128 1632 subscribe The Amazing Return To The Giver Number-10 Subscribe To The Since Way Are following dabaya research professor the are the only difference subscribe and are given hair fall wealth and subscribe thank you all subscribe boys and every time they are giving specific the time and space complex it is equal to WhatsApp Web Share subscribe and subscribe noida mode of Long and algorithm solid much improved do subscribe want to see the subscribe must subscribe our channel subscribe v3 sort algorithm with questions please watch my video to you can find a link below and subscribe favorite subscribe To My Channel Please Share subscribe and Share with your friends Please Click on the Bell Icon on the Tube Will Be Notified About All My Videos Thank You For Watching My Video Bye Problems On Children And Stay Safe And Good Bye On Karo
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
476
today's problem is lead code problem number 476 and it's called number complement and by number complement we mean that uh the number that we obtain by changing the flipping the bits of original number for example here you see it's the bit representation of 5 it's 1 0 1 2 raised to the power 0 which is 1 plus this is absent plus 2 square that is 4 plus 1 5 and here you see it's 2 to the power of 1 which is 2 so the complement of 5 would be 2 here because these are the bits that are used and we have flipped them we don't flip these bits for positive integers these will be all zeros only a certain number of bits will be used and last bit will be zero anyway and we are given that we will be doing it for only positive numbers so the last bit will be zero and we don't have to change flip any bits till we encounter the first bit so here we will just flip three and we will be using bit operations for that since those are much faster than running a loop and uh then every time shifting it one step so that we reach here and uh i did a brief survey on internet and i found that it's also used on it has been asked a few times in facebook interviews and the concepts that you will learn here will be very useful for any other bitwise operations questions related to that so pay attention to it so now this is the example uh and this is the representation of five of course there are many more bits here on the left of it with all zeros i have not written that since those will not be impacted anyway i have just added two extra zeros but imagine there are more zeros here and this is two so here one becomes zero becomes one and 1 becomes 0 all the others will be unchanged so how we can do that so one simple trick could be that let's say we have 0 here 1 0 1 so we know that if we take xor of 2 numbers so 1 xor 1 is 0 xor 0 is also 0 1 xor 0 is 1 and 0 xor 1 is equal to 1 so it is 1 in these cases so whenever i flip whenever i xor a number with 1 we are doing in 2 instances here and one we are doing xor with one here so there are two cases we do x over here so when we do xor of one with one we get zero so this one is flipped so this is the operation that we will perform xor with one and here is a bit so if this bit is zero we get one if this bit is 1 we get 0 so doing xor with 1 always flips the bit and this is what we are required here so whenever we have you have a problem where you require flipping of bits think of doing xor with one doing xor with 0 will not change anything for example doing xor with 0 on 0 you get 0 on 1 you get 1 so bits are on unimpacted so uh how can we flip it so if we do it here we have using three bits we don't need to flip these so if we do xor with this and this will be our mask and we will see how we can achieve it this is our original number so if we do xor with 1 all the ones we get 0 1 which will be ours only solution so the main trick here is how to get this mask so for that we need the number of bits in this case number of bits is 3. so what we do we left shift 1 by 3 and by the way what this number represents 1 it represents 7 this is 1 plus 2 plus 4 that is 7. and if we had 4 ones it would represent 15 and you will notice that 7 is 8 minus 1 and if we have 15 that is 4 bits then it would be 16 minus 1 why i am writing it because 8 is 2 raised to the power 3 and 16 is 2 raised to the power 4 and this pattern will repeat if we have 5 bits 5 once we will have 31 which will be 32 minus 1 that is 2 raised to the power 5 minus 1 so if we have number of bits is nb then we need to find 2 raise to the power nb minus 1 so either you can use the power function and subtract one from it or you can left shift one so if you left shift one by three it becomes uh one zero that is 8 you left shift 1 by 1 it becomes 2 by 2 it becomes 4 by 3 it becomes 8 and then subtract 1 from it and then whatever you get this mask do x or with original number so let's implement this concept in c plus less then we will do exactly same thing in java and python so this is the problem statement and they have given the example of five first we will write in c plus so uh we will need to use log function here log base two uh in python we have a ready-made function in python we have a ready-made function in python we have a ready-made function bit length but in c plus i don't think we have any function like that so we will use the log function log base 2 to get the number of bits and one thing with the log is that you cannot take log of 0 so we will add a base case for 0 so if num is 0 we return 1 why because a representation of 0 is zero and last bit we will flip to one so this is base case uh for one it's zero for zero it will be one other than that we can take the log of anything and this limitation is not due to base case but it's mainly due to the function log that we will be using num bits equal to log 2 num plus 1 and this c plus this has functions log 10 and log 2 and the default log is natural logarithm that is base is e euler's number if you want log 10 you will write log 10 if you want log 2 you want to you will write log 2 so here we will need log 2. then mask is 1 num bits so if it's 3 we will get 8 then finally we subtract 1 but there is a problem here you see that we are always dealing with positive numbers so uh if we are using a generic int let's say our test case is uh into max which will be uh all the 31 bits will be one so let me draw here so the into max will be this 32nd bit is 0 and all the other bits are 1. so in order to get this mask in order to get this 1 what we did one zero so one digit extra for three bit mask we need one digit extra four bits and then we subtracted one from it so if this is the integer that is given to you and this is a valid test case since it's a positive integer then we need to a left shift one by 32 bits so first we need this these are the 31 bits and this is the 32nd bit and then we subtract 1 from it but if you have this representation the last to it is 1 then it's not positive it will be negative so if you do minus 1 it will still be negative so this will not work so what we will do we will use unsigned we need to just cast it to unsigned and then do everything will work fine it will always return positive so this thing was always valid but the problem is that first we need one extra bit for calculating this then only we will subtract it but this itself will become negative that's why we use unsigned and finally we will return num xor mask and let's try it and it works let's submit and our solution is accepted in c plus now we will do the same thing in java and python as well so this base case will remain same and in java let me write it here we have math. log and this log is base 10 by default and we don't have any specialized logs for 2 and 10 like the c plus case so we will use a property called uh log if base is some number a i would not be able to write it here let me draw here so if we have log a b then we can write it as log k b divided by log k a so here k can be any number different from a and b uh and if you want a proof of this let's see so what we are claiming is that log a b is equal to log k some other number base b divided by the same number that we used here a and why is that so let's say this value is uh let's call it p this value so what this means log a b is p that means a raise to the power p is b that is the definition of log if we take log base a both side left side we will get b right side we will get log a b so this is valid now this is our first equation now what is this value let's say this we called v b and this is equal to v a we have not proved it yet we will prove it so numerator is va so what this means k raised to the power va is equal to b and what this means if log k is v k a is va then it means sorry it should be b here k raised to the power of v a is a this is our equation 2 this is our equation 3. now substitute the values of a and b here so left side will become k raised to the power v a and this raised to the power b so it will become b let me write in this side so this everything is in the power if you write a m and you take power n it becomes a m n so the same way left hand side becomes this we have substituted the value of a and then on right hand side we substitute the value of b and uh here both k are positive numbers so we can get rid of these we can take log k on both side and left side we will get va times p and right side we will get vb that is their powers are equal so what will be the value of p it will be vb times vb divided by va so we have proved this what is vb is log kb and what is va log ka and what is p it's log a b so these so we have proved it so that will be used in we will use in our java solution so this log 2 does not exist so we will need math.log num so this will be log base 10 divided by math dot log 2 and let me again interfere here we want log 2 of x so here 2 is a if you look at this form and x is b so this can be written as log k and here we have k is 10 that is available to us log 10 b divided by log 10 a which is 2 and this log 10 is nothing but math dot log in java so math.log x divided by so math.log x divided by so math.log x divided by math.log 2 so that is what we have exactly written here math.log num divided by math.log math.log num divided by math.log math.log num divided by math.log 2 and then plus 1 and this is not required here and let's try it conversion from double to end so this division of two logs so let us convert it to int here and let's try again and this compiles so let's go ahead and submit and the solution is accepted in java as well now we will write the same thing in python and here we will not need to take the logs so we don't even need the base condition that is num equal to zero check we had added that only because of logs so we will straight away get num dot bit length and mask will be -1 and return num xor mask uh num bits some typo and the solution is correct here so let's submit and it's also accepted
Number Complement
number-complement
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Given an integer `num`, return _its complement_. **Example 1:** **Input:** num = 5 **Output:** 2 **Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. **Example 2:** **Input:** num = 1 **Output:** 0 **Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. **Constraints:** * `1 <= num < 231` **Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
null
Bit Manipulation
Easy
null
377
okay so lead code question combination sum four so in this video i'm going to go over the solution how to solve this problem and uh let's get started so let's resolve this problem combination sum four given an integer array with all the positive numbers and no duplicates so find the number of possible combinations that add up to positive add up to a positive integer target so let's say we have three numbers one two three and the target is four so the possible combination ways are listed as below uh so note that different sequences are counted as different combinations so therefore the output is seven so the solution is a dp solution essentially uh we define so first of all we will need to sort uh the nums array uh as any other then we define a dp array with the lens as target plus one so the dp so dpi means how many combinations are there to form a sum of i so of course there is one way to solve to combine to db zero which means uh there's zero numbers so when there's zero numbers there's one way to form a combination uh the sum up to zero so the next one uh we are going to uh try to figure out what dpi is so how to compute dpi so dpi is pretty much just a dpi so we are going to compute dpi we are going to go through every number within this number right to try to figure out what dpi minus num is so if dp i might so after we figure out what dpi minus num is it is something like we tr so we already figure out how many ways we can uh we can get the combination to get a sum of i minus num and we also have a number called num from the nums array so there is a way for there is this many ways uh currently uh to get a combination of the numbers that sum up to i so that's essentially uh how we uh how does uh the dp formula works and finally we are going to return db target so the overall runtime is going to be uh nm times n log n sorry n m plus n log n so n is uh essentially the target m is the length of the array so n log n is this sort and the n m is essentially this uh for two layer for loop so space-wise we need two layer for loop so space-wise we need two layer for loop so space-wise we need all of n which has the length of this dp array so let's see some follow-up questions it so let's see some follow-up questions it so let's see some follow-up questions it says what if the negative numbers are allowed in the given array so if negative number is allowed in the given array it can like the output can be uh can be um can be not a number like can be max integer the max value that is because let's say if we have another number which is minus one so we can have um we can have infinite pairs of minus one and one because minus one plus one is zero so we can have infinite power of minus one plus one so the target is the number of the number the target is the number of ways to get the target uh is infinity uh so if we how does it change the problem so if we change the problem then essentially there could be no answer for this like it could be infinity so what limitation we need to add to the question to allow negative numbers so i would say we need to have a limitation like what is the maximum numbers we could have within the combination so after adding that limitation i think we can try to get a good question out of it so that's it for this coding question if you have any question feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
258
hey guys welcome back to another video and today we're going to be solving the lead code question add digits so in this question we're given a non-negative integer number given a non-negative integer number given a non-negative integer number and when you repeatedly add all of its digits until the result has only one digit so let's say we have the number 38 so over here what we're going to first do is we're going to add 3 plus 8. so we're gonna do three plus eight which equals to eleven now we're going to take that 11 and we're going to add its digits so we have one and one so we're going to add one plus one and then we're gonna that equals a two so once we get a value which has a single digit we're just gonna return that so we get two so we're gonna output two all right so now let's solve this and in order to solve this i'm gonna take two approaches one is gonna be our more intuitive approach where we're gonna use a while loop and we're gonna loop through it until we find a sum which has a single digit and our second approach is gonna be a more mathematical approach and it's also gonna have a runtime of big o one okay let's so let's see how we can solve this all right so for our first solution let's see how we can solve that so let's say we're given an input of 2 342. so our first step is going to be to add all these together so 2 plus 3 plus 4 plus 2. so how can we actually iterate through each of the digits so let's see how we can do that so what i'm going to do is i'm going to have a variable called sum and it's going to start off with the value of 0. and then in order to get each digit what we're going to do is so we're going to do whatever our input value is and do mod 10 of it so we're going to get whatever is at the first digit so in this case we're going to take our 2342 and do mod 10 and then in that case we're going to get a value of 2. so now we also need to change our input and in order to do that we're going to do integer division so now our input value is going to be the old input so 2342 we're going to perform the integer division with 10. so in that case you're going to get 234.2 but since with the integer 234.2 but since with the integer 234.2 but since with the integer division it's going to drop out whatever decimals we have and it's just going to round it down so it's going to our input is now going to have a value of just 234 so now again we're going to take so and now we're going to take this number wherever we get here and add that to our sum so plus 2. okay so let's just keep doing this until we don't have anything in our input so now we're going to do 234 mod 10 which is equal to 4 now we're going to add that to our sum and then we're going to change our input value by doing 234 integer division 10 which is nothing but 23. so i'm sure you get the point by now i'll just show you one last time so now we're going to do 23 mod 10 which is equal to 3 now we need to change the value of our input so our input is going to be equal to 23 integer division of 10 which is equal to 2 and we're going to add this 3 again now we're going to add this 2 and now we have nothing inside of our input so now we added everything so right now our sum is equal to 2 plus 4 6 then 7 8 9 10 11. so our sum has a value of 11. now so as it is we didn't get the value but now we need to perform it one more time so we're gonna add all of its digits we're gonna do the same steps but i'm just gonna skip through it so that's nothing else but one plus one and that equals to two and two is a single digit number and we're gonna return this so this is going to be our answer so let's see how the code looks for this and then after we do solve it this way i'll show you the more mathematical way to solve it okay so our first step is going to be to initialize our answer which is gonna start off with zero and now we're gonna go inside of our while loop while our number is greater than zero so this is gonna we're gonna keep going through adding our digits until we have no more digits okay so each time we're going to add the number mod 10 to our answer so answer plus equals number mod 10 and we also need to change the value of our number by doing integer division with the value of 10. so this is going to keep going until we're done with all the digits so we need to know if our final answer has a value has a single digit value and in the case that it does not have a single digit value we're going to go inside of our while loop again and perform the same steps for our new found uh value right so in this case that's only going to happen if our answer is greater than 9 so if our answer is not greater than 9 then we're done with we got our answer if our answer is greater than nine that means that we need to perform at least one more iteration and the other condition is our number is going to be equal to zero uh just because uh when our number is equal to zero that means that in the previous iteration we went through all of the digits so when these two conditions are true we're going to reset the value of number so our number now is going to have the value of answers so just to be more clear in this example over here so we have 38 and after the first iteration we're gonna get a value of one now we need to reset the value of numbers to that of 11. so now our that's what we're doing over here so we're just changing the value of number to our current answer and we also need to reset our answer to the value of zero so then we start off from the beginning and we're going to get out of this while loop once our answer is less than 9 and in that case we're just going to return our answer and this should be accepted okay so yeah it is accepted and now let's look at our second solution so i just found this online uh so basically uh there's a rule so these numbers or what we're performing over here is actually given a name of something called digital root so this is exactly what a digital root is when you keep adding the nu the digits until you get a single digit number so there is actually a rule for getting this number and that is so what we're going to do is if our number is less than 10 in that case we're just going to return our number because it's already a single digit number and we could have actually we should have done this for our previous solution as well but it's fine okay so that's going to be our first step and now what the rule states is if the number mod 9 so whatever our number is with the modulo of 9 if that is equal to 0 then in that case our answer is going to have a value of 9 and if that is not the case then we're just going to return what the number mod9 so if number mod 9 is equal to 0 then we're going to return 9. and if that is not the case we're just going to return the number modulo 9 and that should be our answer so let's submit this and this solution was also accepted and finally just do let me know if you have any specific questions you want me to answer or if you have any questions regarding this solution and finally thanks a lot for watching and don't forget to like and subscribe thank you
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
2
hello guys welcome back to my channel so in this video we're going to continue with leet code and we're going to solve the second problem in Python it will be this one add two numbers so we are given two a non-empty linked lists two a non-empty linked lists two a non-empty linked lists representing non-negative integers and representing non-negative integers and representing non-negative integers and they are stored in reverse order so we will have to do simple arithmetic we just need to do the sum of these two numbers which are represented in linked lists so for that we are going to use this list note class which is already provided to us by leet code which is a linked list implementation we can access the value using Val and the pointer to the next value using next okay so before we write the code let's see first maybe a little sketch or a diagram to better understand the problem so let's say we are given this two linked list l1 and l2 and here we have the first value two and then we point to the next node which is which has the value 4 and the pointer to the next node which is has the value 3 and here we see that the linked list and since it points to none or now maybe in another programming language but I'm going to solve this in Python so I'm using none we also have the second big list which is this one we have five pointing to the next node which has six is value and the pointer to four and then it ends because this node points to none so this is the same as we were doing the sum of 342 backwards with 465 okay so in simple arithmetic what we do we start to do the sum of the first two units so 2 plus 5 is 7 and then we go to the tens and then we do 4 plus 6 is we which is 10 we put zero here and we carry the one so in our code we will also have to write something to hold this carry now here we do 3 plus 4 which is 7 plus the one we carried from this one and it is 8 and then we're pointing to 9 so this is what we want to implement we need to have another list node where we want to store the sum of these two numbers ok so now let's try to write this in Python ok so first I'm going to create a new list node just node and then I'm going to give it the value 0 just to start sorry ll is equal to list node now we are going to use this ll variable to store the value for each node in this list node so we are going to traverse through the list node so in the end we also went to want to store this list node in another variable so we can access it at the end so I'm going to do this risk for result equal to 11 okay so what I mentioned before was that we also need to store the carry for each operation we do so I'm going to initiate a carry which will be initialized with a 0 value since we have 0 to carry at the moment so what we want to do now we want to access each element in l1 though so the unit's in l1 and then the tens and in the hundreds so we need to access l1 using l1 dot Val for the value and then to go to the next one we do L 1 dot next okay so to traverse all the nodes in the list in the linked lists we will use a while loop so and then the conditions will be well l1 or l2 or Carrie so we need at least one of these conditions for as long as we have one node left in L or in l2 we are going to continue to get that value and work on it doing our operations and then we also need to continue if we have a carry if our carry is not zero then we need to do an extra operation so this will be our while loop now we want to access the values in l1 so we are going to do if 1 L 1 dot next well 1 sorry so if L 1 we're going to do value let's call this value 1 is going to be L 1 dot value so in our first iteration this is going to be the first the value in the first node okay and then we are we want to move to the next one so L 1 is going to be L 1 dot next if we don't have if so if we don't have L 1 so it is pointing to none we're going to put value 1 equal to 0 okay so we do the same for L 2 if L 2 we do 12 to be quills 2 L 2 dot one and then L 2 equals to L 2 dot next to make sure to move to the next node if we have so when we will this condition will not be true when L 2 is none which means that we have reached the end of the linked list so for that we're going to put well 2 equal to 0 so what we want to do now we want to do the sum of L 1 plus L 2 ok so the sum will be the first value in our new link list which we called ll but we also want to get the carry and the carry will be the sum of L 1 plus L 2 modulo 10 okay so let's write this first so we will do right here we're going to use in Python the function div mode which I'm going to explain right now what it does remainders okay so we have well plus 2 plus scary we shouldn't forget the carry so what the div mode does that it divides this sum by 10 and it returns us the quotient and the remainder exactly what we want okay so the quotient will be the quotient in this case is going to be the carry because we like we said if the sum is bigger than 10 we want to carry the 1 to the next operation okay so Kari is going to be no partying and then the remainder we want to put it in our linked list which is going to be the sum of these two numbers represent this linked list so ll dot next is going to be the remind the reminder yes okay so now we have stored oh sorry we have to put here list node yes so we are constructing the next node for this linked list LLO okay and then we need to move ll to the next one so we can traverse this list linked list okay so we will continue doing this until we traverse all the nodes in it in every in both of the linked lists and then ll will be pointing to none so will be pointing to the net to the last node in this linked list but we want to return this new linked list we created that's why we did this here so we can return the return it using our s re s dot next Y next because we started the this linked list here at zero but we want all the linked list after zero which will be the result of our sum okay so this seems to be okay let's try to run it oh we have a problem here let's see the code okay hmm sorry guys this was a really stupid mistake I just noticed I forgot to put the returned so let's run it again okay so it's working as expected let's try to submit this okay so here we have it is working fine okay so in the next video I'll try to solve the same problem but this time using Java okay guys so don't forget to Like share subscribe if you find this helpful so I can continue doing more videos like this thank you and I'll see you in the next one bye
Add Two Numbers
add-two-numbers
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[7,0,8\] **Explanation:** 342 + 465 = 807. **Example 2:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\] **Output:** \[8,9,9,9,0,0,0,1\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros.
null
Linked List,Math,Recursion
Medium
43,67,371,415,445,1031,1774
87
uh today we're gonna working on uh lead code question number 87 uh scramble strength okay so in this question we can scramble the string s i want to get uh to get a string t using the following algorithm okay basically the length of the string is one we need to stop right there if the length of the string is greater than one we have to do these things let the string into two non empty substrings at a random index uh that is uh if the string is s divided to x and y where s is equal to x plus y and then randomly decide uh to swap the two substring or to keep them in the same order that is after this step s may become s is equal to x plus y uh or s is equal to x of y plus x so we can actually uh we can actually change the position of x and y and apply step one recursively on each of the two sub strings x and y okay so given two strings s1 and s2 of the same length return true if s2 is a scrambled string of s1 otherwise return false so in this one example it explains in that it in detail like how he has done the above steps in order to prove that the great and rg e80 are can be scrambled uh like using these rules so in order to do that the way we're gonna be doing is to uh like use a helper method which is gonna be called uh recursively and also use uh like our dynamic programming array so that we don't keep calculating the same result over and over again so we're gonna call a helper function with s1 s2 and at the beginning it's gonna be an empty uh it's gonna be an empty array and our helper function is gonna be well it's basically gonna take that s1 s2 and dp array the first thing we want to check if the tp of s1 plus s2 is not equal to on undefined or the dp of s1 plus s2 is not equal to sorry s2 plus s1 is not equal to undefined and i'm sorry this is gonna be the map so the dp is basically a map where uh these are the keys which we're gonna be checking in this that's not gonna be an array so yeah the dp is gonna be a map and we are checking that whether we have already put the value of that key inside that map so we are checking if we have uh already port 30 s1 plus s2 as a key or s2 plus s1 as a key if this is not undefined in that case we cannot return the dp of s1 plus s2 otherwise we're gonna check that uh if s1 is equal to s2 if there is a case we're gonna basically return true other than that we also want to check if s1 dot length is not equal to s2.1 in that case we're is not equal to s2.1 in that case we're is not equal to s2.1 in that case we're gonna just return false otherwise one last thing is that else if we are at that point where uh where we have only uh one character left where we need to stop the uh the rule number one in that case if s1 dot length is less than equal to one in that case oh just gonna return s1 equals to s2 okay if none of that case if no if we're not in one of these cases what we're going to be doing is to loop uh i equals to 1 to i is less than s1 dot length and then i plus okay now if the helper of that s1 dot slides so basically we're gonna be splitting it and checking if that like the next step they're kind of recursively uh trying to evaluate the next step so that is gonna start from zero to i the next one is gonna be s2 dot slice 0 to i and then the dp there is the one thing and the helper of s1 dot slice the rest of the string s1 s2 dot slice of i and dp either this combination or we need to uh like kind of completely make the other combination true if this or the other one is that the helper of s1 dot slice 0 to i and yes this time this one has two is gonna be sliced uh with the s1 dot length minus i in the dp and help ups helper of s1 dot slice of i and s2 dot slice of 0 and then select s1 dot length minus i and then dp so basically we are making sure that we are actually so basically we are making sure that we are going to be so basically we're gonna be making sure that we are actually uh dividing the both strings in different ways and explained by the rule over here and we want to make sure that either the first combination or the other combination uh turns out to be true if that is the case we're gonna say that dp of s1 plus s2 is equal to true and we're going to be returning true if we come at this place out of this loop that means it is not true so dp of s1 plus s2 is gonna be equal to false we're gonna return false yep and it passed all the test cases
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: 1. If the length of the string is 1, stop. 2. If the length of the string is > 1, do the following: * Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`. * **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`. * Apply step 1 recursively on each of the two substrings `x` and `y`. Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. **Example 1:** **Input:** s1 = "great ", s2 = "rgeat " **Output:** true **Explanation:** One possible scenario applied on s1 is: "great " --> "gr/eat " // divide at random index. "gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order. "gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ". "r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat " which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. **Example 2:** **Input:** s1 = "abcde ", s2 = "caebd " **Output:** false **Example 3:** **Input:** s1 = "a ", s2 = "a " **Output:** true **Constraints:** * `s1.length == s2.length` * `1 <= s1.length <= 30` * `s1` and `s2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
null
1,697
welcome to Pomodoro job for Saturday April 29th 2023 today we're doing lead code problem 1697. checking existence of edge length limit 1697 checking existence of edge length limited paths this is a hard problem this one really hard problem all right an undirected graph of end nodes is defined by Edge list where Edge list index I is equal to UV and dist denotes an edge between nodes u and v with a distance of dist note that there may be multiple edges between two nodes for example here they have two edges one of distance two and one of distance 16 between 1 and 0. given an array queries where queries index I is equal to p q and limit your task is to determine for each query whether there is a path between p and Q such that each Edge on the path has a distance strictly less than limit return a Boolean array answer where answer length and query length are the same and the jth value of answer is true if there's a path for queries J that is true and false otherwise oh man this one is tough and I do not have a lot of time today so we'll put 25 minutes on the Pomodoro Timer and I am going to zoom through this I won't be explaining a lot and maybe I'll come back later and do some voiceover to explain it right for this one we're doing a union find so the idea here is we will sort all of our edges by length then we will actually build our sub graphs we will create a bunch of sub graphs by the length of the edge in the edge list so for example if we have a query that's looking for anything with a limit of up to length 20 then we want only edges in our graph that have length 19 or below or something less than 20 or blue so essentially we'll build these graphs that actually meet the limits of our query so we'll probably be sorting our queries by limit so we'll do the smaller graphs first building up to the larger graphs then we'll build these smaller graphs out of edges that just fit our limit in our query and then we can check to see if the two nodes that we're looking for are also in that graph now we also need to make sure that they're not just in the graph but they're in the same graph so for that we'll be using a union find Union find is a more advanced data structure or algorithm I'll try to explain it but again I have very little time today so I'll probably just be coding all right here we go let's start by creating our Union find class now for this one I will also be doing an optimization right off the bat because I know I need it so this mapping will just keep track of which nodes belong to which subgraphs foreign okay so this is our Union find data structure it has three methods the init it has the find and it has the union so find will find the sub graph in this case in the generic case it's called the parent in our case it's a sub graph so it'll find the subgraph that this node is in and Union will actually take two subgrabs graphs and merge them together into one okay first thing we want to do is sort our edges we're going to sort by distance so that is element number two in our Edge list for in each element of the edge list so it'll be node a node B and then distance between them so that's going to be X at index 2. next thing we want to do is sort our queries but before we sort our queries we need to keep track of the original index of the query so for that we'll have a mapping uh but this Q we will have to make a tuple okay so this is storing the index for our given query that way when we run the query and we create our result our answer we'll know which index to put the result into we're going to be doing all of our sorting by distance and again with the query it's going to be Node 1 node two and then the distance that's going to be X at index 2. so we've sorted our edges we've sorted our queries now we need to create our sub graphs and we need to create our initial empty or our initial result I guess I should say I should call this current Edge index we're just going to assume true for the time being at the end we will return our result but now we have to go through and actually run all of these queries all right so let's do that okay so our query we're going to have a node one a node two and some distance d now we need to add all of our edges to our current Union and find so we're going to go through and add edges but only edges up to the limit of this query so instead of D maybe I should call this limit uh maybe this name is too long so we'll just call this current Edge instead of current Edge index so all the current Edge we're going to get our current Edge out of this sorted edges list and we want to find its distance so that's going to be at index 2. so while that is less than our current limit then this is a valid Edge to put in our current graph all right so now we have node one node two and now we need to actually add this Edge to our Union fine to keep track of so let's see I'm actually going to change these names instead of N1 I'll call it query one query two those are the query nodes so this Edge is going to have an N1 and N2 and some distance d that's going to be the sort of edges okay now we just need to add this to our sub graphs not index two that's right so we'll just Union these two nodes together and we don't actually need the distance in this case then we need to move on to the next Edge so this is building up a sub graph using only edges that are below our current limit okay once we've built up that graph now we'll actually execute our query and that's going to be a little bit simpler so first we need to figure out what's the reverse index so like the proper index to put our query back into let's see what's going to be in this index map here and again we need to create a tuple out of our query and our result at this query index that's just going to equal whether or not these two query nodes so that's q1 and Q2 here if they are in the same subgraph so we can do that by checking the subgraph find q1 and if that's the same as the sub graph that we find for Q2 they are in the same subgraph and all the edges in that graph are below our limit so that'll be true otherwise it will set it to false okay barring any typos I think this should do it let's give it a shot and of course I have typos let's see what's going on here a bad index right no it's not right this is the bad indent current Edge is not defined because I have too many r's here which means I copied and pasted to here all right see if that works hello some graphs plural foreign let's see if we can pass all the tests so again this one's super complicated and I really don't have enough time to give it the time that it deserves all right and we do pass and we do okay 52 for runtime seven percent for memory yeah so this one super tricky I will try to make a better video on this later but today that is all for me alright hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
Checking Existence of Edge Length Limited Paths
strings-differ-by-one-character
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` . Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_. **Example 1:** **Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\] **Output:** \[false,true\] **Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16. For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query. For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query. **Example 2:** **Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\] **Output:** \[true,false\] **Exaplanation:** The above figure shows the given graph. **Constraints:** * `2 <= n <= 105` * `1 <= edgeList.length, queries.length <= 105` * `edgeList[i].length == 3` * `queries[j].length == 3` * `0 <= ui, vi, pj, qj <= n - 1` * `ui != vi` * `pj != qj` * `1 <= disi, limitj <= 109` * There may be **multiple** edges between two nodes.
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Hash Table,String,Rolling Hash,Hash Function
Medium
2256
141
hello hi everyone welcome back to the channel so this is your randip Singh today we'll be solving this problem link list cycle so in this problem we are given the head of a linked list and we have to determine if the linked list has a cycle in it right so what is a cycle in a link list so here we have our link list the last node of the link list points to the previous one of the previous notes of the link LS then that forms a cycle how we can detect this cycle that's what we have to know right so let's see how we can do that to do so what we need to do is we need to take two pointers the first pointer is f the second pointer is s basically the algorithm which we are going to use here to do to solve this problem is called Floyd's cycle detection algorithm so in this algorithm what we do is we use these two pointers the slow pointer moves one step ahead like this from first node to the second node to the third node to the fourth node and so on while the first pointer moves two steps Ahad from first to the third node then from the third to the fifth node and so on so what we will do is we'll start these two pointers from this head node and we'll make them run so let's start from the node one so from this node we'll move to the second node this is my slow pointer so the slow pointer is here so let's call S while in the very first iteration the fast pointer will reach this point let's move to the next iteration in the next iteration the fast will be one 2 the fast will be here and the second will be here let's move to the third iteration in the third iteration the second will be here the first will be here again the fast will be here so what we observe here after a few iterations these two pointers are matching that was only possible if we had this link here right if we had this link that means we started fast from here we moveed to this node then the fast pointer move to this node and in that time the second pointer is standing at this point right because one two and then one two and three in three iterations the first pointer is here 1 2 and three and in three iterations the second pointer is also here so what does that mean that means after certain number of iterations if we have a cycle then these two pointers are going to meet and that's how we going to solve this problem we'll use two pointers we'll start from the head node and we move ahead we move those two notes in the given link list and we check whether they meet at any point or not when they meet at some point then that means there is a cycle in the link list so let's see how we can do that so here in this case let's see how we can do that so let's first do this low the head fter now let's move this Loop first and low and fast next till why I'm doing this because the Fast Point must not be enough the slow must not be null and the next of the fast must not be null for make the move because we have to move two points like from here if I want to jump to the third node next to the next node then I need to have at least this node right why because let's say if we do not have this node then what I will have when I move two steps ahe I will end up with a null pointer and that's allowed but there's nothing next to the null pointer so I at least need one more node one more not non null node after the node on which I standing right so let's see slow is equals to slow next fast is equals to fast next so at if at any point these two pointers are matching if fast is equal to slow then I'm going to return true otherwise you have to return false at the end of this function so let's run this code so let's submit it okay that got accepted so that was all we had to do this is called Floy algorithm to detect the cycle I hope you understood the algorithm in the very next video I will be discussing the proof for this algorithm the proof for the Floyd's algorithm stay in touch stay tuned with me I will see you soon in my next video till then take care bye-bye love you
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
1,740
Hai gas welcome to today's video and today we are going to do lead code problem 1740 whose name is find distance in a binary tree so basically here we have two nodes or the values ​​of two notes are P and K or the values ​​of two notes are P and K or the values ​​of two notes are P and K and we have one root. Of a binary tree and we have to find out the distance between the notes corresponding to these two volumes and return that, then D distance between you North is D number of edge on D path from one and here if there are no vertices then adjust. Above this is going to be decide how big is that text and for example if there was five and zero here then one two and three next A so the output is going to be three is this vertex or vertex is vertex then tax is 5310 so three condition is power. First condition will be left side otherwise second condition will be P and K R Both condition will be mine one P is on left and why is it on right otherwise why is it on left and P is on right then apart from these three conditions are there any conditions? Okay, we did this by doing these conditions, so in some cases, I am seeing that if I find my own locket in this, the LCM, we find that, if I find the L C L O S common sister, then what? What will my reduction be? Let's see once and for example, now my P was here and K was here, so what is the lowest common nc² of P and K. Three, so if I have these three notes A, somehow the LCM one, then I What will I do directly, I will get the distance of P from me and the distance of K will get from my LCM and after adding both those distances I will return, that means this is such a simple answer or approach that first of all I will find the LCM and then what will I do. My left one aa left and second distance laka then after that the next one is get distance of p from LCM and this will be the digital edition of both so this is how the strike of LCM happened in my mother so you can see that we have the same information. It is not in Nord that my K and P are going to come on the left and right, so obviously I will have to search and enter a lot of information, first of all I will have to see whether I should traverse the shirt on the left or do the driver on the right and then also I will have to check whether my LCM is passing through the notes of P and K when it means I am on the road during the day or not. If not, then I will have to look for some more information on my left. And we will have to go to the right note because coming D and off D, I don't know where my P and K are going to be, but this is our optimum condition, when my P will come to the left and when it will come to the left, then what will I do directly? I can calculate the distance of P and K from my notes using my light and then by just doing distance addition, I can calculate the distance between those two notes, then why would this LCM be good, then you can think like this, if this is any And if there is one tree or all are free, then from this sub-tree also I will have to come here @ and off then from this sub-tree also I will have to come here @ and off then from this sub-tree also I will have to come here @ and off date. If I take any two notes, I mean, which two notes can I take, in this tree, but D and off D come. You will be able to calculate its distance only after coming to the LCM, because in this time, if both of these are also there, but for example P and K, then you will have to navigate to this note somehow and then you We could have found that okay, this is one and this is two because our two notes are never going to be D and off D, the notes of P and K are going to be equal, how will we do next that if P = K then what? So we do next that if P = K then what? So we do next that if P = K then what? So how can I directly apply the base in such a way that if the value of P is equal to my K then directly return zero because there is no distance between them, but if my K and P are two distinct then I will get every You will have to take LCM once, but for example, if these two notes are distinct P and K, then I will have to take that note. In G mode, my P and K are going, otherwise you can also see like this, if my P is this. And if K is this then I will have to come to the Atlas to see how much is my distance from K, so we have to come to LCM to see how much of my P and K is from that note. distance from which I get the text which connects P and K and that is our distance is the distance of those two notes so if I want to find the distance of two notes then I have to find their position so this is Approach key I want you to find the distance between I have you get the text or get so from LCM we can directly lock those five and take two distances from there and after adding that we can directly return the length of that text so it is ok. Hope guys, you must have come to know this approach and we have already written the algorithm here, so now we will code it, first of all we will take the luck, then we will get the distance and then we will add the return. Okay, so now let us code one. So first of all what will I do for that, I will write a function of luck, we have already done the problems, and if you have not seen that then please first go and watch that video where we explained in detail. How do we find the LCM of two notes, so if you have not seen it then please go and see it first, then this will be my one 3 note LCM, I give you, I pass the route, a public train will return and it will return. CA's and Gate LCM is its name and we take a tree note and wait exactly what will we write in LCM. First of all, if any note comes to me as null then what will I do, if it is not my LCM then I will return it. Meaning, I will not be able to find LCM because it doesn't do all the tricks, so what will I do in it? If the note is null, then return it to my left and right. Tomorrow I will put cursive that and bring me the note. If you find the note, then that. And g time I get a note that note equal tu p and k so what I do is return my current note that means we are getting a note that is matching with this value so Now we will do this, there is no return and then what will we do if I get a note in which both notes are found on the left and on the right, then what does it mean, I am its LCM, the first note that we will get, in which I also have one note on my left. Mode is found and it is also found in the right side so in LCM also we do the same if in my left side a mode is found which we are looking for and in the right side also a note is found which we are looking for then that means I am his lowest mango and sister, so what to do here, if found and right found then what to do, return the current note because I am the LCM and if not found, what will you do, then what is the meaning of return if but give me an example like this. There is a note, this P is mine and now this is my current note and why is it so what will I get from it P but what has happened now, I have got only this note and why this note, to find the note I will have to go from here to here, so What will I do with my DFS which is due tomorrow? Will I send my current note there itself? What will happen to it? It will also go to the right to search for my why note. We have not found the one we need till now, then this would have happened. That's why turn it to the left, we don't have to return the null notes because if we return the null notes, then how will we find them from L, this is what happens to the entire lakh, so now we have got LCM. Please gas, video of our own luck. If you have not seen then please go there and see once that we find out from LCM, there you will get very good clarity and understanding. So what will we do now, first of all we will take the distance, then print left or distance = distance should be there. Why so this is our total distance between P and K from or through and LCM gives the right function first of all what I will do is public distance in is going to return our LCM and a value that we have to find so what we will do is first of all IF our How will the base be that if we get that one normal, we will have to pass, so what am I doing here, I am starting my distance from zero and every time I will keep adding distance to one left and right corner and whenever I That note will be received only then I will know why that distance is still late or added and I will return the distance every time from tomorrow onwards and then we will get that distance, so if you are not able to know then do not take tension. We are going to drive so first of all if my value is equal with the value of you note then reduce my distance by one and return the distance of the five that we have traveled till now, what will we do now which will be the left distance and then After that what will we do distance plus one we have done ok and now what will we do return first of all if I have already got such a note which is equal in value then what will I do IF left distance because I have already got such a note Which is equal to my value, then I want to return the distance of that, you give me note and come D and off D of mine, which will be LCM, it will return here the distance P, that distance and similarly if I have got it on my right side. Wide stunts then return that distance right distance and if I have not got it in left and right then what will I do I will return left and plus right distance so when will this happen when my left and right distance will be zero and I will not get any note equal to value then I will return only zero but for example if I want to find ₹ 5 on this note example if I want to find ₹ 5 on this note example if I want to find ₹ 5 on this note then my left will go like this tomorrow it will return left means tap on tap will return zero on its consumption. Right will return zero tomorrow also and what will seven itself do? 0 + 0 which is and what will seven itself do? 0 + 0 which is and what will seven itself do? 0 + 0 which is zero and it means that it has not got a five on the left side of 2. Similarly you will go to the right side, right will play four tomorrow on its left and right. From yesterday he started taking zero in the distance left and right and will also send 4. Zero because he has not received that note and similarly you B will send zero to its parent note because that zero signifies that we have not received that note yet. OK, so now this is our complete code and now we will run it once and see if there are any mistakes, they will be corrected, OK, it is wrong, it is 97, OK, the number 9 should have been 24, OK, and here But the bigger one will be left wild distance plus one right so first of all we will write and LCM and what do I pass A and pass K and LCM does tomorrow we will run Android left found it equal you get LCM North K right Search for I. If you have found it then reduce one and return it. What to return. If you have found it means you have got both the notes then return this note because you have found it and you are going to return it on your right. If left pound is null then return it. If it is not null then write like this then return it. Left phone is not found and after that what we were going to do is get distance and in that we will pass tristan distance p plus distance. Why is it okay so this is ours. Now we will write the distance, how are we going to calculate the distance, then the gate will do the distance and guess what is a fairy note, tree note, which one is this LCM, then we will name it note and then wait, it will give us the value whose value we will get and whose distance we will get. If you want to find it then its base will remain the same that IF NO = NULL then reduce it by one and remain the same that IF NO = NULL then reduce it by one and remain the same that IF NO = NULL then reduce it by one and return it to zero because you have not found this note, then after that in the distance we were also passing this, start from zero, your distance and Every time he adds the distance, it will be this distance. Okay, so reduce one by one and return the distance till now. Return D distance till no if note found it. Then what are we left. Give me the distance to the left of the note. I will pass the value and distance plus one because the left note of mine is one distance away from me. Similarly the right distance will be mine. We will pass the right value of get distance north again because the right note is away from me by one distance and then its What will I do later? I will return the left distance plus the right distance. If you have not received the note but if you have already received such a note, IF the left distance is greater than zero, that means you have found the note which we have to find, then right from here. Tomorrow, what to do but go direct, return this left distance because we have already got that distance. Similarly, if you have got my note on the right, then return that right distance because then there is definitely life in the left next to it. We don't have it, so this is our code, once we run it and see something is going right, okay let's run it once and here the line number should be 16 stars and here something is going wrong, take a look. Let's take what is wrong if note is equal tu null painter return if the value of my north is equal to PK or is equal to K then return my note left found left has been put right found right has been put if is found ho And if right is found then this is LCM. IMD LCM. Similarly, if my left is not found then null painter then left is going right. Let's check it once. Starting from zero, note that LCM has passed the value distance, so all this is correct. It is going on that I have passed P and K once, I have seen BP here and why So now we will tell whether ours is correct or not, then this will tell which of these two is ours. Which means if it is not going smoothly then luck has come, our 3 means we have this function again Is there any problem in distance or not, this is our next page, we have brought our gate distance here, brought LCM here, okay and Drawn my strike here and let's start we will have to bring this also this will be my find distance works fine here and A goes in the stock three what does it see my value is not equal to you P and K From P our is five and why is it zero then what do we do? The one on the left is the cost from here and then gets added. What does five do? Have you seen that ok my value is equal to PK so I return it. From here A goes to the left of three, what does it do to its right, it moves right tomorrow, its right gets added from yesterday, its left moves tomorrow, it adds zero, what does it do? Well, my K is equal to my mobile. I lower myself because in the lift of one, A goes to take 10, it is late and because it has only one found left and it goes to the right and it adds 8 here and there and then adds something. If it doesn't happen, he runs his left and right yesterday and adds the tap both the times and returns from here, that's why both the left and right of 8 are nonstop, tap is done with this type and because both of them What does it do if it is null? If the left form is null then return the right form, so it calls right and returns null. Then it goes to the right of one and what does one do itself? So what do I do with my left phone? So here we go to A, its meaning is then what do we do after that, first of all we go to distance and put LCM, here which is three and put P, ​​today N value is also what put P, ​​today N value is also what put P, ​​today N value is also what is ours? If there is five, then what do we do first in the gate distance? We check whether it is nodal or not. Is my north equal north's well equal tu value and if it is not there then what do I do? I go left distance and add my left tomorrow. I add five here, then what does five do? Well, my value is equal to the value, so I return here the distance one. Why does it return the distance because when we drove this left yesterday for three? Our distance relief is zero so know the value here if this distance is zero mother take this distance then three what does it do while applying distance plus one means this one does its value from the distance is equal so returns the distance so and this five One goes to our LCM, now 3, what do we do, why do we do distance tomorrow and here again add 3 to our LCM with distance zero, then what does we do, first of all we move our left tomorrow, distance one. Together, then move your left tomorrow, it makes the distance 6² with you, then move your left tomorrow, and here add Nal Painter and from here return zero Nal, you go distance three, which is ours. Why is it sorry zero, so I reduce it, I return the left plus right distance which is to the left of zero five and this becomes it goes away, gives it, adds it, what do you do, your left goes away tomorrow. Adds 7 to 7, goes to your left and right, and neither of them gets zero, because it adds the null and returns the base, and then seven returns zero to your left. You go to your right, tomorrow it works, adds four to four, again left and right tomorrow and returns zero because this tap gets added and from here we were returning zero, then what? It returns that I have not got zero yet in my note, then what you do after that, I will also return left plus right which is equal to you zero, that is why it returns, till now then 3 What does it do to its right, it moves tomorrow, it adds relief, one to one's distance, one moves to its left, it moves tomorrow, it adds zero to its distance, then what do you do, okay now let me get my value. If I have gone then what do I do? Equal is the value that we have to find. So I return my distance which is you. Then when I find this zero for the first time, then what does one do? Left after walking tomorrow, directly. I have seen that my value left value is greater than zero, so I return the left distance, so you return, here you returned one, so come now D. And why do we get the distance i a goes tu and then @ what we do is return @ what we do is return @ what we do is return distance p + distance k which is distance p + distance k which is distance p + distance k which is equal tu plus one which is three so we get this text. Hotel and I have come to know about it and we will do it one more time with the example Then I have to say four, okay I have not got both of them completely, but I have got one in the left phone, so I will note that only. I return it here, so it returns the one to the left of the three and it goes away from the tax. What does Prithvi do? He moves it to his right. Adds the five. Then what does the five do to his left. Let's go, he adds six and we have to say six, I am the one whom we have to find, I am equal by the value of key, I return me to myself, he goes from six to here, he runs it from the stock here. Then what does Five do? He moves his right side, adds the tap, but from here the return is done by tap, well, I have got only one on the left side, I switch it to mode only, returns. Because this left phone is not his tap then it goes away then I return myself because I myself am our LCM, set 3 is done, let's do set 3 distance tomorrow, passing the LCM first. Here my left goes tomorrow. By going left tomorrow, I add four to here with distance one zero plus one, then after that I return four to my distance, so it returns to you and goes to what I wanted to find. I return the same distance directly. If I had to search further for my parent, I return the same note. I return the same wait. Then what do we do? Why do we go with the distance with zero and we start searching why it is what it is? Equals you 6 So now everything is the same again Three Apna left kal chala adds to four And Apna left ka chala adds to one One Apna ka chala adds to and returns the handle From there it is zero one, its right goes tomorrow, after adding the tap it returns zero, then this tap goes from the stock and because one has not got any s6 at this time, so what does one do left distance which is Is equal, you return zero, four, its meaning is that I have not found the note you are looking for yet and it becomes one, he adds it, then after that, what does he do himself? You have to say, okay, I haven't found that note in both my left and right, so I reduce it by one, I also return zero by adding left plus right, then what does it do to my right, saying, 'Kal chalta 3' It's okay, if I don't find it on my left, saying, 'Kal chalta 3' It's okay, if I don't find it on my left, saying, 'Kal chalta 3' It's okay, if I don't find it on my left, then I will go to the left and look at the right. Once he moves to the right, he adds five. Tomorrow, he moves to his left and adds six. But at this time, the most First you have to say six, okay, I am the one who is looking for us, so what do I do, my distance has passed so far, three had passed five had passed six with one distance, you have passed with distance. I return this distance to my parent, whatever you have done, then they become this, I return from here and I have to say, okay, I have found the note I was looking for, so I return this note at this distance. I give it to my parent who is late, the right one of 3, then free, what to say, okay, it goes like this, okay, I have found the note in my right, which I was looking for, so I am the same which is right distance. That's what I return, so this becomes tu, here the return is equal to distance, this is equal to three and this is completed by tax, then come d and off d, what do we do, we have already got from L. Which three we have also got the distance which is tu and why we have got the distance which is so we do distance p + distance k we do distance p + distance k we do distance p + distance k tu plus three add which is 5 and this 5 returns this answer. Is our answer equal? ​​This is 12 little no distance p our 2nd was sorry distance why ours you were so 3 when we put the right kal then it turns into five add with distance one and five what does when you Left goes tomorrow, you add six with distance, you are returning it, we are returning it and you also return five, this is you, here we add it with distance, you and we are returning 2 + 2 which Key is equal to 2 + 2 which Key is equal to 2 + 2 which Key is equal to four and this total four answer goes to us, here I have written only you and we return this complete answer to us, then what is my answer Laka that if it is also possible that I get the entire left. And after getting written, I get such a note which is happening at the end of my write, LCM will be off N, then after that what do we do, let's go to the gate distance for P and K, then both of them are also gate distance P. If you have understood everything about Ka of N and Gate Distance, please try to run the question yourself and submit it and after submitting, do tell me that you have submitted, you will get the questions.
Find Distance in a Binary Tree
count-subtrees-with-max-distance-between-cities
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Dynamic Programming,Bit Manipulation,Tree,Enumeration,Bitmask
Hard
1177
198
Hello Hi Everyone Welcome To My Channel It's All The Problem How So You Are Professional Work Planning To Rock House On The Streets Of Us Have Certain Amount Of Money Only Can Stop You From Each Of The Independence Connected And Will Automatically In To-Do List Of negativity of money In To-Do List Of negativity of money In To-Do List Of negativity of money you can draw system example subscribe to subscribe our 200 examples to so let's understand this over that morning money lists job live whole from the number 0123 more than 400 and in general and definitely subscribe to this channel possible oil can come From - 20 - 1m that from the current becomes and b its setting 's acceptance of death witch can come from it - 's acceptance of death witch can come from it - 's acceptance of death witch can come from it - one who will take over subscribe our and function of it from being robbed of - two plus whiteness different house will be - two plus whiteness different house will be - two plus whiteness different house will be Minus one is the function will start from last subscribe and subscribe robert se developed solution for its improvement developed and undeveloped solution will check that film will return from the sources also written raw no - festival function problem half fuel nor will check it must return gift otherwise Written Update After Proving Default - 211 More Proving Default - 211 More Proving Default - 211 More What You Are Running From Being Born In Mushar Subscribe Risum Specific Soil Might Live But Passed Away Into The Road Subscribe Now Subscribe C 210E Is Still Going On So Let's Understand That Aircraft Index Meanwhile Have come into force on which can come from 21 2012 and 2013 Similarly after they can come from one or two 181 Destroys Coming Again Subah is a Britisher problem so they can apply for the result of the width problem you later this definitely vitamin E will tell you Can Also Related Entries Subscribe Now To 99 Will Also A Piya Aa Is Not Internal Server Error In This First To Enter Into India With The Position Of Festival Development Officer The Repeaters Problem Festival Programming Approach To Avoid Time Complexity Of Dissolution Of Subscribe To The Page if you liked The Video then subscribe to The Amazing subscribe The Channel and subscribe the two and you subscribe the two and 10 from [ two and you subscribe the two and 10 from [ two and you subscribe the two and 10 from Water Drop Nam Shubh Naav will update the amount of that from B Math Dot Mix Madam X of Is The ODI Previous Basically Today Live Video Channel Subscribe Like Subscribe Now To Receive New Updates To Plus To Try To With Fun Ki Hand Jeevanvidhi Maximum Hai 116 Environments Maximum Widget Will Update Distribution Will Return Comment Hai So Let's Compile Scored A Small And Middle-Sized Farms In It's Possible at Middle-Sized Farms In It's Possible at Middle-Sized Farms In It's Possible at Samridhi Code Ki Samiti Shi Akshar Take Show Time Complexity of Dissolution and Also of Pain and Distress Complexities Pair subscribe and subscribe the Channel thanks for watching
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems 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 = \[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 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262
237
what's up guys this is lead code 237 deleted node in a linked list write a function to delete a node except the tail in a single link of the list giving only access to that node given link at least head four five one nine which looks like the following we need to delete what we need to delete here so node five into the node 5 and return the list without this node here we need to delete node 1 and return it will not actually return delete we don't need to return anything just delete the node with some nodes here the link at the list will have at least two elements all of the nodes values will be unique the given node will not be the tail and it will always be a valid node of the linked list not return anything from your function okay so this is a everything an exercise here only called that is done voted there are a lot of downfalls here much more than up folks and i think it's because we will not actually delete the node that we were given as an argument the solution for this problem will be we need to update the current node values and set the next pointer to the current.next.next pointer to the current.next.next pointer to the current.next.next so we are actually deleting the next node but not the current node we are just updating its values okay so let's try to write some code to understand how this works so as i said before we will not delete the node that we were given here as an argument we will update its values and set the next node to the create.next.next node to the create.next.next node to the create.next.next so that we will like simulate the deletion of the current node so it works like this so imagine that we have this list here four five one and nine and we were given this node here the node one and we have to delete the node one what we will do we will here at the node one update the node values to get the next node value which is nine and set the current node.next to be and set the current node.next to be and set the current node.next to be the current node dot next node.next.next the current node dot next node.next.next the current node dot next node.next.next which in this case is no so we will do something like that okay so the code to do this will be okay so let's just check if the node itself is valid now there's no we just stopped the function and also we will update the node values denote value to the node.next dot the node.next dot the node.next dot bell and set denote.next should be the node.next denote.next should be the node.next denote.next should be the node.next not next and i think that's pretty much the solution let's try to run that's it let's try another key here where we want to delete the first node that's it let's try to hit submit that's it so that's the solution for this problem thanks for watching
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
67
hello guys I hope you are all doing well in this video I will show you how to solve the problem lead code add binary so let's get started the problem is that they give us a two binary strings and they ask us to return their sum as a binary string so as we know decimal number are from 0 to 9 and for binary numbers are numbers that are presented only by zeros and one so in simple terms a decimal number has based a number and the binary number has a base two so in decimal to Binary conversion the base of the number also changed from base 10 to base 2. so before we start converting decimal numbers to binary numbers let's start by understanding how decimal numbers are represented and how they work so let's seek this number so the decimal number are represented in columns and each columns represent a power of 10. for example in this number the 3 represents three ones or three multiplied by ten to the power of zero the number two represents two tens or two multiplied by ten to the power of one the next number one represents 100 or we can say 1 is multiplied by 10 to the power of 2. so the number last number the number 2 represents two thousand or we can say that 2 is multiplied by ten to the power of 3. so all decimal number are base 10 numbers on the other side the binary numbers are base two numbers so let's use this binary number and try to convert it to a decimal number so binary numbers are also represented in columns each columns represent a power of two for example the First Column represents two to the power of zero multiplied by the value of the First Column and we add it to the next number zero multiplied by two to the power of 1 which represent the second column then we add it to the next number one multiplied by 2 to the power of 2 which represent the third column finally we add it to the last number one multiply by two to the power of 3 which represent the last column and the binary number so after adding everything together we get 13 as a decimal number and base 10. so now that we have a basic understand standard of decimal and binary numbers let's take a look how we can add two binary numbers together so binary addition is an operation of sum in numbers and binary form so it's worked like a normal decimal addition the difference is that the number are presented only in zeros and ones as digits so let's take some test case so that you can see how it's work so a represent the first binary number and the B represent the second binary number so if a and b are both equal to zero the sum will be zero and the curry will be zero if a is equal to 0 and B is equal to one the sum will be one and also the curry will be zero and the same if we have the opposite but if we have both A and B are equal to one the sum here will be 0 and the carry will be 1 which will result a carry that will move to the next column or number so let's take an example let's say we have those two input strings a equal to one zero one and b equal to one zero one so we start by looping throughout the two string and reversed order we take the first binary number from a and from B we sum up them so the result will be zero but we will have a current number to add to the next operation then we move the second number we have zero plus the curry one so the result will be one and the curry will be zero next we move to the next number we have one plus zero plus the car is zero so the sum will be one and the car will be zero then we move to the next numbers so here we have one plus the car is zero so the results are one and the curry are also R zero and finally we'll have a result equal to zero one zero so the time complexity for this solution is off S because we are looping over the string that have more characters or we can say the time complexities often where n is the maximum length of the two input strings and the space complexity is off and since we are creating an array that are related to the two input strings that's it guys so let's jump at code in the solution so the first thing we need to do is to initialize a variable result and set his value to be an empty array then we initialize our variable called Curry that's going to hold the carry of the audition after that we initialize two variables and set their value to be the last index of the two strings so that we can Loop and reverse the order throughout the string then we Loop over the two strings and reverse it order while I is bigger or equal to zero or G is bigger or equal to zero or if we have a curry left so we start by initializing a variable called total and set his value at first equal to the curry so then we start by checking if I is bigger or equal to zero we add the current number at index I to the total and we use the nth function to convert the string to an integer and we decrement the index I by One the same thing for G of G is bigger than or equal to zero we add the current value to the total by using the nth function in Python so that we can convert the string to an integer and we decrement the G index by one after that we take the modulo 2 of the total and we add it to the array result as a string then we update the curry to be equal to the total divided by 2 so it can return a wall number finally we convert the reverses the result array to the string using the join method and python which takes all the elements and group them into one single string and return the result that's it guys thanks for watching see you in the next video
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,239
I'm taking a very big risk on making this video because I have seen that if you discuss many approaches the video goes long and people don't like the long videos people just want the answers so I know okay I'm taking the risk for sure the video will be long because I'll discuss every approach recursion backtracking bit manipulation act extra also we'll also discuss why DP cannot be applied all that stuff it's the reason video will go long but people don't like the video being long that's okay but it's a risk which I'm taking yeah this question has been asked by Microsoft Tesla Uber and honey I don't know uh let's start with the what the problem says it says that maximum length of a concatenated string with unique characters which ultimately says the same thing that we have to figure out okay we are given some strings again the question itself is pretty weak which means one H Cas the question neither the question nor the examples cover what that is okay we are given an array of string called as error which means you can see AR of string error and a string s is formed by concatenation of a subsequence of error I'll take some subsequence which means I can take un UE anything whatsoever and then I can make I can concatenate them and you can see subsequences just but okay any positions any indexes I can take and I can concatenate them and get the answer but the condition is that it should have unique characters so if I do a concatenation of them it should ultimately have unique characters now the one thing or Edge case which you could have missed okay do I need that okay both of them should be different and after concatenation it can have a same character or like after concatenation entirely as in I'm say okay let's say it has some element un and it has IQ so yeah both have different so I can simply concatenate them I can make a U and IQ and that will be my answer which is the length four which is the maximum length again maximum possible length of s but what if I ask you if it had a u n QQ then would you combine them because after combining okay you will say because I'll just combine them because this the characters are not matching but for sure you will see that okay indirectly it's obvious that you need to have unique characters in a string but yeah it should have been specified at least in the example that we cannot take the string itself which has duplicate characters that is one thing which you have to make sure this is not mentioning the question now let's come on that simply we have see again we have to do one thing we have to try the maximum possible length such that okay for example if I am at the first location I will have two options either I should take that character or I should skip that character which means I just have to take some characters take see I just have to take some strings out of this entire thing it's a subsequence right so I'm just simply trying to make a subsequence is nothing but okay take it or not take it so at this location I have two options either I can take it or I can skip it then if let's say I take it so I will have a CH then I can go to next one I can take it as I can skip it if I take it I will have a CH a r if I skip I will have a CH a and then I can go on to next so it's nothing but I'm trying to form all possible subsequences in the first place let's see it's a simple take not take okay take it which means you will take your cha if you skip it which means you don't take it which means okay now you will have the new Range which is this entire range itself okay let's say if you are at this location if you choose to take R then okay you added a c h a and then R added again I just wanted a subsequence I wanted them to have unique characters so I will have to maintain a check I am not getting a string which is having duplicate characters so that is check which will be applied if we are taking something if you're skipping simply skip okay if you skip this okay skipping that now the new Range will be act and ERS s now if I take it if I take act now you will see if I take it which means I will be appending this entire string on my CH R if I append the string for sure a will actually match if something is matching your main condition that it should not have duplicate is violated so for sure you cannot go here which means you cannot take it so for sure if something I'm about to take I will have to put a condition okay it's actually matching or not now if I don't take which means if I skip it then for sure uh characters plus ERS now the same way the entire tree can be built you for your reference you can have a look but now for sure as soon as te as soon as your take not take comes in picture if we have a pre-owned mindset picture if we have a pre-owned mindset picture if we have a pre-owned mindset that we will apply DP right firstly we'll apply DP that is one thing you will think of but in a contest I'm seeing in an interview you might think of applying a DP for sure you might think and that's obvious but in the coding contest you will see the constraints DP is never used for these kind of constraints maybe we can use dig DP but you can see these all are alphabets so for sure one thing is obvious we have a conflicting views one way we are saying that it's a take not which is obvious napsack which is obvious we can apply DP again we have not gone through maybe you are smart maybe you are just saying okay for sure that for sure I cannot apply DP but yeah one thing is obvious by are so much study that Fe might apply DP and by this we see okay for sure DP is not applied recursion also will actually work and that's obvious recursion will work with this kind of constraints very obvious because why recursion will work but is nothing but two for a recursion is something but take not take M you have two options for every string you have two options take it or not take it 2 into two into 2 into two and let's say you have n strings so it's nothing but 2 N which will for sure work so for sure recursion will work but still let's see why DP cannot be applied now let's say if you apply DP then DP will store a sub problem right and your sub problem and your main problem was finding the maximum possible length of string s so your sub problem will also store the maximum possible length for a specific portion which means let's say my sub problem stored starting from this index up to the Super End what is the maximum possible length right now let's say you will see maximum possible length right here is four which it can actually store okay he will store four as maximum possible length then when I will be getting like I will be triggering my answer for this portion I will ask the pre-computed value for the right portion pre-computed value for the right portion pre-computed value for the right portion for the right and right portion will say okay the maximum possible length in the right portion after this is actually four which is the pre-computed DP value four which is the pre-computed DP value four which is the pre-computed DP value so he will return a four but make sure while you are attaching the string you had to make sure that your correctors should not overlap so you can only include the strings from here which don't have a d e and f because this is the string having maximum possible length in this right part which your DP will store now in this left part which is okay because has how a pre-computation work like as uh how a pre-computation work like as uh how a pre-computation work like as uh how our top down TP works you will actually be landing onto this portion and you will use the pre-computed value and you will use the pre-computed value and you will use the pre-computed value of the right portion and right portion will say Okay maximum length is four and the string is a EF so you can only take the string from here which is actually not having a ADF which is for sure you are going in a greedy way so ultimately the obvious counter example is that I had let's say a DFG which for sure I cannot take because if I take it then ADF which was the maximum in the right side I could not have taken that so I will have to pair it with ABC now one thing we have to know no matter what I will have to store all possible combinations in this portion and then try it with all of the possible combinations in the left which means ultimately no matter what again many people will say okay I have written a DP code but still bro your DP code will always have to keep all Poss combinations that is the reason your DP is not actually a DP it's memorizing what like so that's the reason there's no technically again you can go and write that DP code and many people just write for showcase but that will not optimize your code because you will have to still store all possible combinations now when this thing is on side then we know okay we can simply apply recursion is simple take not take but while taking make sure that you are not repeating obviously your character should not repeat so I'll simply have this array of Str which I pass and I start off from the index zero initially my string is empty now this string empty which means my final string my resultant string again because of this recursion itself you can actually like in the interviewer like interviewer ask you okay I don't want the actual string I sorry I don't want the length I want the actual string so you can also get the actual string itself rather than the length so that's a use case of this code also that you can also get the actual string which is having maximum length Okay cool no worries I'll have to start from the index Z and go on to all the indexes so it's a simple recursive case now we'll go on to the actual recursive case and then we'll go on to the base case so firstly if I have let's say if I go back and I'll show you so I have initially these all strings right these all strings these this initially my result is empty as I showed you initially my result is empty I'm passing and I'm trying to build the maximum answer so you will see okay initially whatsoever is the best result so far just get that and I have try to maximize it maximize do two options take it or skip it now when I say take it I will say Okay current result whatsoever I have buil so far if I am taking the ith string add that string in my like result and I will get a new string bigger string and then pass it and then say okay try for I +1 and it and then say okay try for I +1 and it and then say okay try for I +1 and then this is the new string which you are passing if I skip it which means I will just skip this Ari okay I just simply pass the actual result itself and go on to my next Index this is that take not take and whosoever give me maximum I have to return that maximum that is a simple recursive case now coming on to base case again remember if at any point of time I encounter a string which is having duplicate I have to sorry I have to return either you can return here itself either like either you can have a check here itself like here while actually adding your while adding your AR ofi in your string you can have a check at this location or you can have a check after adding if you figure out later on return it so now when I'm going back now here I did okay I added that without even having like blindly seeing that I added that but when I'm again coming I'll check if my result has some duplicate correctors bro sorry bro return it I don't I cannot have that so he will just simply check okay the result set will simply this is the actual string let's say if I had a b c so my result set will contain a BC so I just compare okay the length of my result and the length of my result set length is three result length is four what it means that result is actually a like a string this is actually a set this will only have unique values so I'm saying I have three unique values here saying okay I have four values so for sure one value is duplicate so I'll just say if the set sizes are not same I have a duplicate value again there are multiple ways to compare you can also apply a for Loop which is as same as this one also so ultimately if this is not matching which means you are have duplicate values while if let's say it would have been only a so the size would have been three only so it would have matched so there's no duplicate so if it is duplicate simply return a zero I cannot afford that and ver like for short normal base cases you are starting from the index zero what if you reach the end index so if I just reach the end index simply return whatsoever is the result size which you have got so far simply return that because it's a correct result without any duplicates so this line should come after this line for sure because I have to make sure I'm not returning something which is having duplicates okay great that's a simple recursion now let's see the time complexity of this so if I just have a look so I'll just show you that you will see that okay one thing is for sure in a simple recursion what happens um you will actually be going on to all the cases now we saw that okay we have n strings and different strings and we for each we have two options so for sure it is 2^ n so my options so for sure it is 2^ n so my options so for sure it is 2^ n so my recursive flop will actually go to 2 power n times which is okay great obvious um so this will go to a 2 N times but in this you will see there are few things which can actually increase the complexity which means okay if it's a recursion it's a tree right the depth of the tree will be nothing but depending upon I which means okay he'll try for this ey this eye as you can see above also okay this is the first index trying for the second index time for the third index of the string like of the word like you have let's say this specific input as this AR so okay first index of this AR next index and this is a depth of my entire uh tree which I'm making so for sure at every depth I am trying to replicate or making a new string again and again so what will happen in this is that at this location if I have a corrector so okay corrector will be made now he will go down and corrector CH a r a new string okay this is a string which was cha will be made then when he will go down he will make a new string CH a r because he know one thing okay I will have to maintain the chha because what if I skip this R then I will have to add a act later on so he will be skipping as you can see he just copied this entire thing here which means this was a cha he will again how a DFS works it will go in the entire depth so right now he's not going here but he's making a new copy every time cha a new copy is CH a r then a new copy is CH A R A let's say if it is actually made but yeah it's not made but yeah let's if it would have been made so a new copy so now what will happen because of this new copy is that okay right now when he will go back he don't have to return anything he will just go back now while going back he has stored this value in the memory CH a r so now he can easily go on to the right side and he can easily try for the next one which means ers so you saw that okay at every depth I have to store the copy of the string that is the reason at every depth my depth is n like my levels my like in time my all the levels are n and for every depth I'm actually making a copy of the string so for sure my at every level which means n is the level for me and for every level I'm actually making this copy of the string so one thing is for sure that I will have to add this compressor which is n into W in my actual string so this n into W will actually be added like apart from your this um complexity of your recursion cell which is 2 power n you will have to do n into W thus you will see that again this n w is very small because n is 16 W is 26 so the multiplication is also a constant number but still it will actually impact not much because the con are very small and the same goes for depth that for every of the depth and depth you will actually be making a new copy of string so it is again NW which you have added so this will be the time complexity and space complexity for you because of the copy which you are making for sure whenever some copies are being made one thing we can obviously do is backtrack which means you will not try to make a new copy every time that is the reason of making a backtrack now what you'll do by backtrack is again backtracking has two use case going onto the previous value again other use cases just avoiding a copy of something what we mean by that is if I am having a cha I will just push again in the same string cha I'm not bring any copy I'll push a I'll push all the characters one by one of this upcoming string let's say the upcoming string is r a let's say upcoming string is r d e let's say rde e so I'll push R then D and then e so my entire push will be just nothing but okay pushing all these characters one by one in this specific string CH now this will become rde the new string again this is the actual Str itself it is not a new string so CH the original string I just pushed elements r d e and then this has become a CH rde again that is the only string now when going back I know okay I added three characters I don't matter what I added three characters r d e i just remove three characters from the end okay I'll remove R like I'll just remove three characters that's it from the end so it will just while going back it will land onto its original state which was a CH and then I can go right side and that is how pack tring simply works okay while going back please revert to the original state itself so as to try the next possibility so I'll do a simple exact same thing it says that now my string is passed as a reference because I'm not making any new copy now and I don't want to make the new copy and the exact same base conditions exact same thing is just that now the upcoming uh index word which I have okay for the a of I for this all the characters I'll simply push back in my this result string so I just pushed back all the characters of my AR ofi in the result string and then I will just pass my result but you remember while going back now this whenever you line when like whenever you write any line below recursion it is while going back now while going back I make sure I have to remove number of characters which I had so I just simply remove again I'm not concerned about what the characters I added I just have to remove all of them whatsoever I added so I on the entire characters itself again and then those number of characters I removed from the result itself and then I will be very good to try on the next possible case that is how a simple recursion will work with this you saw that it will actually and only go to the actual recursive cases which is nothing but my exponential uh my power n which is this exact same time and this entire operation will again you might say uh Aran that is O of like word size which operation which you are doing on every character is but yeah that you will for sure have to do because you will have to for short try so you can technically say Okay o of w is being added at every call which means that word size which actually which is actually 26 if you remember and go back word size is a 26 so a kind of in the worst case a word size which means every character is being copied again and again so there can be o of w Edition o of w extra time added to it that is okay that is again obvious but yeah the space will be over depth only but you can also say okay every depth like at every depth of O of n my actually word size might increase so in the worst case it can be o of n to W that's also completely okay but you will still see that bya backt track the time complexity has reduced now comes the most interesting part can we reduce it more because you saw that the main weightage or basically the main addition of time complexity was earlier it was because of the copy of strings being made okay we reduced and we don't make any copies so far like we don't make any copies now but string but still the string itself which is being compared with other string so this string itself is actually taking the time on every iteration which means on every time like I have to copy this entire string and then pass it and then compare it and all that stuff this entire comparison of string actually happens and this entire comparison of string will actually take the string length time so and this is actually o of n w so you saw okay um my string comparison will taking time my string comparison is taking time my string copying is taking time and why in the first place I need that okay I need that because I will have to check okay I can add ABC with DF but I cannot add ABC with ADF because a is repeating so for sure string comparison will be needed if the string comparison is needed and technically I have to just compare the string and as I just have to compare okay if some character is matching or not in these two although comparison will be just 26 size which is actually constant comparison nothing much on that side but yeah still if I am comparing something and uh again this actually will bound to O of w only because you can have worse case 26 characters now coming on back that you will have just 26 comparison but still it's a constant increase in time can we reduce that also so yeah we can how if we see the constraints it's a very small number now if I ask you that can you just convert this entire string of L 26 to just one integer itself and then the integer operation will be nothing but just comparison so what I did was okay I will use bit manipulation to actually uh utilize this comparing because I'm just comparing two strings that is a main operation which I am taking and I will have to add a string in other string that's the time which I taking right now and basically it is more or less nothing but comparison or adding of string to other string but I realize that my strings are very less size I can use my bits to represent my strings which means a b c I'll represent as a number as seven so ABCs string I represent as a number as seven how we will see that so we will actually use bit manipulation now uh for sure bit manipulation plus region and bit manipulation back tracking both will be same because now I'm not even handling strings altogether I'll actually use my actual bits which means actual numbers I'll be using rather than my strings so your uh recursion we increase like we decrease the complexity by using back tring because we are actually modifying because we actually not making a copy of the string but now I'm saying I not even make the string in the first place now coming on back that how to actually convert the strings to integers is nothing but we know we have 26 at Max 26 alphabets so you can assign all the alphabets just one bit okay I'll say that a will be the zero bit B will be the first bit C second and so on and so forth so if I am saying that okay if I have to mark that currently my one of these strings is actually a c d g if my current string is a c d g now to represent this string I will actually be marking okay zero bit which means corresponding to a Mark that bit as one corresponding to C Mark that bit as one corresponding to D mark that bit as one corresponding to g mark that bit as one and with this I will get a g DCA basically I can you can imagine this as any combination it's just that I'm concerned only about the frequency for me the entire sequence doesn't matter I'm concerned only with the frequency that's it because again because I just want to find the length if you had to find the string itself then there's a different case then you have to apply back tracking as the best option but right now you only concerned about the length so this is the best option that okay if even if it chumbles you are only concerned about the actual what's the character if the C is there or not so what I'll do is I'll take the existing example I'll convert all of them to actually numbers how okay for the zero bit which means for the a it is at the zero bit have a one for a B have a one for a c have a one for a d okay all of them will actually be a zero D will be a one for a c okay it will be one so I'm just converting all of them to actually my integers and again this is a integer value which is seven this is integer value which is 1 2 4 8 12 so this is how you can convert all this entire thing as just an integer but for sure if you have something that's say a FG now while you're converting that to an integer so you'll just Mark the first bit as one you will Mark the first bit as one now again next a comes in which is so you will see okay you already had a one and you are about to mark it as a one so for sure this string this specific string no matter whomsoever it pairs with it will actually be making the answer as false basically it will never actually contribute in the answer why because it is already giving me duplicate which I never wanted so he's giving me duplicate which I never wanted so for sure remove him at the first place itself okay I'll simply remove him again his approach also is super helpful in pruning as in like although in lead Cod and all the stuff you will just see okay it's actually useful in pruning only but it's main use cases reducing the complexity of comparison and also it is very helpful in pruning means okay if you have a recursion tree let's say if you have not watched the 100 days 100 placement uh Series in that I have discussed pruning but in like in one of the problems of backtracking itself uh which was uh generate parenthesis because in that we will not generate a specific part of the tree which is actually called pruning in that what we will do is okay if we know this is the entire tree which we will have I will cut some branches that he will never go down in these branch in these Branch I'll cut these branches itself so with this what will happen is it will never go and try for this comparison so my entire tree branch will actually get reduced in the first place itself now I'll convert this also to actually integer and that's how I can actually do it so if I just show you that how this comparison is done you'll go on to all the characters you'll go on again you will make a character bit set this is a character bit which is actually an integer I showed you now you'll go to all the characters let say BDF now as you go to all the characters you will have to make a mask so initially my entire thing is a 0 a number zero is actually a 0 32 bits right okay again remember it is 32 bits an integer is 32 bits okay that is great we have 32 bits now as soon as I encounter first C which is actually a b so I will have to make sure okay B is there right so 0 Let's put it like this 0 so I need to know that okay A B C so I need to know okay first I need to know first index first bit I have to mark it as a one so I will make a mask as 1 0 and so on so forth and then I'll do a all operation so what will happen with this or again you can just have a quick check and then you can do or operation again or operation and operation if you don't have an any overlap both are same so okay I can do or operation or and operation again if you don't have an overlap what I mean by overlap is 1 + 1 overlap what I mean by overlap is 1 + 1 overlap what I mean by overlap is 1 + 1 + 1 is actually a 01 but one or 1 is 1 + 1 is actually a 01 but one or 1 is 1 + 1 is actually a 01 but one or 1 is actually a one so if I say one or zero this is or sign a straight D it's actually a one 1 + 1 one or uh it's actually a one 1 + 1 one or uh it's actually a one 1 + 1 one or uh 1 + 0 again it's a one so when you don't 1 + 0 again it's a one so when you don't 1 + 0 again it's a one so when you don't have any overlapping bits R and an operation both are same remember that fact but still here we can also apply R operation but you remembered we have to Quick have we need to have a quick check if some bit is not repeating so firstly before even applying and operation or an or operation I will do a quick check I'll do an and operation and check if that specific bit was one or not if this and operation comes as a nonzero value which means okay if this is a one so he will come one and remain all will for sure come as zero because your M have all of them as zero and you are doing and operation so for sure if this is a non- zero which means I have a this is a non- zero which means I have a this is a non- zero which means I have a repeating character which was already set so okay if some if the character bit which means this character bit set and The Mask which you have made this is a mask this is a character bit set if the and operation is some non-zero value simply operation is some non-zero value simply operation is some non-zero value simply WR because you have found a string which is actually having dupc duplicate characters in itself only okay great no worries but if not then you can simply do an all operation or an and operation both same again I told you how now so if you remember it was actually a zero so he will actually become a one now my new character set is actually a this thing this is the my new character set character bit set but you remember I have just passed one of the characters B I have to next pass a so I'll pass my a I'll simply make a mask okay sorry I this was a one and this was a zero I'll simply make a mask which is nothing but one and all of them are zero then all of them are zero let's it is this now I'll simply do a all operation again firstly I have a quick check but yeah if I do all operation I'll make a one and all of them are zero again this is my new character bit set now again a is done do a f so I'll make a mask of f which is one and then some zeros here so I again do a and operation which means sorry or operation or a plus operation both of them are same so I will get a 1 0 whatsoever was there 0 1 and that will be actually representing my this specific string as an integer again if I get this is actually all the work is done being done on an integer so you will see one left shift C minus a c was actually in the first place your first character was B so your first critor was B so B minus a is nothing but a one so you are left shifting one time if I say okay if I have a 0 and a one so this is okay one left shifted zero times if I do a left shift of one time so he will become like this if I do a left shift of one two times he will become like this okay this is how my left shift works now this is how you know okay how your strings will be converted to an integer now but do you remember one thing what you wanted to know the maximum length which means that you will also have to store the length now if you have any string let's say if I have this string I want to know the length of the string I know any character is not repeating so all of the characters are unique right so I know that if I have some bits as one so for sure they are contributing uniquely in the answer which means I will have a one time B one time and f one time so one way is that okay in this integer I can just count the number of a set bits which are actually three that will give me the length of the string but if the integer is n counting the set bits take log into the base two time because you just have to go into all the bits of that integer has 32 bits so counting the bits in an integer of length like of 32 size like an INT will actually be 32 in the worst case which means okay to count the set bits to just get to know the length itself of this specific string I'm using a login operation that is very less but still my entire constraints were actually 16 26 which are actually less than 32 so for me log and is also a contributing answer so I should actually remove this also how I will remove this I will maintain I how I maintaining okay I have a b and F I will also par maintain if what is the length how and where again I just have one integer I cannot use multiple again I can use but yeah that will increase the complexity but yeah I use only one integer to populate this value also in the same integer how let's see that is so interesting no yeah so how what we will do is okay we know that we will have at Max 26 unique characters so this length will actually be at Max 26 right so and we know we remembered we have 32 bits so for sure six bits are still remaining for us to utilize so what I will do is I will get this length it is a three length is three I will left again length is three is represented as 1 one in binary form I left shift this number three 26 times so that it never overlaps with the first 26 characters of the English alphabets and then I will populate this value after 26 bits so now the starting 26 bits will represent the characters and the frequencies and the remaining six bits and first in first case you will remember okay the length can be 26 which is actually nothing but um uh 20 32 which means like Which is less than 32 and 32 is five bits so it is less than five bits or basically you can say five bits at Ma Max which we can for short store because we have six bits remaining so this is how in like in how so like that is so interesting you know so again that is like this mesmerizes me so what we will do is again if you tell this who interview no I'll I swear I'll hire you at the first place I'll hire you cool now we are storing okay in the starting 2 bits we are actually Shoring the frequency and the last bits six bits we actually Shoring the length and the same way we'll do for all the characters okay for him I'll Reserve again no matter what I'll reserve the starting bits for my characters only and the last bits for my length okay you will see the length was actually a two so I represented a two here 1 zero uh here the length is three so I just put one now in the same integer I have both the uh the string with the individual frequencies which means okay the string with the actual contribution to the answer and also their length now just nothing but again while comparing you will have to bring back these numbers which means if I want to compare these two strings I will have to bifurcate which means I will have to get this entire stuff out which mean I have to get this entire blue part out from this and the uh purple part out I have to get this part out which is actually a work but yeah it's worth it now uh let's quickly have a look that how we actually be making this entire string okay from this string I how I will make this number I'll simply as I showed you previously also to make this starting blue part which is the first part we will simply use the same operation as we saw above also that we go to all the characters we'll make a mask of all the let's say if I get a c so I'll make a mask as 0 1 and all other zeros which means one left shifted two times what is two nothing but C which is a character minus a again C is the actual color here while C is the iterator here which means Okay C can be a b c and so on so forth it's just a variable but right now I'm seeing C is actually act actual C here it can be a d which is D minus a is actually nothing but a three same way um I treat on all the characters I'll make a mask first if the mask and my actual this current this character bit have any bit as like overlapping which means any bit is actually already set then I'll simply have to return if not then I'll simply do a or n plus operation just simply adding the bits but I also remember I have to Al get the length I'll firstly get the length from my nothing but from my input which is the specific word which I'm trying to get the mask off or get the int off and then I will have okay I'll just left shift this length to length 26 times I will get this new mask which is nothing but 0 like which is nothing but 26 times and then this is the length which is again 0 so this is the new mask of the length so I'll just get the length bit and then I can simply add this or you can also do the or operation here again or and this operation or which is bitwise or Plus bitwise or plus both are same in this case because we are not having any overlapping bits so remember this fact but yeah that can be confusing if you are relying on this entirety now have a quick check that how the comparison will look like that let's say if I have this as a specific result now if you remembered that in the entire recursion tree we will have some result and then we will be comparing with the I index a simple comparison how it was done so I know that okay I've converted this actual result which means this actual string to actually a result which is integer but I know the starting 26 bits represent the actual characters while the last six bits represent my length so I will make sure to actually compare if the characters are same or not I will have to compare the starting 26 bits only again I cannot it trade on those 26 bits then still it will actually land to the same condition that we are traing on those 26 bits I cannot do that so what I'll do is I will get this 26 bits out which means I will make a mask how I will make a one I just see I now ultimate my main aim or my m is to get these 26 bits out from this number without even it trating on them all of them again and again so what I will do is I will make a mask which is one11 all the stuff and then remaining all of them will be zero what this happen with what will happen with this is if I do and operation so for sure all of them in this left part will become a zero and all of them in this part will become whatsoever was in the input so if I make a mask of one left sh 26 which means one left sh 26 times if I do a minus one then again this is 0o which is 26 six times if I do a minus one with him he will go zero and all of them will actually become a one of length 26 so we will have a one of length 26 now with this a one mask of length 26 I will be doing an and operation so as to get only the starting 26 values of the input so I'll get only the St 2 values of the input and the remaining values will actually be a zero so this is my original result ABC but now you also will repeat the same process for this specific uh and you remember you have firstly did a pre-computation and converted all these pre-computation and converted all these pre-computation and converted all these two and you converted all these to an integer and you just stored that in your AR as bits let's say you name the vector as AR as bits and you stored that in a vector let's say for him the value is um you will see 1 2 1 uh it is 1 2 4 so it is actually 7 uh plus this values which is 2 20 and something so this is okay like you showed an integer okay this integer value this are integer values now you will get this integer value from your AR of as bits again from this also you will have to extract out the last 26 characters you will make a mask for the last 2 me one and then you'll do a and of these bits again this is the reason bit manipulation is not easy for everyone if you are not familiar with and operation mask and stuff it will be hard and that's the first because I was not about to teach you these methods but I thought that why you should not know the most OP one approach you should know because no one has like no one has taught this yeah why cool going on back um so firstly we'll have again if you're liking it then please pass the like baby cool uh now um so we will make this mask 111 we will have this ARS inputs but we want to extract only the last 26 bits we will do and operation we'll get the last 26 bit at itself now to know if now to know okay we have got this original result now we are about to compare with this specific I need to know if they have same character or not the same thing which we did here which we did right here also if you remembered I'll do and go back if you remember to go and check if something has same bits or not you just simply do a and operation with the with them so here I want to know if this value if this specific bit was set or not basically originally was there or not I did a and operation if the and operation gives me a one value which means a nonzero value again this is not a one this is actually value two in integer so if this gives you a nonzero value which means for sure you had repeating correctors so same way what I will do here is I know my abc is represented as 0111 so I know I have 00111 which is ABC and then this mask is nothing but 1 0 and 0 1 which is actually nothing but my ABF so you will see if I do a sorry it is ABF yeah so if I do and operation this everything will become a zero so you saw that the contribution of f became a zero the contribution of C became a zero but b and a both are repeating so both contributed something so I can only attach two strings if they don't have duplicate values so what I will do instead is I will just do a and operation if this value is zero I am good I can add this incoming correct incoming index which means the specific string I can add in my original string which was this ABC at the first place I can add that but if it is not you can only skip that so if the and operation gives me a zero only then I should try adding that and when I say add that simply again I'm concerned about the length so simply firstly add both of them again here also the r operation will work right or operation will work here or operation will not work here and will work because you're adding to lengths you converted okay you got the length which is two you got the length which is three now you are adding the length physically adding the length now the new length will actually become five and then you converted that to Binary form and then you placed it so here the r will not work here the or will work this is the reason I told you the implementation of basically how the r and changes now uh here because you know here also you know or and both will because these new characters and old characters we made sure that they don't have any duplicate characters only then I am actually adding them so what will happen now for this case it will actually not be attached but if I take the other example let's say if I take my other string um let's take the other string let's take this string so we have a CD we have a BF so if I convert the CD I'll grab the only characters last 26 characters I'll grab them as a bits okay that is a number 1 2 4 8 which is 12 and this is the length which actually number two which is nothing but as a one zero in bits form so this will be a one Zer number is two this will be 1 0 which that number is 12 and the same way I'll convert this BF okay nothing but it is saying some number let's say the new characters it is 1 0 1 again integer value you will get to find out and here is the new length which is nothing but a one integ value is three now I know that my final answer I will have to get all these correctors so I'll just do or operation which means 1 0 and I will have a 1 0 and 1 right so I'll simply get a 1 0 1 which represents I have a B I have a c I have a d I have a f and you will see I have a B I have a c I have a d I have a f and that's how I can simply represent it and again the values which means the length it is nothing but two and three adding that I'll get a new length is five because for sure every character was unique so I'm just simply adding the length my new length is five but make sure that the characters should again occupy 26 bits and the final length which means the length which you have made should go in the last six bits so left shift the new length which is five by 26 so as to move that to left Remain the space remaining starting space of 26 characters should be of characters and length should be the last six bits thus you can simply get the new result thus this is the only modification which you need to do in the recursion in the recursive code first is precomputation and next is using that precomputed values so first you will see that I will convert my all so again you will have a quick um doubt on why we are using AR of bit site bit like bit set um so basically we are using unordered set of AR of bit set now you will have a question that why un set why not vector and stuff and why we converting Vector but we will solve all that stuff so firstly we are just getting AR of bit set and this it is nothing but an unordered set so it will store for all these strings they corresponding integer values and when I say string I am storing starting characters 26 characters as the actual frequencies which means the actual occurrences of the characters and the last bits which are six bits we actually storing the length now uh this is the function word to bit set which will convert this specific bird and push it obv Bally insert that into my AR of bit set okay how this function will work this function as I showed you already previously it will go on and make this character bit set right which is keeping the occurrences of all the characters go on to all the characters of that specific word let's say the word here is just ABC so he will actually try to make firstly he will have to verify if that is already not there in The Mask if not then he will actually make a actual character bit set will actually become a 111 and all the bits are zero but you remember we also have to add the length in the next 26 characters which means after skipping the starting 2 characters I will have a length bits length bit set also which is nothing but a length mask which is which will be after 26 characters which means I will have a length let's say the length is here three I will left shift that 26 times I will get a one and 26 zeros and then I will do a r operation or basically a plus operation anything I'll get a new mask I'll get a new value which will be nothing but I'll insert that in my AR of bit set I am passing this by address right okay I will insert so basically it's nothing but corresponding to this specific word I got its integer value which is having occurrence and um occurrence and length combined in one integer and pushed it into my ARR bit set but it might happen firstly I will never be storing if something is like a b c this will never come inside my AR bit set right okay that will never come but what could have happened is that if I had used Vector here then something as ABC and if ABC is still repeating in my actual ARR if in AR I have ABC twice then this if I would have used a vector then I would have made his integer let's say his integer value will be X and his integer value will also be X so my X would have been twice and there is no point whatsoever that you can have two duplicate values or two duplicate strings so a two duplicate strings entirely is not even use case for us so here also we just use a unordered set rather than a vector to do again a pruning again there's another pruning which is being Happening Here by avoiding duplicate strings at the first place here we avoided duplicate characters but here they avoiding duplicate strings so I got this in my unordered set then I converted that to a vector and just okay all the values of the unordered set which only will have unique values representing unique strings I will convert that to my AR of as bits which means now it's a vector so as to iterate on the vectors because we have to itate on the words itself I converted them to a integers and that I stor in the vector which is an array now I'll simply call the same recursive function now in the same recursive function just a simple thing that the actual result which you have existing result you will grab out the actual occurrences of the characters and the length and the new incoming I index you will grab out the actual occurrences and the length and then you will try to match it so in the existing result I grab the old characters whatsoever I had by simply saying okay whatsoever uh whatsoever existing result and by simply making a mask of 111 26 times so I will get only the last 26 actual character in my result and I'll same way I'll get the old length which is nothing but okay whatsoever you have the result value let's say if I have the result values one and all are let's say some values some 26 values so I just I want to truncate these values so I'll just do a right shift which means this one will be right shifted 26 times so this all will be truncated down trated down 26 times it will be all trun down and this I'll only get this specific length so I'll got this length now So currently my best possible length is my current own length which whatsoever I have that was the input also the result length now the simple base case um if my I goes beyond then simply return the best length you had possibly here but if not then find the new characters in this ARR AR of as bits of I index I'll find the new characters again the same way we did here same way we will do here now I will actually have to go on to I will actually have to go on and check that okay I trying to attach the I'm trying to attach this new characters in my old characters I'm trying to attach that right so I have to check okay if these should not overlap now for that I'll simply have a check if these don't overlap only then I should add my new characters in my old characters I simply add that and this is the same operation which we did finding the new length finding the new result which will be nothing but old characters plus new characters here also I can apply all operation but this will be new length plus old length and then left shifting 26 times so has to move it back so this will be my length which is in the last six bits again here Plus or both will work but here plus will only work now uh coming on back um coming on back uh we will have the best answer which means maximizing the best answer best and try to solve it for the next index considering the new answer only but no matter what you can have other case which is the not take case which means simply go on to my i+ one with the simply go on to my i+ one with the simply go on to my i+ one with the actual existing result value and then ultimately returning the best possible answer with this your time and space are exactly o of 2 power n but with ex extra pruning at many levels which will actually increase or Bic which will actually reduce your complexity by many times just because of that you for the bigger strings you are pruning a lot and that's how it will be much more efficient but in complexity terms it will actually be like representing this values but it will be much better cool thanks for watching I know that the video is 51 minutes but I want it like this is just a test that's the like I mostly skip in DP problem also I mostly skip um the very much let's say if I'm teaching a DP problem I know that bottom up will not optimize the code but still I skip that bottom of code because I know that people are mostly concerned about okay I should solve the problem that's it no matter what the complexity is no matter what the analysis of the problem is no matter how it is useful for you or not people just want to skip it and that's the reason we have less views because of long video length and again the video will go on around 10:30 which is way too much time and 10:30 which is way too much time and 10:30 which is way too much time and usually the people push the video around uh 600 a.m. or 700 a.m. we will be uh 600 a.m. or 700 a.m. we will be uh 600 a.m. or 700 a.m. we will be pushing around 10:30 a.m. which is pushing around 10:30 a.m. which is pushing around 10:30 a.m. which is actually way a lot so to make this entire notes and stuff it took time which actually will implicate or replicate or basically will actually affect the entire thing video reach um video like uh you know interaction and all that stuff but still I wanted to have this as an example for any of the further bit manipulation recursion and bit or backtracking videos because this was the first problem involving everything so that's the reason I just went into it if this gets good response I'll probably try to discuss every approach in all the videos but going forward I only like I make sure I only discuss the approaches which are actually reducing your complexity cool thanks watch good bye-bye
Maximum Length of a Concatenated String with Unique Characters
largest-1-bordered-square
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[ "un ", "iq ", "ue "\] **Output:** 4 **Explanation:** All the valid concatenations are: - " " - "un " - "iq " - "ue " - "uniq " ( "un " + "iq ") - "ique " ( "iq " + "ue ") Maximum length is 4. **Example 2:** **Input:** arr = \[ "cha ", "r ", "act ", "ers "\] **Output:** 6 **Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers "). **Example 3:** **Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\] **Output:** 26 **Explanation:** The only string in arr has all 26 characters. **Constraints:** * `1 <= arr.length <= 16` * `1 <= arr[i].length <= 26` * `arr[i]` contains only lowercase English letters.
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Array,Dynamic Programming,Matrix
Medium
null
1,926
Hi gas welcome and welcome back to my channel so today's our problem is so what is given to us in this problem statement here we have M * N a here we have M * N a here we have M * N a matrix has been provided the table is fine in which what is yours is empty cells and The wall is here, the dot is representing your imprisals and the world is representing meaning plus is representing the walls, okay, so here is the problem, is the pay here giving you an intense point, okay and what else do you need? If you have to come out of this wall, then from where can you come out? You can come out from this boundary, you can come out from this boundary, that is, you can say this, you can come out through the outer silk. Okay, so this is also your outer cell. But you can't move out from here, why can't you move out because you have been kept here in which direction you can move towards down, you can move towards the left or You can move in one direction if you find a path, that is, if there is a wall, then you cannot move, okay, but you have the possibility that you can move in these four directions. Okay, so here, this is your intense point, so where are you? -Where can you go from here, where are you? -Where can you go from here, where are you? -Where can you go from here, then see which is the nearest, this is yours, so what do you have to do here, you have to find the shortest path here, okay find the number of state. In how many steps will you take to get out? If you come here from here, then you can get out from here, neither will be one step. The answer will be because now you will put steps in it, here you will put one step, then the answer will be, what is the shortest for you? If you want to find it then there will be a van here, okay then you see in this example, you are here, this is your entry point, so where can you get out from here, you can get out from here, now you will say, you can get out from here only. No, because you have to come out from whatever is your entry point. Okay, so you can go out from here, so what will be the answer, you will be here, okay then in the third example, you see what is given here. There are only two cells and you are here there is a wall, so here you cannot go, and in the film you are in, you do not have to get out from there. Okay, so here you cannot get out, otherwise the pay here will be -1. The answer is okay. So I hope you have understood what the -1. The answer is okay. So I hope you have understood what the -1. The answer is okay. So I hope you have understood what the problem is, so thirdly I have taken an example from myself, what do we do and try to understand our problem through this, okay look here I have not taken a dot. It is kept blank that this is your path, you can go through this path, here is the plus, that is your wall, now you cannot go from there, okay, this is your entrance point, this must have been given to you, okay, this is yours at this point, now you have it. There is a possibility to go in which direction, to go in this direction, so now if you go to any of these cells, there will be a van step in a way. You can say, you van level, you cross it, people right suppose, this is your intense point, you can go here, then this has become a level of yours, at this level you can take the van. You can go in van time, okay then look, now you are here, now you are going, you are here, okay, then from here, your direction is in which direction can you go, you can go here. You can go, you can also go down, but now if you come from down, then in this condition you will also have to keep in mind that from where you have already visited, you do not have to visit again, it is okay, isn't it? Here we have to take care of that point or note down the point that we have visited the place where we have visited, is there any visited, if there is a sale, it is a visited sale, we do not have to visit again, okay, so from here you can see everything here. You come here, see, if you came here, there is a wall here there is a wall, so now you can go, what can't you go, otherwise you will come here, okay, you came here, if you came here, then what do you have to do with coming here? If you want to do this, you will have to mark it as widgetized so that you can do it again because from here, which way can you go, it can be towards the left, it can be towards the right, now it can be down, okay so you here. You can also go here, you can also go here, otherwise what will happen here, see here, when you go here, you will go here, then you will know that you are in the outer cell, if you can go out from here, then here How many steps did it take? You can get out in 1 2 3 steps. Okay, now let us see if we were here then in how many steps we could go. From here also the vans come here in one step. Then if in this direction. You come out in step three, look here. Now if you had gone down, you would have come here in one step and then out in step two. So you are coming out in three steps here. The three steps are coming out here too. If you come then you will come out in 1 2 3 step, you will come out from here too, the van will come out in three steps, right, what will happen to you here, sorry, here you will come out in one step, the van will come out in one step, anyway you stay. You have to fine the minimum, right here, what can you do here, what are you observing here, what algorithm can we do here, look here, basically look at us, you will come here, you will cross a level here. You will come to know that you can get out here, so this is your second level, so somewhere this is your best on BFS and what is the minimum distance in the bus, when we have to find it, then we do it on BF. Right, and what should we do here? We have to look at the H level, maybe we should look at some level, at the H level, you can see four ways here, maybe this is your way out, so right here. You will know then why are you here, why next, why digital, right, that's why we do it without any hesitation, by doing BSF, we find the minimum distance from which level we can get out if we have to stay at the level we have come to. Let's go to H note and visit the level, now we know that there is one from where we can exit, then why will we see right here, it is suggested here, look here, if it is not there, if it is here, suggest your intentions. The point would be here, okay, this was your entry point, so what do you do now, you go here, you can go here too, here you cannot go because there is a wall and if you go here, then you have to look at the van level, you can go here. Yes, you can go here also, it is not possible here because there is a wall and you can go here too, but if you go here then look at your intensity, you cannot get out of here either, but as if you come from here, you will We will come to know that you can get out of here, then further note why we will visit the next cell, why will we visit here, if we come to know that we can get out of here, then we will simply stay here as much as we have crossed the level. They will damage the level right so that's why we just do it here okay I hope you have understood now this is how we do it let's see look let's remove that let's see for this there is a dot here Okay, that level is going to be our answer, we have to take care of it and we have to visit this level, so what do we have to do for this, why do we have to do it, okay, what do I have to do, what do we do about it? Which row is the column, so whatever data you insert here in the form of foot will be in the form of foot, okay, so now the suggestion is that what can happen here is that it will be the don column, okay, so now where do you go? Now you can go in the direction, you can go here, you can go this way, so what will this be from R - 1 to column but row will be one less, be from R - 1 to column but row will be one less, be from R - 1 to column but row will be one less, what will happen here is your R will be from row will be C + 1. You can go in this direction, C + 1. You can go in this direction, C + 1. You can go in this direction, then what will happen to you here, R + 1 will be the column, okay, R + 1 will be the column, okay, R + 1 will be the column, okay, this will be the stop here, what will be your mines van, you can do this and also you have to keep this in mind. There should not be a plus, there should not be a wall, there should not be a respect, we will not go, okay, so what will we do, we will see where we can go, we will see here, we will see in this direction, we will see on this R - here, we will see in this direction, we will see on this R - here, we will see in this direction, we will see on this R - C, we will see whether this is a dot, what if this is a dot. So we can go here, we have a level of our own, what will we do here, I will write down, it will be better 0123 012, because it will be better to explain more, the possibility is yours, okay, so now you will have to see if there is any wall, we will check first. Let's take it, okay, if you go here, you will know what will be your, what will be its dimension, what will be your coordinates, what will be your, this is the next column here, so we will know that here is pay plus, here what is pay plus, so What will we do, we will not look at this again, we will look at the other one, okay here, we have looked towards the right, now let us look towards now, when we look up, what will happen to us, what will happen to this, now I will row one less, there will be zero and What will happen to you, 2 will happen, okay, you will see here, it is okay and here you have come one step and you come to know that this is the outer cell, now from here we can go out, so at the same time what will we do which The step is that we will return the level because we have come to know what we have reached in the outer cell. Okay, what we will do here is we will return the level. Okay, so you will know how the outer cell. If you are in the cell, see, this will remain your zero. Look, wherever you are here, this will remain the outer cell, it will remain your zero, otherwise you will understand that you are in the outer cell, they remain here, they are outside here. If you know that your column is also at zero, then you can pass from here, you can pass from there, then what will be your condition that when our daily will be zero, will the column be zero or row? What will happen to us, this will be the last one, okay, and minus van, if n - 1, then we can get out from here also. n - 1, then we can get out from here also. n - 1, then we can get out from here also. Okay, if our M is here, the column is ours, if it is the outer one, then we can get out. So, what is the base condition here? It will be done that here we will see whether our row is zero or our column is not zero or our row is not our N - or our column is not zero or our row is not our N - or our column is not zero or our row is not our N - or our column is not our M - 1. If so, then or our column is not our M - 1. If so, then or our column is not our M - 1. If so, then we will go out from there at the level we have created. What will we do? We will do it okay, so we will do it this way. Okay, so look here for this also, I will see what to do for this. Proper will be fine. 1 2 3 4 0 1 2 3 4 So what will happen to you 2 And 2 will be right its 2 and 2 is ok now where can you go here you can go to its van you can then down what will be the increment you can go to 32 you are okay then where can you go you can its If you can go here too, then what will stop you will be its column three, then if you go here then you will be crying, it will be column van, it will be painful, we can go, this level has reached van, on whom will it become? Level will be made on van, okay, what will we do with all these, first of all we will see what is the dot, what is Han dot, that is, we are out of here, from here, we have a path, from here we can go, so what will we do, insert this here. We will do one and you, we have done it in instinct, then what will we do on 3 and 2, we will see three and you three, where will this tu be, from here we will see, we will get dot, then what will we do on 3, we will insert it here. Okay after that we will see 2 and 3 23 what will be your two and three this will be so here also you know you will insert the dot here okay then we will see 21 we will see this is right sorry get this van either This will be yours, we will insert it, okay, this is done, we will know till one level, we have created one level, now what we have to do is to extract each element from here and see that now let us write the next one. This is your 12, so now where are you from here, where can you go from here, you can go here, you ca n't go here, you can't go here because what is this is your wall and you are not even here. You can go, what you have to do is to plus this dot, okay because you have done this here, it has become your digital, so what to do now, don't do it again, so you will plus this dot, okay it is done. Now this van tu here is yours so you can go to this one in zero tu and 1 in 3 okay so this level its next level will be ready for this so what will be the answer here why I your answer will be zero tu van three and where will you be here will be here now what will he do see where can he come from see here he will look here so here what will happen to this 33 and this what will happen to this here four you will be okay 33 what will do to this So, at this level, it will insert 3-3, today it will level, it will insert 3-3, today it will level, it will insert 3-3, today it will insert 42, otherwise first it will also check, along with this, it will also check whether our new row, new column has come, is it on the boundary, then you will know. This is on the boundary, isn't it, on the boundary, we have reached four, so at that time, what will we do with its level, i.e. the that time, what will we do with its level, i.e. the that time, what will we do with its level, i.e. the second level which we have prepared, we will return it here, second level, you do one for this too. Variables will be kept at the level, keep that in mind, if you are okay, then in this way you can solve the problem. Okay, I hope you have understood this. I will also show you the code. What you have to do here is basically what you have to do. Okay, this will be your column, how much is the total column and what will be yours is how much is the total row. Okay, what we have done is taken in which what we will do is add the parents, both will be of integer type because what we have to insert here is row. Have to do end column, okay, we will insert it in the row first. Okay, we will insert that point at which row and column, its intensity 0 intensity van, we will insert this, okay, after that, what will we do in the table? We will mark the point at which we are, okay, now in whatever direction we will go ahead, what we have to do before that is to mark it as visited and put a plus on it again so that no one can hit it again, okay, so we What will we do with the intense zero intensity van? What will we do with the plus mark here? Okay, now we have made the level zero and here we have taken two vectors, two adels, here we have taken Dr by the name DC, this is actually what you need. It was told that you can go in the direction of the direction. Now look, if Rohan is on the column, if you do 10 plus, then you have to become one. You will do one plus in the row and press zero in the column, then what can you do on this index, then what can Mines van do? Yes, in that you can do plus in the row and now you can do zero in the column, then you can go to zero minus van, meaning what we are doing here, this is what we are doing right here, look here, mines van is doing zero here. If you are doing plus in RC, then what to do here? Today it is this, that is, you are doing zero and you are doing 1 plus, so to take care of this direction, we have created pay add A here because now you will see it separately for you. You will look separately for down, you will look separately for right, you will look separately for left, it is good what we do, let us analyze it, okay what we have done to analyze it, we have taken four directions, okay now we What will we do? For how long will we keep doing this process until our why gets improved? Okay, we will do this, then we will find out the size, what is our size and what level is it, we do the same in BSF, we first find the size and then we Let's also make level plus because now we are getting ready for the next level. If we are doing full step then we have to take care of that also, otherwise the help level will keep becoming plus. Okay, then what do we do? Whatever elements we will do, we will look at them one by one. Okay, after that, what will we do? One element will come out, then we will look at that which will be its first element, that will be its column of the second element. Okay, now what do we have to do? If a particular row or cell is on a row or column, that is, if it is on a cell, then we will see that we can go in four directions, so what we have done here is start from zero and take the loop till four, which is for which. For this, it will be up to 01233 index, otherwise it will be available from here and one J plus will be promised in it, due to which what will happen is that our neuro new column will be available. Okay, so we will check the condition here, first of all, we will check. Will you do it? Neuro aapka Girdhar equals tu zero hai kya new column aapka zero and nuro aapka less than end hain new column aapka lesson m, only then if you go out of the boundary then you need to check what is not there right? So that's why you have to check here, one condition is okay, then you will check whether the new column created is not your plus, that is, there is no wall, if there is a wall, then we will not go in that direction, we will continue, okay second. We will see neuro, new row and new column, okay, then if this condition is not fulfilled, then we will definitely come to this condition, then we will see that the new column created by neuro is not zero, is it N-1? Cry, is it N-1? Cry, is it N-1? Cry, is n't that column a mine van, that is, if you are not on your boundary cell, then you have not gone on the boundary cell, if you have gone, then what should you do now return it to the level. It is okay if this condition is also not fulfilled. If it is your cumin, what will you do with the new column and you will mark it as widgetized i.e. you will do plus on the right, in widgetized i.e. you will do plus on the right, in widgetized i.e. you will do plus on the right, in this way it will be yours, if the level has been attended here then your level answer will come and you have not got it anywhere else. So if you return the mines van finally, then you have to go in the mines van right because if it is not returned even once then the mines will be final. Okay, then how much will be the complacency of this problem. Look what are you doing here now, visiting like this. You are right in a way, so what can happen to the watch that if you have to visit all the cells, then your time here will be less luxury. M*M's is fine and its space M*M's is fine and its space M*M's is fine and its space complexity will be your oil because why we have mentioned here. I have done it ok I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
Nearest Exit from Entrance in Maze
products-price-for-each-store
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at. In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit. Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_. **Example 1:** **Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\] **Output:** 1 **Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\]. Initially, you are at the entrance cell \[1,2\]. - You can reach \[1,0\] by moving 2 steps left. - You can reach \[0,2\] by moving 1 step up. It is impossible to reach \[2,3\] from the entrance. Thus, the nearest exit is \[0,2\], which is 1 step away. **Example 2:** **Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\] **Output:** 2 **Explanation:** There is 1 exit in this maze at \[1,2\]. \[1,0\] does not count as an exit since it is the entrance cell. Initially, you are at the entrance cell \[1,0\]. - You can reach \[1,2\] by moving 2 steps right. Thus, the nearest exit is \[1,2\], which is 2 steps away. **Example 3:** **Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\] **Output:** -1 **Explanation:** There are no exits in this maze. **Constraints:** * `maze.length == m` * `maze[i].length == n` * `1 <= m, n <= 100` * `maze[i][j]` is either `'.'` or `'+'`. * `entrance.length == 2` * `0 <= entrancerow < m` * `0 <= entrancecol < n` * `entrance` will always be an empty cell.
null
Database
Easy
1948
733
welcome back to uncle Jess today's question is leak code 733 flood fill so an image is represented by an M by n integer grid image where image RJ represents the pixel value of the image you're also given three integers srsc and color you should perform a flood fill on the image starting from the pixel image srsc to perform a flood fill consider the starting pixel plus any pixels connected for directionally to the starting pixel of the same color as the starting pixel plus any pixels connected four directionally to those pixels also with the same color and so on replace the color of all the aforementioned pixels with color return the modified image after performing the flood fill okay so there's a lot to take in from the initial statement so essentially what we have to do is we have a starting point this one in the center is our starting point and it's represented as an image where the row is one and the source is one and what we need to do is wherever we find a one we update it to two as you can see we've updated it to two here and then we move to its four directionally connected pixels so the pixel above the pixel to the right the pixel below and the pixel to the left we check those to see if they're the same as this starting pixel this one and we update those to two so we'll update this value to two and this value to two zeros can stay the same and then we'll perform the same operation on this one and we'll end up with something like this so I think the tricky part of this question is just breaking down the initial statement into its own sub problems and what we'll do is we'll go through that in this walkthrough so let's run through this and see how it works out so we update this value to 2 because it's equal to a one we move to its four adjacent values so up right down in the left let's say we went right at this point we're at zero we need to make the check if this is equal to the original of one it's not so we return from this we don't carry out the search on this the recursive call and return back to the original pixel let's say we go down this again is zero so we return from this we go left this is equal to one great so we have found a pixel that is equal to the original we can update this to two and we can recurse let's say we recursed right we go back to the original pixel and this is equal to two now so what's going to happen at this point we're going to create an infinite that we'll have to make some kind of additional check to see whether the image at source row and column if that is equal to color so if it's equal to two then again we'll just return from this because there's nothing else we need to do really right it's been updated to the value of 2 which is the color that we're trying to change to so we can just return from this let's say we go down we have a one here great we can update this to two and we can recurse in these four directions now let's say we go to zero we can't go anywhere from this because zero doesn't equal the original value of one so there's no updating of this pixel so we go back we go down this is outside the images parameter right so this will be out of bound and the same with going left so we need to make a check for that so we have rows and columns so if a row is less than zero or rho is greater than image dot length minus one then it's out of bound we have columns as well so if a column is less than zero or a column is greater than image at zero dot length minus one because remember this board is M times n so the column could be greater or less than the row so we need to check at zero then it's out of bound so these two are out of bounds they're a no-go so we exit this so we've currently no-go so we exit this so we've currently no-go so we exit this so we've currently checked the right side below and now if we go left here this is going to be out of bound so the only extra recursive call we can make at this pixel is going above we're at one great we can update this to two we go up left down right we can't go up we can't go down we don't go back because it's equal to two so we can only go right we update this to two we recurse in all four directions we don't go back because it's equal to two we don't go down because it's equal to two up is out of bound so the only way we can go is to one here we update this to two we recurse we don't recurse this way because we've already visited this we don't recurse down because it's equal to zero right is out of bound up is out to bound so we can exit this recursive call and just return the image to the previous recursive call in this recursive call we've checked all four directions so again we can return to the previous recursive call same with this one we've checked all potential directions so we return to the previous call same with this one return and now we're at the initial recursive call here we can just return the image so time complexity for this one is going to be o m times n because we have to Loop through every position within the board and space is also going to be om times n okay so let's start off by defining the original pixel that we're on so const original is going to equal image and Source row Source column now because we're using recursion we'll create a function for this we're going to pass an image Source row Source column and then we're going to call this and return its value so firstly we need to check the boundaries so if Sr is less than zero where Sr is greater than image.length minus one than image.length minus one than image.length minus one or C is less than zero or SC is greater than image at zero dot length minus one we'll also need to make a check to see whether the current pixel we're on doesn't equal the original value of one foreign C doesn't equal original and we'll also need to make another check to see whether Imager srsc if the pixel is equal to the color so if it's already equal to two as in example one then we can just return the image right because there's no need to carry out the recursive call on this pixel then we can update the pixel to the color and then we need to recurse in four different directions so up down left and right so it's called the recursive function again and we need to update the row so Plus One will go down minus one will go up and also the column so Plus One will go right minus one will go left and then finally we need to return something from this so we'll return the image okay let's give that a go submit it and there you go
Flood Fill
flood-fill
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image. You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`. To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`. Return _the modified image after performing the flood fill_. **Example 1:** **Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2 **Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\] **Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. **Example 2:** **Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0 **Output:** \[\[0,0,0\],\[0,0,0\]\] **Explanation:** The starting pixel is already colored 0, so no changes are made to the image. **Constraints:** * `m == image.length` * `n == image[i].length` * `1 <= m, n <= 50` * `0 <= image[i][j], color < 216` * `0 <= sr < m` * `0 <= sc < n`
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
463
83
hello everyone welcome back to everything swift today we'll be tackling a little question 83 titled remove duplicates from sorted list we are given a linked list type list node here and we are supposed to return one as well whereby the return version is basically non-duplicated uh notes within the non-duplicated uh notes within the non-duplicated uh notes within the linked list so i think the example here is pretty much straightforward we are given a linked list basically of type list node here stick right here which is represented in this parameter here and basically we're supposed to remove the duplicate and in this case in this example here which is 1 so it becomes uh the return output is one and two because one is the duplicate right so seems simple enough to uh to know what we are supposed to do uh the question is just like how we're supposed to do it right so uh in this uh version of uh linked list it's basically called a singly linked list which means like the only direction is basically uh next like we don't know anything previously right so the other version which is like doubly linked list which means we can either know next and also the previous so that is doubly but for this case we only have a singly linked list which is just uh going on to the next right so uh if we think this through uh we need the way to compare the numbers that is a given right like we need a way to know whether there's a duplicate and to know that we are basically going to take like using this example we're going to take the first number for example in this case first node and compare it to the next node right and then we're supposed to find out if they are basically the value of the node is it matching if it is we're supposed to break the link between the first node and the subsequent node the duplicated node and point it to the next uh node essentially right so this uh question is pretty good i would say because it serves as a foundation in terms of like how do we want to delete an item uh in their linked list in a singly linked list basically and when we do uh for the question uh any related link list question this pattern is quite uh common so it's pretty useful to try and understand this question and try and recognize the pattern so uh the strategy here is basically like we have to hold the value of the first note and compare it with the second note if it is the same we basically going to break the link by changing the next to the next of this pointer to here right so that we are basically not removing it like deleting or anything we're just changing the pointer from uh this particular node to the next one right so i think the code is pretty much simple and that will probably clarify my explanation much better so i'm just going to jump straight into the code let's talk through about that okay new i'm going to return new so essentially if there's no link list to begin with then pretty much there's nothing to check so i'm just doing this for performance reason in the real world uh this is probably helpful but in the world of lead code unless specify is probably redundant but it's just a habit of mine so okay so now what we need to do is basically we need to somehow get this reference right and then we're going to compare it with the next node and then we're going to traverse through the list node so the first thing we're going to do is get the reference so i'm going to create a variable here called current and point it to the hit here so what we're going to do now is we have to traverse through the entire linked list until we ran out of the nodes so how we're going to do that is basically just check if current equals to male or not so let's say uh the current is not new we basically once want to compare the current node's value with the next known value right so we basically just store it in a constant called next node current dot next so the only reason why i can confidently unfold some rep here is because i know within this while loop the current is never going to be new so i'm just force unwrapping here and then what we're going to do now is basically compare the current value and the next node value right the next node dot now which is equals to current dot l right so what happens now so now in this if condition we have found a duplicated number so we need to break the link of the current node to the next node right so current dot next equals to next node dot next essentially right else so let's say if this number one and then the next number is two so it's not duplicate right so basically we need to move our current node to the next node so that we can keep comparing them throughout the entire uh linked list chain right so we are at this point here and then now let's say we have compared with this specific node that is not the same imagine this number was two so basically uh we don't have to break the link we just need to move forward to this linked list and then we can compare this node with the subsequent next node and then we can see whether we need to break the link or not all right so to do that we just have to set that we just have to set that we just have to set equals to equals to equals to so basically from this node move forward to the next one and once that operation is done once we traverse the entire linked list basically we have uh removed the duplicated uh node and then what we need to do is just return hey which is uh the modified version of the link list right so i'm just gonna go ahead and run it first and just to make sure that i got it right and looks good i'm going to submit this hopefully yup so that's the answer for this question but just to recap here the most important thing is uh try to recognize this pattern here like current dot next equals to next dot uh next node.next or you can also write uh next node.next or you can also write uh next node.next or you can also write it as like current. if uh that makes it current. if uh that makes it current. if uh that makes it easier for you to understand but essentially this pattern here this particular line here is very important for us to recognize in the linked list kind of like many questions sort of like use this kind of format in some way so this pattern is quite useful for you guys to recognize uh to break the link in uh linked list so in this case using this example here what happens is the next node is basically one and current is basically one so we found a duplicate basically the current of this next so this particular line is basically what we are saying here in this line 21 we're taking this uh pointer pointing it to this number two which is the current x dot next which is uh next and then next again right so we're just breaking this link here and pointing it to two so yeah uh i hope this video is pretty helpful for you guys if you do please feel free to like and subscribe and uh please feel free to share this channel i'm trying to grow this channel as well and i'm gonna put more videos like this out in the future so thanks for your time take care and bye
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
1,551
hello everyone and welcome back to another lead code video solution so today we're going to be taking a look at the lead code question minimum operations to make an area equal all right so for solving this question there's actually a really simple pattern and what i'm going to do is i'll try to show you how we can come across and identify that pattern and use it to solve our question so let's start off by reading what the question is actually asking for all right so we're going to be given an array of length n where area i is equal to 2 into i plus 1. so for example the fifth index would have a value of 5 into 2 plus 1 which is 11. okay and i is going to be in the range of i is greater than or equal to 0 but less than n um okay so in one operation we can select two indices so you can select one index x and one index y so whatever index x is we're going to subtract one value from it and we can select index y where we increase its value by one so for example if we have uh two things one with the value of one with a value of three and what we could do is we could increase the value of one and decrease the value of the other one okay so the goal here is to make all of the elements equal to the array and it is guaranteed that all elements of the area can be made equal using some operations okay so given an integer and the length of the area return the minimum number of operations needed to make the elements of area equal so let's take a look at the first example that they gave us over here which is n is equal to three okay so we're only going to be given n which is again the length so the first step just to make it easier let's form our area from scratch okay so our area is going to have a length of three okay now what exactly are their values gonna be and to get their values we're gonna be using the formula which they gave us which is n into i plus one right and just to make it simpler let's write the index values so zero one and two okay so in this case uh at the zeroth index it would be two into zero plus one and that's nothing else but zero plus one which is one so over here we have two into 1 plus 1 which is 2 plus 1 3 and then over here we have 2 into 2 4 plus 1 which is 5 okay so this is what our area looks like when n is equal to 3 and this is the rule that we're following to get the actual values now what exactly are we supposed to do our goal is that all of the values here have to be equal and we want to do so in the minimum number of steps so to make it the minimum number of steps we have to kind of fixate on one target so what is going to be our final target for this question what is the value that is going to be consistent or the same in the entire area now how exactly do we find that so one really simple way to do that is we're going to look for the value which is in between of the entire area so in this case we want a value in between of one and five and that value could be the number 3. now why exactly do we want a number in the middle and the reason for that is because what we could do simultaneously is we can always increase the smallest value and decrease the biggest value right so x i think so x is the one which decreases by one and y increases by one so this could be y this could be x and we could do that for each pair so let me just show you one example so let's say we have a total of four things so we could increase this by y decrease this by x and sample and this could be kind of like a pair simultaneously and the next time we could increase this by some amount and decrease this by the same amount so they kind of form a set of pairs and the set of pairs is what we're going to kind of use to actually get the minimum number of values right okay so going back to this case over here we're finding out that the target is three and essentially we're just uh saying that because since that's what's in the middle okay we want the middle number in this case and that is going to be three and another way to actually get that is uh in this case we have uh three values and we have a middle value which in this case is 3 and we want everything to be equal to that all right so in this case what we're going to do is we're going to first we're going to do it in pairs so first we're going to take this and this okay the first value and the last value and we're going to increase the first value and decrease the last value until both of them equal or equal to the target so first we increase this and decrease this so this entire thing is one step okay and we do it again right so now this becomes three and this over here is going to become three so at the second step both of them now have the same value and this is going to stay as it is and as you can see at the end of two steps we found the entire value right so when n is equal to three it took us two steps to find this value so now let's look at a bigger example and this should actually kind of show you a pattern which is visible in this question all right so let's just take n is equal to six so in this case we're going to form our area again so we would have one then we would have three and essentially this is a arithmetic progression with a difference of two so one three five seven nine and eleven okay now the question is how do we find our target so when we have an odd number of values we can find a middle point but in this case uh to find the middle point uh we would actually have these two numbers right so uh one two on the left of that so the middle point would just be whatever's in between of these two numbers so five plus seven divided by two is equal to six so the target is equal to 6. and just for the sake of simplicity another way that we can find this target is by taking the sum of all of these values so let's just do that real quickly so 1 plus 3 plus 5 plus 7 plus 9 plus 11. so that would be 20 27 30 35 36 okay so that would be 36 that's the sum of this and we're going to divide it by how many elements are there which is nothing else but the n value so 36 divided by 6 gives us a value of 6 which is the same thing as the target so that's another way to find the target okay so now that we know the target we're going to perform the operations uh in that manner and remember we're going to do them in pairs so we're going to increase and decrease the first and last in the same amount of times then we're going to increase and decrease the second and the second lasts the same amount of times and so on and so forth so let's start off with this over here so this we're going to increase it by one and everything else is gonna stay the same so i'm not gonna write anything and then we're gonna decrease the last one by one so it becomes two and ten so we just keep doing this so this becomes three and this becomes nine then four eight uh five seven and six perfect so at the ending of let's count how many steps it took so it took one two three four five so after five steps the first and the last value are equal to our target okay so we can ignore so we're done with those two values now we're going to look at the next two pairs which is going to be the second and the second last value three and nine and we're going to do the same thing until they're both equal to six so let's continue so this three is now going to become four nine is going to become eight so four eight then we have five seven and six so this is the sixth step seventh step and eighth step so after eight steps we have four values equal to the target and finally we have these two the third number and the third last number we're going to do the same thing so we're going to increase this by 1 making it 6 and this is going to decrease by 1 making it 6 as well and this is the 9th step so at the ending everything ends up becoming the value 6 after 9 steps but there's one simple pattern that we can observe so the thing is in the beginning it took us five steps to get the first and the last value to be equal to six okay so i'll just write it down over here so it took us uh five steps in the beginning now in the second time which is the second and the second last values it took us three steps okay then it took us one step uh for the third and the third last values so as you can notice this is a small uh progression over here right so the basic idea is each time we're going to decrease by two to get to reach our target so beginning it took us five steps then it took us three steps and then one step right so there's kind of a small uh progression in this case with a difference of negative two and we're going to use this idea to solve our question so the way we're going to solve our question is we're first going to find our target where we first find the total sum and then we're going to divide it by the n value giving us a target now that we have our target we're going to find the difference between the first value and the target or the last value on the target but in this case the first value is easier because we know the first value is always going to be one all right so in this case the difference is gonna be six minus one which is equal to five so five is going to be the starting or the basic amount of steps it takes to reach that amount so we have five in this case in the beginning now what we're going to do for our for getting our result we're going to start off with five then we're going to add it with 5 minus 2 which is nothing else but 3 right and the reason for that is because after 5 steps it takes 3 steps for the next set then we're going to do 5 minus 2 which is nothing else but 3 minus two which is one so now we have five plus three plus one and the next thing would be one minus two but that gives us a negative number so once we reach one we're done so this is nothing else but our result which also gives us the value nine which is the same as what we expected so hopefully you didn't understand this pattern and we're going to use this pattern in order to find our final answer so now let's see what the code of this looks like all right so the first thing that we want to do is we want to find our target and to do that like i said you want to first find the total sum of the array and we're going to start off by having a value of zero and then we're going to go in a while loop and we're going to do this by doing for i in range n so essentially if n is 6 which means it has a length of six uh we're going to be iterating through all of its indices so zero one two three four five we get all the index values now using the index value we can find out what the actual sum is supposed to be or sorry value is supposed to be at that index and we can do that with the formula which they gave us which is n into i plus one all right and now that we know the value at the index i we can add this to i'm sorry we can add this to our total sum so total sum plus equals to the value so at the ending we have our total sum and now we can find the target by doing total sum divided by n perfect so now the second step is to find the result right which is the minimum number of steps or operations it takes right and the way we're going to do this is like i said is we're first going to find the difference and this is going to be the difference between either the first or the last value and the target okay and just to make it simple i'm just going to use the first value because we know the first value is always going to be one so this is going to be target minus one all right so we have that and so that should be it and over here i just want to talk about two cases so we have we might have a condition where we have um nothing right it's just an empty area and we might have a condition where we just have the number one so in both these conditions uh we could write separate statements for them but it's already being taken care for here because in this case we would actually have a difference of negative one and in this condition over here we would have a difference of zero so in order to actually take care of both of those uh first let's define our result of zero then we're going to have a while statement and in this while statement we're only gonna go inside if our difference is greater than zero so this takes care uh care of the two base conditions i showed earlier and another thing this does is once the difference is equal to one we're done we're not going to do anything else that means we reach the ending okay so over here each time we're going to increase our result by the difference the result plus equals to difference and each time the difference is going to decrease by two and why is it two it's because i showed you the pattern which we uh saw in the illustration earlier right sorry so that should be it at the very ending once difference is equal to one then the next iteration difference is going to be equal to negative one or something and then we're not going to enter the while loop and finally we need to return our result so one thing to know is that for some reason result is a floating point value so i'm just going to convert it to an integer over here okay so that should be it for the solution and i'm not going to go over the java solution because i think it's pretty simple and basic to understand uh at least code wise so yeah so that should be it for this and thanks a lot for watching guys
Minimum Operations to Make Array Equal
npv-queries
You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`). In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make all the elements of the array **equal**. It is **guaranteed** that all the elements of the array can be made equal using some operations. Given an integer `n`, the length of the array, return _the minimum number of operations_ needed to make all the elements of arr equal. **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** arr = \[1, 3, 5\] First operation choose x = 2 and y = 0, this leads arr to be \[2, 3, 4\] In the second operation choose x = 2 and y = 0 again, thus arr = \[3, 3, 3\]. **Example 2:** **Input:** n = 6 **Output:** 9 **Constraints:** * `1 <= n <= 104`
null
Database
Easy
null
983
everyone welcome back and let's write some more neat code today so today let's solve the problem minimum cost for tickets and before we even get into the problem when you see a keyword like minimum or maximum or number of ways or you know anything like that you kind of have a hint that the problem is going to be dp related dynamic programming related but let's just continue on and i'll kind of explain why dynamic programming is going to help us with this problem so we're given an integer array of days and each day within this array is going to be sorted right so we're going to have a list of days let's say one two three and basically it's going to be a sorted array and it could have integer values anywhere within the range between 1 and 365 so it's days within a single year now it doesn't have to have those right we could have one two three and then you know a hundred right these are the days within the year that are going to be in this array right you know it could actually have every single day from 1 2 3 all the way to 365 right it could but that's just kind of uh the possible values we could have within this array we're given a second array as well this second array is always going to be of size three it's gonna have three different values the first value is going to represent the cost it takes to purchase a one day pass what does a one day pass do for us well we're given this integer array of days this one day pass will allow us to travel for one day so suppose on day one right here on day one we purchase a one day pass that means okay we have our travel covered for day one right but now we're on day two so we're gonna have to purchase another one day pass if we want to be able to travel on day two basically this array of days is just a list of days that we want to be able to travel on and this uh second array is going to be the cost of the travel pass that we need to actually be able to travel now the difficulty here is we are given a choice we're given three choices of travel passes that we can purchase a one day pass we can purchase a seven-day pass or we can purchase a seven-day pass or we can purchase a seven-day pass or we can purchase a 30-day pass now a one-day purchase a 30-day pass now a one-day purchase a 30-day pass now a one-day pass is straightforward a 30-day and pass is straightforward a 30-day and pass is straightforward a 30-day and seven-day pass is a little bit more seven-day pass is a little bit more seven-day pass is a little bit more tricky so for example a seven day pass in this case suppose we purchase a seven day pass on day one so that covers our travel for day one for day two for day three for day four five six and seven but notice how four five six and seven aren't even inside of this array that means we don't even need to travel on these days so one possible choice you might be noticing here is we can we could have done this two different ways right we could have purchased a seven day pass which would allow us to travel these three days that we need to travel on or we could have purchased a one day pass on this day and even a one day pass on the last day or like i said earlier we could purchase a seven day pass to cover these three days and then do a one day pass on this day and basically as the title states we want to know what's the minimum cost it's going to take for us to travel all these days so the first thing we should do with a problem like this one is just try to determine a possible solution even if it's inefficient let's start out with the brute force approach and then see if we can even come up with a solution that works and then from that brute force let's see if we can optimize it any way possible okay so let's take a look at the first example that they gave us so this is the days that we want to travel on and this is the costs array so the first value two is if we purchase a one day pass seven is if we purchase a seven day pass 15 is if we purchase a 30 day pass right so this is the price and we want to know what's the minimum cost to travel all these days given these choices so let's just brute force start making our choices right and you guys know i like to do a decision tree for that so let's say that we start on day one or in other words we start at index zero of this array right day one is what's at index zero and we could purchase a one day pass which would cost us two dollars we could purchase a seven day pass which would cost us seven dollars or we could purchase a 30 day pass which would cost us 15 now obviously if we purchase a one day pass you know instead of being at day one we're gonna be at day two right but now the important question you said you should ask is day two even in the array of days that we wanna travel on well we don't even wanna travel on day two right so who cares skip day two right do we wanna travel on day three nope it's not in the array is it so in reality when we purchase a one day pass all we really need to do is go to the next position in the array right we started at position you know at day one the next position is day four right so let's just go automatically to day four right day four is the next day that we actually want to travel on and if we purchased a seven day pass for seven bucks then we would the next day we would want to travel on is day eight right one plus seven brings us to day eight now in terms of how we're actually going to do this algorithmically is we're not just going to assume that day eight is a day that we actually want to travel on it could be that day eight isn't even available let's go back to our array right starting at position one we're gonna go to the next position until we get to a value that is greater than or equal to day a because you know we purchase a seven day pass that means we traveled on day one we can travel on day two three four five six and seven right but so basically we have a travel pass that can cover these days but we can't cover day a and beyond right if we want to go to day eight nine ten we can't cover that with a seven day pass so we'll have to purchase another pass so that's what i'm getting at over here so let's go back to our array so from day one we can go to day four yep we can cover that we can go to day six yeah we can cover that day seven we can cover that but then finally when we get to day eight we can't cover that with a seven day pass so day eight is going to be the next uh day that we look at in this decision tree now if day eight wasn't even in this array up above if day eight was not there then we could automatically skip all the way to day 20 right because we don't have to travel on any days in between 7 and 20 then we can just skip there right that's kind of the logic that i'm trying to get at here so with the seven day pass we get all the way to day eight now with a 30 day pass for 15 bucks we can actually skip every day here right because with a 30 day pass we can go through days 1 through 30 right so if we iterate through this array day 4 is covered day 6 is covered 7 8 20 is also covered with a 30 day pass that we purchased on day one so we actually covered the entire array right so there's nothing left so basically this is one solution that we can at least one decision one path in our decision tree right if we just purchase a 30 day pass it'll cost us 15 to arrive at the destination so the question now becomes is that the minimum well we don't know for sure because we haven't fully gone through these two other paths yet so now that you kind of get the main logic of the decision tree i'm going to go kind of quick so i'm just going to tell you that this is the path that's going to lead us to the correct decision and you know we could purchase a one day pass which would bring us to day 20 and the cost of that would be two bucks so then we'd be at day 20 or we could purchase a seven day pass for seven bucks and that would put us at you know the end right or actually that would not put us at the end because then we'd actually again be at day 20 right because from day eight seven days is not enough to also travel on day 20. so you can kind of already tell that this path is the same as this one except this one just costs more so this is probably not going to be the solution and from here we also have a choice we can purchase a one day pass or seven day pass or a 30 day pass but since there's only one day left day 20 is the last day of course we're gonna want to purchase a one day pass right for two bucks so let's draw that over here and then we get to the end so what was the overall cost of this entire path it was seven plus two plus uh two which puts us at 11. for this path was 15 you know with this path we could purchase a seven day pass for seven bucks and then purchase another one day pass but that would pretty much be the exact same as this path uh which would also be 11 bucks so 11 bucks is the minimum you can see that there are you know potentially multiple solutions that lead to the same result but it doesn't really matter because all we want to return is what was that cost right we don't want to know what days did you purchase the passes and all that we just want to know what was the cost in this case it's 11. up above you can see that they had a similar explanation and the result ended up being 11 which is the minimum the good thing here is that we did find a brute force approach what is the time complexity of this you can see it's a decision tree we could have three branches on the decision tree which gives us three as the base now what could be the height of the decision tree basically the length of days right because we'd have a branch each time we get to a new day so overall you could say the time complexity is 3 to the power of n which is not very good it's exponential but is there any way we can eliminate repeated work in this problem yes we can and there's a couple tricks to doing it so you can kind of tell that you know the node values that you see here what determines you know the node value for example one or four or eight what determines that it basically is determined by the index i that we are at currently in our day's array right if we're at index zero then we're at day one if we're at index one then we're at day four for index two we're at day six etc and that's really the only parameter we're going to have to pass into our recursive dfs solution right i is the only parameter the index of the day that we're at because our costs are always going to be the same this is never going to change or anything so i is the only parameter we're passing in so then how many if we cache this hopefully you are familiar with caching basically if we find the result of let's say dfs we call dfs starting at index 2. if we find the result of that we don't want to recall dfs again because you can see that might be the case with a really big tree like this we might end up you know from here you can see that these two parts of the tree end up calling at the exact same index so we don't want to do repeated work so we can cache that so if we compute a dfs of two we'd put that in a hash map or a cache or some kind of data structure and then we wouldn't have to repeat it again so if we only compute the dfs from every single position index i how many times are we going to be calling dfs uh basically the size of the input array days right so the actual time complexity is going to be roughly big o of n because n is the number of times we're calling dfs now each particular call of dfs could be inefficient right it could have its own time complexity so maybe of n is not accurate but it turns out that the way we're doing it if we purchased a one day pass we'd only look at the next position and then we'd be good if we purchased a seven day pass then we'd have to potentially look at the next seven positions of the array if we look if we purchased a 30-day pass if we look if we purchased a 30-day pass if we look if we purchased a 30-day pass we'd have to potentially look at the next 30 positions of the day's array so technically the actual time complexity of this could be not n but rather 38 times n the way i got this 38 is basically 1 plus 7 plus 30 because that's how many operations we'll have to do within a single dfs that'll probably make more sense when we write out the code but what i'm saying is the time complexity is still big of and even though we have a constant value here i think this is all you really need to know to jump into the coding solution so let's do that okay so now let's do my favorite part the code because we don't have to draw anything we can just write it out let me know if you made it this far into the video make sure to like and subscribe it really helps out the channel a lot uh but so the first thing we want to do here as you can see is our cache i call it dp you could call it cache or whatever you want this is just so we don't have to do repeated work now let's write out our recursive uh backtracking or dfs function that we are going to be implementing with dynamic programming because we're using a cache and remember the only parameter we need for this is just the index that we're at in our days array now let's not forget about the base case what if we go out of bounds well if i reaches the end of our day's array then what are we going to return we're going to return zero because what we're saying is if we don't have to travel any days right like if we're if there aren't any days left for us to travel how much is it going to cost it's going to cost 0. the second base case is if this has already been computed before meaning if i is in our dp cache if that's true then we're going to return dp of i because it's already been computed we don't want to waste time recomputing this work the next thing we want to do is initialize this dp of i equal to a default value and since we're looking for the minimum a good default value for this will be infinity because then if we compute a different value it'll obviously be reassigned to that smaller value so initially we'll set this to infinity but we're obviously going to compute it based on the three costs that are available to us so let's iterate through that costs array and we're going to do it simultaneously with another array and so basically some python magic is we can zip an array basically iterate through two arrays at once so one is we want to know for the prices how many days can we actually travel we know that's 1 7 and 30. so that's one array the second array is going to be the actual cost associated with each of these you know durations so we're going to be iterating through these two arrays simultaneously so d is going to be the number of days we can travel and c is going to be the cost for traveling that number of days and here's where things get a little bit tricky compared to other dp problems so you might be thinking okay we want to know what's the cost to you know uh starting from day i to travel all the remaining days in the in parade can't we just compute that with let's say obviously we want to find the minimum right so let's take the minimum of whatever it is itself and then also you know recursively say okay well the cost if we purchase this current day pass is just going to be okay c plus uh dfs of let's say i plus d right that might be your first guess because i is the current day and then d is the number of days that we purchased the pass for but remember like i showed you in the example what if we had an input such as 1 2 and 8. right if we purchase a 7 day pass on day 1 that'll cover day 2 but it's not going to cover day 8. and remember the parameter that we're passing into our dfs function is the index of the value you know of this day's array so we can't pass in day eight and expect to get here we'd actually have to pass in index two to get to this spot so we're actually gonna before we even run this we're gonna have to do some pre-work we're gonna have to do some pre-work we're gonna have to do some pre-work we're gonna have to find that day basically we're gonna run a while loop starting at day i wherever we're at and keep incrementing until we get to a day that would be out of bounds so for example if we purchased a seven day pass day eight would be the first day that's out of bounds so let's use a different pointer to determine that we're gonna use a pointer called j it's initially gonna be set to i and we're gonna increment this pointer j while it has to of course be inbound so while it's in bounds of the days array end while days uh at index j is less than whatever day we can travel to with the purchase pass that we're iterating through right now and how do we determine that well it's going to be days at index i right that's the current day that we started at plus how many days can we travel we can get that with d right d is that parameter so days at index i plus d this is the day that we can travel to so for example if we start at day one and we had a seven day pass eight would be the value that this evaluates to and then uh you know this our pointer j would keep being incremented from this array until we actually arrived at this position so this while loop is just kind of incrementing j plus one and then finally when we have j at the position that we want it to be at in this dfs that's what we're going to pass and we're not going to pass an i plus d we're going to pass in j because that tells us what's the next day that we'll actually need to purchase a travel pass on and c is the cost that it took us to actually travel to this position so c plus dfs is you know the computation that we need to do here and after that loop is done then we can go ahead and return dp of i that's what we you know spent all that time computing and you might think that is this an o of n time loop no it's not this loop is going to run at most roughly 38 times because this while loop could execute once when we go through the one day pass it could execute seven times when we purchase the seven day pass and it could execute 30 times when we purchased the 30-day pass times when we purchased the 30-day pass times when we purchased the 30-day pass so it's not a linear time loop it's in you know 38 times loop but yeah that's the entire dynamic programming solution recursively at least and then once we're done with that all we need to do is actually call our recursive function that we just defined and we'll pass in zero because remember zero or whatever you know this value i is the index that we're starting at in the days array of course we want to start at index 0 of the day's array it's not the day itself 0 it's the index so that's the entire code let me run it to make sure that it works and as you can see on the left it does it's relatively efficient you might be wondering what does the actual dynamic programming solution look like compared to this and it's pretty similar i'll just copy and paste it right now just to show you so we'll use the exact same cache that we have above but let me copy and paste so this is the dynamic programming solution you can see we're doing it without recursion we're doing it uh you know we're doing it backwards the outer loop up above is going in reverse order but you don't have to do that the reason i do it in reverse order is just because then it matches up with the recursive solution but you don't have to do it like that you could do it front to back but the rest of this is pretty straightforward it's pretty similar to what we had in the dp solution uh one thing i will mention is how the base case you know in the recursive solution we go out of bounds we end up returning zero the way i handle that in the dp solution up above is a dp.get which is a python function is a dp.get which is a python function is a dp.get which is a python function for hashmaps so i'm saying dp.get for hashmaps so i'm saying dp.get for hashmaps so i'm saying dp.get whatever is at index j now what happens if index j is out of bounds well then we're just going to return 0 as the default value this is just a predefined function in python that i'm using just to shorten the code a little bit so that we don't have to actually write out an if statement on this line but other than that i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel if you want and hopefully i'll see you pretty soon thanks for watching
Minimum Cost For Tickets
validate-stack-sequences
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Array,Stack,Simulation
Medium
null
384
in this video we're going to be looking at this problem shuffle and array we're asked to design an algorithm that randomly shuffles the array and what it means by random shuffle is that all permutations of the array should be equally likely as a result of the shuffling alright let's break this question down so let's see what does it mean to shuffle something in real life so let's say that we have an array of numbers one two three four and you can think of this as a bag of marbles labeled one to four then the result would be okay first let's randomly remove an item from the array so let's say two and then let's remove randomly remove another one let's say four and then we keep doing this so on until we're out of numbers so this would be a random shuffle every resulting permutation is equally likely so this works but if we try to translate this brute force solution directly into code it's not the most efficient so the pseudocode will look something like this so we're going to repeat n times going to randomly remove an item from the array the issue is that removing the item itself we would need to shift down the array which is o n so we would actually end up with the time complexity of o n squared so how can we do better so we want to use an algorithm called fischer yates shuffle the idea behind this algorithm is that instead we can randomly swap elements in place in the array so i'll give you the pseudo code first index i in the array we're going to swap the item at index i and a random index between i and n being the length of the array so we're iterating through n items swapping is one so the overall time complexity is on so take a minute to try some examples on your own and try to convince yourself that this is actually the exact same thing as randomly pulling numbers out of a bag but in a more clever way so the idea is that you can think of i as being the i item being removed out of the bag which means that the items from 0 to i minus 1 are essentially the items that have already been removed whereas items from i to n are the remaining items in the bag so then when we generate a random index between i and n that's analogous to randomly choosing an item still in the bank all right let's implement this in java this problem asks us to implement the methods reset and shuffle where reset is going to reset the array to its original configuration so first let's create a field called nums and we're going to save nums so that we can return it and reset later now onto shuffle let's first get this edge case out of the way which is where nums is null i'm going to just return all here then let's create a copy of the nums array this is because we don't want to modify it directly because then when we reset it won't be its original values now let's iterate from 0 to the length of the array the first thing that we want to do is generate a random index between i and the length of the array let's create a helper function for this let's call it random range so to generate random numbers in java we're going to use a method called random a class called random and we're going to do random.next int and we're going to do random.next int and we're going to do random.next int max minus min plus min take a minute to understand this for yourself but basically next in generates a random number between 0 and n here's generating a random number between 0 and max minus min so since we plus min that means the lowest number that can be outputted here is min and then the highest is max minus min plus min which is max so this works then over here we're going to do in j equals random range between i and the length of the array as we said and now we just need to swap the elements between i and j and we're going to create a helper function for this as well this is a pretty standard pattern we're going to create a temp variable and then the item at index i is going to be j the one i j is going to be temp and then here let's return the array i also just need to instantiate random okay cool now let's run this code great it works so that's how you do this problem shuffle an array
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
732
hey what's up guys john here again and today let's take a look at this uh let's call the problem here number 732 my calendar number three it's a i would say to like a medium between medium and heart problem you know and i think it's a very interesting problem comparing to the regular or normal like or interval or meeting room problem you know same okay so and this one it asks you to uh to implement like uh a small class here okay where the book method will be called uh many times i think here uh yeah the book method will be called like at most 400 times okay and then basically it asks you to return like the uh the most meeting rooms not the meeting room sorry the most events okay so the most events that have like have uh have the intersections okay so for example this one here and so when you call the book at the first time right there so uh it's 10 to 20 okay right so it's 10 to 20 so which means the intersection is one basically i think it's just asking you to like what's the most meeting room you i mean you need but uh in history but not at the moment okay so this is a little bit tricky here so and so in book two here like uh 50 to 60 okay so somewhere here 60 to 50. and still right still there should be only one uh intersection right and now 10 to 40 okay so now we have 10 to 40 okay so now as you guys can see we have a we have two like bookings right who is a intersect with each other okay right now five to 15 okay five to 15 is here right 5 to 15. okay and at this moment right see we have three right which is this one we have three i intercept three bookings that intersect with each other now the next one is five ten so that's five ten okay so five ten but keep in mind here right no notice here like the 5 10 you know 5 10 eight 5 10 only intersects with uh with 5 15 that's that which is two right but we're still returning three here because it asking us to return the most k uh here i think the most okay uh yeah returns an integer k representing the largest inter integer such that there are existing okay bookings in the calendar basically it asks you to loop through to check all the history bookings okay and to find out the uh the most intersected uh bookings which in this case is still three right okay and then 25 to 55 25 somewhere here 25 here uh that's here 255 is here 25 to 50 to 55 okay so i think it's so this thing is to uh it's still like uh three yeah one two and three okay is this three no actually it is two okay so for 20 for this 25 to 55 it's still two because 25 only uh intersects if it's this one but these two they don't share the same like intersection that's why for this one is still two but we still have like three here okay so i think you guys can see here so what we are what we really need is we just need to uh keep the history for all the bookings okay and every time we have a new bookings here we're gonna try to scan from the left to the end okay and every time you know just at the beginning you know i was thinking that okay i need like i need to create a two list basically uh you know every time when i see a start here right i increase the count by one okay we're gonna have like self i'm gonna start starts right the list and then i'm gonna have like ends list okay and then i'm gonna try to sort this start and end from smallest to the biggest right and every time when i see a starts i increase the count by one and then when i see the ends i decrease okay so same thing here basically uh when we see five here right so we have five and five right and then we just uh the count will be two well i mean will become two right and then when we see uh like a ten here right so 10 here means that we're gonna decrease by one so two will become one and then we have another like ten here right so the now will become three now we have a 15 here so this will become to 2 20 1 right yeah and then when we see a 25 2 and forty one fifty two uh fifty five one and then sixty zero okay that's how the uh the intersection looks like right so and as you can see the most one the biggest one is it's three that's why that's how we get the three here but i was thinking about if i can use the like the i was trying to use two lists here but then the problem is that you know since uh we need to sort the starts both starts and end right and then the uh the start and end the integer in the range of like a huge number here so basically we cannot assort we cannot do the range from the smallest and then from zero to the biggest number of to the last time of the end which that will be too many uh for loop right so we should like instead we should just uh loop through all the starting point and ending point but with these two uh arrays separate right i mean it would be hard right basically let's say we sort the starts and we and then we source the end we restored both the start starts and end and um we can only use one of the list as i mean as a for loop right let's say we start we use the starts and we have five which is good and then the next is five the next stars is ten right it's ten but then how can we find how can we use the stars to find the end here right that will be uh kind of difficult so instead we should merge those stars and ends in into one into a one like into one like times okay into one array here basically you know so every time we have a starts we use the time we do a we plus it with plus one right and when we have an ends here right we decrease that time by one in that case we can just use the time this one's array to represent both the start and end and still we sorted by the time then we can just simply loop through all the time spots right in this array and then we can get the result we need here yeah that's the basic uh thinking process here and let's try to implement this thing here cool so like i said uh we're gonna have like time times right and this is gonna be a like the uh the integer and default it is integer and it's a dick as a dictionary and um yeah so self dot times right times uh start with increase by one and self dot times end right we decrease it by one okay now we just simply do a sort right for time in sorted inserted self dot times okay and uh yeah we can have an answer here it's zero okay so uh that's the answer uh and we need a current here we need the current we also need the answer here uh yeah it's current inter intersection here and if we have an answer here basically the current interac current intersection will be the self dot times dot t right and then we every time we have a answer there we update max dot current enter right and in the end we simply return the answer yeah i think that's pretty much it is okay let's submit yeah cool so accept it all right i mean as you guys can see the rent the time running time is not that good because we uh what's the time complexity for this right let's say assuming we call this booking end times right and for every bookings will be uh n right times what we do uh we do a sorting right we sort the uh the times right that's going to be a unlock n okay right unlock so basically it's going to be an n square log n yeah we stored it and then we do a for loop before we say it's just n right but still it's also unlogging so which makes this solution n square log n okay and i think if you use like a java i mean in java there's like a tree map right where you can uh basically where you can keep the sortings of the times while you're doing the insert right in that case i mean maybe uh it's going to be a i think o in it's going to be a log and may maybe i'm not quite sure about that because here we need to sort it right because we have to scan from the left to the right i mean or we can somehow like when we do the insert when we do the um yeah when we try to do uh the set here maybe we can try to maintain like other so that we don't have to sort it but uh anyway so the main idea for this but for this problem is the uh we just need to track up the boundaries basically we track the both the start and end endpoint right and we use the same list or the same dictionary okay because uh we need to scan both the start and end all together that's why we're going to use the same uh dictionary and the difference is for the ending time we decreased by one and to start we increase by one okay and after that we just simply uh keep track of the current intersections okay and then we update the answer yeah cool i think that's pretty much i want to talk about for this problem you know this is one of the those like meeting rooms uh meeting room uh calendar problems basically we have these different intervals and then we have to do something with intervals you know now for the other like interval problems like the meeting room number two it asks you to find the minimum meeting room right you need to uh to hold all this like meetings or all these bookings right so for in that problem you know what we need what we did was the uh it's very common right to sort by the start time okay we store it by the start time and then we uh we use a priority queue right we use a priority queue to track off the uh the end time here yeah we use the so i think if i remember correctly you know there were like a few uh regard different uh violations about this kind of problem you know the first thing first one is the uh it asks you to find okay how what's the most how many the given like uh given like a time range or something like uh what's the most uh or like given like two meeting rooms or some meeting rooms are like what's the most uh meetings uh this two meeting room where k meeting rooms can hold right so for that problem you what we did was the uh we sort been by the end of time we use a greedy method because to be able to hold as many readings as possible we want to start the meetings that ends the earliest first okay and then basically we sort by end time okay and then we just uh scan that the meetings from that from start to the end and another variation is the uh like the uh the meeting room number two which is ask you uh to find the minimum right the minimum uh the minimum me a meeting room right to hold all those kind of meetings right so for that one i believe we need to sort by the start time okay and we sort by start time and then uh we use the uh the priority queue the priority key to hold the uh the end time for all the meetings for other meetings that we have already started and every time when there's every time when we have like a new meeting new media meeting comes in we check the priority queue to see if uh if the earliest uh so if the current meeting start time is greater than any of the uh then than the earliest ending meetings if that's the case then we know okay we can basically reuse the previously uh scheduled meeting room to host the uh the current meeting right and then we keep doing it until the end in the end we simply return the length of the priority queue then that's what that's the length of the priority will be our and the minimum meeting room we need actually you know what i probably i would just do another videos for that um meeting room number two problem to do a uh more detailed explanation for this okay cool guys i think that's pretty much i want to talk about for this problem yeah thank you so much for watching the videos guys and stay tuned see you guys soon bye
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
463
hey everybody this is larry this is day four of the october eco daily challenge hit the like button to subscribe and join me in discord let me know what you think about today's problem so one question i've gotten recently is try to figure out how to do it how to you know there's a new interface trying to figure out how to even get to the new problem because it used to be an explorer so i think the two ways to ice fine it's that what i like one is just you know it's in a problem which you know it's just a top thing but the other thing you can do is actually look at this calendar to the right group just click on it and it goes straight there i think that's the way that i'm going to try to do it going forward and of course also today i'm a little bit later than you um at this because i don't know 8 pm yes t uh eastern time is a little bit awkward for me so we'll see how that goes anyway okay let's look at today's farm island perimeter okay uh let's see so one thing i would say is that i usually stop this live so it's a little bit slow just watch it on a faster speed okay so let's see okay okay um yeah i mean i think this seems pretty straightforward it is uh a yeezy problem but like i said i don't like seeing that because it kind of bias me to think about dumb solutions um whether instead of trying to do a little bit better but yeah i mean i think for n and m or r and c if you will rows and columns is less than 100 let's look for every cell right so what does it mean right every cell there's a border if you look uh up down left right and it is inside a cell and the border is out not inside a cell right so there's a couple of ways you can do this a couple ways you can you know um but yeah i don't um yeah i don't think there's anything tricky about it so let's get started then right uh let's see so that becomes an implementation problem so directions let's just say we can look uh i think i usually write this in a couple of ways but today i'm just going to keep it simple for now and so that afterwards i can go get food so yeah so then now we start at x y and of course you have to declare it let me make sure that there's at least one column okay so yeah so then now we just go if the grid of x y is equal to uh what's it which one is one uh one is land so yeah if this is lan then we just you know we also have a count here zero and then just go through d x d y in directions if so n x and y is equal to x plus d x y plus d y so then we have uh two scenarios right so if nx so if this is not true meaning so this is our bounds or you know same thing but for y or a grid of nx and y if this is equal to zero then we just increment count oops and that's pretty much it i think yeah so let's give it as uh example test the one thing i do like is that i don't have to write the example cases but yeah so it looks good and it looks good so let's give it a submit yeah let's give it a summary ah i did it in c apparently two years ago or something like that and then i also did it in python a year ago and then today i also did it in python yeah i mean this is pretty i don't know i don't remember i'm not gonna lie i don't remember this problem per se but this is uh you know i would also say that and that's just very weird or memorable i'm not gonna remember a easy problem because it's just not worth remembering right uh you know just thinking about how to be consistent with your techniques and your implementations and everything should be okay so yeah so what's the complex of this well this is just linear because this is all r and c or r times c times eight if you will but of course the bigger takes it away uh in terms of spaces it's just over one we have a couple of variables and we just go further away and we don't even change anything so yeah um that's basically all i have for this one this is a pretty straightforward one hope y'all uh you know enjoy the rest of your weekend or if you're it's already monday then enjoy the rest of your week or whatever you like anyway stay good stay healthy to the um to good mental health i'll see you later bye
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
1,578
hey everybody this is Larry this is day 27 of the Leo day December challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm it's going to be uh what is it three more four more one five or six more until the end of the year I cannot count clearly but uh maybe I can count this Farm though let's take a look 1578 minimum time to make whoop colorful okay that is a nonsense statement but let's keep reading this has I don't know I'm a little bit Tripper today I think I finally stepped enough but still have a little bit of jet lag so we'll see what happens Al says and balloons are range on the rool you're given a zero index string colors where colors Sur the color of the eye balloon Alice wants to be colorful she does not want to consec balloons to be of the same color so just B well B can we move some balloons from the W to make a color but you're given s index away needed time where needed time is the time in seconds that Bob needs to remove the eye balloon from the r we the minimum time Bob needs to make R colorful okay I mean I don't know uh but it just seems like uh I don't know about the statement I mean but it seems like uh basically you don't want to cons balloons to REM to have the same color so basically another way of saying is that for a group of the same color balloons you just want to keep one of them uh there probably a couple ways to write this uh but yeah it's all going to be just linear time constant Spacey things if you're lazy you can maybe you know do constant space Oh sorry linear space but I mean I think it's fine either way right so basically h yeah um yeah I mean I think just it just going to be greedy right and by greedy I mean that for a collection of balloons that are consecutive or adjacent I guess is probably the better word but for all the adjacent balloons or collection of balloons where they're the same color you just take the one with the uh I guess the maximum time to keep and we move all the other ones right so yeah so basically uh yeah I think that's pretty much it really where n is length of colors right and then basically uh if just trying to think what the CEST way to write it is but I don't really think I mean I think you're just careful it should be fine right if this is zero and uh color sub I is equal to color sub I minus one then what do we do right um basically what we want to do is um so if it is not then we do okay so if the same colors then we keep one of them or we have to choose whether we want to keep otherwise it ways otherwise that means that we're at the border and or uh the thing so then we don't do this right so max is uh you go to needed time needed times of I cuz that is basically the max that we're keeping and then otherwise if they are the same color though because if they're different color then you don't remove this one right because this is the first balloon of a new set of colors otherwise then yeah otherwise you want to see if um if needed time sub I is greater than Max then we say okay well first of all we well maybe not first of all at the end we set max is equal to need of time before that means that we're going to remove Max right so total we at Max and that's pretty much it I guess cuz then now you do this and then at the end I think this should be good but maybe I'm missing like an ed case which I am apparently uh I'll put one expected two yeah I'm kind of I don't know how I missed this but no I mean wait okay so you move this one so it gets one or you move it when you get to two okay fine next one is four oh I guess I forget an else here otherwise you just remove this time and I think that should be fine right uh yeah uh am I missing a case let's give a submit it's very easy to miss a case to be honest so I'm not wouldn't be surprised at least the way that I wrote it I to be honest this is linear time constant space is very cool it's just like I said right after you formulated the problem there's so many ways to kind of write this you can write however you like and I try to keep this um linear time constant space but honestly if I were to write this in a more like I was in competitive or something like this I would probably just do linear time linear space or maybe even just pass another scan or something cuz this kind of you have to really think for all the states that can happen if I were to kind of guess I would have done something like um maybe I would have done zip and groupy together or something like this so then maybe I would have something like you know you zip colors and needed time um and then now you want to do goodbye I forget how to choose the goodbye key is it just key um something like this right and now you have for um and something like that maybe uh let's see if this well something like that maybe I forget how it goes I'm just kind of returning some random junk just to see if this compiles or I say compile but yeah okay I mean I guess I that's actually impressively I mean I'm impressed by myself which I don't know because I did not expect this to work like that is what I mean but uh but yeah but then now you can just write some right we want to um basically add the sum of V minus the max of right just one Max and that's pretty much it and this look I don't know if this works uh sum of V oh because it's not V it's um X for in we and same here X4 because we it has the color in the wi uh H Max is an empty sequence can that be true how can that be true oh yeah that's what I was saying that I was worried about because um because it's an iterator so you can't do it twice um but then I got distracted by rewriting this part that I kind of forgot about it to be honest but yeah um so as long as you cast it to a list is okay that's one of the caveat that you have to do and then that's pretty much it because you're just summing it minus the max it's the same idea um I mean this is a little bit slower because technically you're kind of scanning it twice so it's two Loops even though it doesn't look like it um I guess three of you kind of Max actually I didn't that was just a little bit lazier on my part but um but nonetheless you know uh yeah very easy to write but and in a way may maybe except for the thing uh you know it's just less ER prone right because you it's more expressive as to what you say as opposed to this ative um state full account um and this is the power of functional programming to some degree what did I do before Oh I guess I did it the same way before kind of different weirder State and before that I did more um I guess I keep track that way that's kind of cute uh but yeah um anyway those two ways are the ways that I have it now uh this is the kind of linear time linear space right because we have to kind of do this and also I mean even if we don't I guess technically you do iterators is it so linear space I actually huh I guess maybe not is it may not be linear space but SI I think maybe linear space anywhere no because it we return iterators and the point of iterators is that they're not but still I just meant yep never mind it is going to be linear space so yeah uh and you know this is going to be constant space if you prefer this way uh let me know what you think uh yeah that's all I have for today though stay good stay healthy to your mental health I'll see youall later and take care bye-bye
Minimum Time to Make Rope Colorful
apples-oranges
Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. Return _the **minimum time** Bob needs to make the rope **colorful**_. **Example 1:** **Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\] **Output:** 3 **Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. **Example 2:** **Input:** colors = "abc ", neededTime = \[1,2,3\] **Output:** 0 **Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope. **Example 3:** **Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\] **Output:** 2 **Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. **Constraints:** * `n == colors.length == neededTime.length` * `1 <= n <= 105` * `1 <= neededTime[i] <= 104` * `colors` contains only lowercase English letters.
null
Database
Medium
null
387
hi let's Sol today's daily challenge that is first unique character in a string so in this question we are given a string s and we need to find the first non- repeating character in it and non- repeating character in it and non- repeating character in it and return its index and if that character doesn't exist we have to return minus one so what is the meaning of the question so let's consider the first string that is lead code so here I need to return the index of the first non-re repeating character of the first non-re repeating character of the first non-re repeating character what is a non-re repeating character what is a non-re repeating character what is a non-re repeating character non- repeating character is a character non- repeating character is a character non- repeating character is a character which only appears once in the string right so let's see uh let's try to see what character appears how many times so it appears only once e is appearing 1 2 three times T is appearing only once C also once o also once and D also once so I can see that l t c o d right these are the characters that are non repeating out of them what is the first one uh first non- repeating character that is L first non- repeating character that is L first non- repeating character that is L so I have to return its index so zero is going to be my answer similarly if I take second test case love lead code here again we will check the frequencies of all the characters so for L you can see it's present two times here and here so two o is present here and here so again two V is present only once e is present four times this time T is present once C is present once and D is present once so now out of these I can see V T C and D these are the characters which are non- these are the characters which are non- these are the characters which are non- repeating and out of them what is the first one non- repeating so that is V so first one non- repeating so that is V so first one non- repeating so that is V so I will simply return two in this case so that is what the question is now let's see how we are going to solve it so um we are going to use hashing so I am going to take a map in which I'm going to store a character and an integer now you will ask why only character and integer because we also need the index as well as we need the frequencies but the catch here is you might take that as well you can take a pair ex inside of the map but we don't need to make this that complex so here the int represents index in this case right now I know that whatever character I want the index right I only want L which is non- repeating I want T which is non- repeating I want T which is non- repeating I want T which is non- repeating C non- repeating o is non- repeating C non- repeating o is non- repeating C non- repeating o non- repeating D non- repeating so I non- repeating D non- repeating so I non- repeating D non- repeating so I only care about their index and out of those which sh is the minimum index that I have to return so that is I'm very clear with now if I come to frequency part so because I need elements with who which appear only once right so I don't have to care about the frequency right I do not need the number of times that character repeats I only want to know that character already exist inside of the map correct so I know that if let's say I'm iterating in the string right this way so now let's create the map so I put L and L with its index so its index is zero then I will come to e so e is not present inside of the map I'll put this with what its index is one now I come to e again so what I will do this time is I will say e has e is already inside of my map so I'm going to mark this number with some other number let's say infinity in this case so that I know whenever I'm going to you know take the minimum of non-re to you know take the minimum of non-re to you know take the minimum of non-re repeating character Index this will be Infinity so definitely this will not give me an answer right because I don't have to do anything with this e so that is the basic logic so what are we going to do we are going to put the characters inside of the map and how we are going to put the character along with its index only if that character has not been present inside side of the map before so here in this case L was not present so we put it here e was not present so we put the index of e with it that is e um e colon 1 then e again appears so I will see if e is already present so then I will mark it with infinity that it is of no use to me right I don't have to deal with it at all because this is not a non-re all because this is not a non-re all because this is not a non-re repeating character right and similarly we'll keep moving forward 4 we will store its index which is nothing but 4 right 0 1 2 3 all right it's three then for C you can see it's four and for o it will be five for D it will be six right so now what I will do after creating this map I will simply iterate in this map and I will while iterating I will check which is the minimum index that is going to be my answer right that is the first non-repeating character of is the first non-repeating character of is the first non-repeating character of the string now what if all the characters repeat then what will happen so if all the characters repeat so let's say I have a string a BB and CC right so here for a with Lo with this logic we know that if we are iterating here I will store the index but as soon as I come here I'm going to store Infinity so I'll store infinity or similarly when we come here so we'll store B and its Index right and as soon as we come here we see B is already present inside of the map right so mark it with infinity similarly so this is the final state of the map right so now when I will go and try to iterate inside of this map so I will be getting the minimum answer is infinity only so if I get this answer that means that there is no non-re repeating that there is no non-re repeating that there is no non-re repeating character correct so I will simply return minus one in this case so I hope the approach is clear now let's quickly go and code it out so first things first I have to declare an unordered map here which will store care and int as I said int is going to denote the index and if the character has already appeared it's going to contain maximum value right so here we are going to use int Max instead of infinity right so uh this is our map and then I will start rating inside of the string I less than is do size and i++ and now I have to check right i++ and now I have to check right i++ and now I have to check right whatever character I'm currently at was it is it already present or not if it is already present then I have to mark it as infinity and if it is not then I have to Simply put the index so I will check if MP do find S of I right if it is equal MP do n that is this character is not present inside of the map then I can simply mark it as index otherwise the character is present so in that case I have to make it equal to Infinity right so that is all that we have to do here and here now I'm going to take an answer variable in which I'm going to store initially it will have int Max only right that is it's initially infinity and then we will calculate the minimum out of the all the answers right out of all the indexes that we have inside of the map so now we will iterate in the map and what do I have to check the minimum with answer and the second value of the map that is the index that we have stored so I'll say minimum of ANS comma it dot second so after this if let's say my ANS is not equal to int Marx right see if it was equal to int Max that is every value is infinity that means the answer is going to be minus one that is there is no non-re repeating one that is there is no non-re repeating one that is there is no non-re repeating character right so that condition we have we also have to check so here we simply um return if an is equal int max if it is return minus one otherwise return the value of the answer that we got so now let's quickly run it so it's accepted so basically this is how we have to solve this question and we are doing it in single iteration so the time complexity is going to be biger of n being the size of the ring and um space complexity as we are using an ordered map so the space complexity will be for that and it is going to be biger of NS SP
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
121
hi guys hope you're doing great our today's question is best time to buy and sell stock this is a very common question with interviews because it's a question which is quite complex to think about and listen to but has a relatively easier solution so let's get started say you have an array for which the ayat element is the price of a given stock on the I if you were only permitted to complete at most one transaction that is buy one and sell one share of the stock design an algorithm to find the maximum profit you cannot sell a stock before you buy one right so for example given this so this is the price of the stock on the eighth day and we can we need to find the maximum profit that we can make so which would be five because we can buy on day two when price is one and then sell on day five when the price is six so the profit is six minus one five and this is not seven minus one because selling price needs to be larger than the buying price because at seven you can purchase but you cannot sell right because that's the day one so that is not possible right similarly this so you can see that this is a constantly decreasing stock price right and that is why in this case there is no such point where you can buy and then sell it at a higher price at any point in time price on any day so that is why the maximum profit is zero right so this is an unsorted array and let's have a look at the various approaches that we can take for an unsorted array so please pause the video think for a moment have a look come back alright so this is relatively very easy because we don't really need an approach for this just a simple traversal problem right however we do need to think about what is the approach that we need to apply right so in such cases it's definitely helpful if you have seen the question before or if you've solved the question before to be able to get to the right approach in the interview so don't be panicked about there must be a thousand other questions like these who approaches I would not be able to think about in the interview so it's not like that the more you practice the better you get the more you practice if you see such questions you have a lot of processes of blood of approaches in the back of your mind which click at the time when you need them so no need to worry about so let's talk about what we can do here so clearly what we have to do here is we have to maintain you know a profit value right which we want to implement and we want to also maintain a value that stores the minimum price that we have seen till now right so because whatever is the minimum value that we have seen till now we will subtract that from the current price that we are at and identify that whatever profit I have been able to make till now is this profit greater than the profit I have made so it's basically similar to finding out max a max value in an array but with some conditions so once we get started with writing the code we'll get better okay so first of all as I said we need a min right let's just okay let us just initialize it with our max value because we want it to be updated the first time yet and you and the other one be profit so profit is let's say zero right now okay now let's start traversing through the prices array right so what we have to check first of all we need to update min right so we'll check that if min is more than prices of I it means that there is up another value which we have seen which is lesser than the min we were thinking is the minimum right so we want to update that so we say that okay then min equals to crisis off and that's it so we are done for this price of I that we have updated min with this so we cannot do anything else because basically we have kind of what this talk on this day because we found that this price is lesser than its price on other days right so we would prefer buying it on a day when it's prices the lowest right so this is done if not okay so if it is not less than the minimum price if you have seen that mean then we need to check for profit right so that is similar to max value as we calculate for an array that so we'll check that else if the profit that I have been making till now is that less than okay prices of I that is the current element because we know that it's not less than min so whatever profit I can make from this value minus min is that profit more than profit which I have recorded to know if yes then profit equals to this value prices i- methods okay then this is my prices i- methods okay then this is my prices i- methods okay then this is my maximum profit till done right so we just update it like that extra okay fine and then we just have to return the profit okay and we could add a base case that if prices dot length equals zero then we can just return zero because there's no way we can make any profit right okay let's see if that works oh that's weird sorry yeah the time complexity for this is o of n because we're just traversing the area once right the space complexity is o of 1 because we are not using any extra element apart from min and profit that's a constant right so I hope you guys find this helpful and learn the simple array traversal technique as well which does not involve any other approach apart from just using some logic and deriving the answer so if you like this video please like share and subscribe keep worrying and take attacks
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 5 **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. **Example 2:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transactions are done and the max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming
Easy
53,122,123,188,309,2138,2144
222
Hello guys welcome back record in today's problem which account complete re notes and this problem will be of ascendant problem and will not explain different problems solutions for the end died and will see the time complexity and scorpio s11 life even if you own youtube channel please do Subscribe Vishal Sharma To Compete With Problems All Right Knowledge Skin Problem Solve Problems Z1 Complete Penetration Counter Number of Units here in the Input Bhi Hai He Giver Narhat This Complete Penalty Shot Properties Back Liner Degree Holders This Incomplete Binary Tree Every Level Except The Possible The Last A completely failed and all the notes in the last level are for left as possible that can have seen it too much noise includes quotes is tempered glass live with rebels have in the a complete front and third last level should be given or lips in this case Here This Is That Will Also Appeal To All Left 101 3G Phone Lee Single Notes Present With Date Will Also Be Not Effective With The Star Left Side Show Women Don't Have Any Single Mode On Right And Left Already So ​​Let's Mode On Right And Left Already So ​​Let's Mode On Right And Left Already So ​​Let's Twitter Number Of Notes From The History From The Problem Simple And Intuitive Difficult Work Done In Return To Observe It Does Not Give You Nor Rossi Definition Clearly A Complementary Poems Kal Subah Toll Properties Begum Please Tree Hai She And Right Now Let's Understand The First And Will Explorer Different Problem Solution Party all night show in the giver noir of three aspects of complimentary no like na media the number of units and contented life is the giver and complete the thing 99 subscribe to the main aapke show total number of noir of this completely in it's going to be TOURIST TO H - MORE THAN 140 AND YOU WILL HAVE TO H - MORE THAN 140 AND YOU WILL HAVE TO H - MORE THAN 140 AND YOU WILL HAVE TO DIFFERENT ARE NOT PRESENT TO YOU HAVE NOT FOR THE ROOT WILL REMOVE IT DOES NOT HAVE NOT TO SUBSCRIBE TO 9999 SUBSCRIBE AND TOURS - 132 br7 TOURS - 132 br7 TOURS - 132 br7 That your boat here is only a constraint that two It is a complete very birthday gift with all possibility and women not having a blast liquid possibility that will not have no rights in the definition with all blast liquid not having no right to handle the and width complimentary and last not the question will give the answer will give The year result was the institute of the book of this of logic and one who did not present job may not directly apply this condition scientific and what we will do is twist utilize this condition for two years will start trusting you are not a good check left Height is let's tree height and right street will be this venues calculator left it will only left side that aapke n you find out if left sub normal and right side value calculator rights of trees and you will only right ans is ok yoni ko tight and at LEAST TO A LIGHT YOU CAN ACCESS OIL HEIGHT THAT NER HEIGHT IS ON THIS OCCUPATION NA HO IN THE COMPLETE CASHLESS CHAPTER COMPLETE BINARY TREE AND COMPLETE DAREFUL TREE IN THIS IS GOING TO BE EQUAL OK SIR IMMEDIATELY RETURN TOURIST TO-DO LIST 8 - ONE Who can return this way results 8 - ONE Who can return this way results 8 - ONE Who can return this way results for the means of but not to interest hall aa sakti users one time left side open time right side you two not need to visit this notes and 1000 subscribe hai inch ke is android a bird flu se one this is Not equal will be in what we can do it is will give winners will apply same logic will to next level down liquid match at point from this point to some sum node to this entry through the benefit of all subscribe returning from the more yes leaves And more branches of Godhead is this approach good moral for what are you doing this where going to monitor that your hazel sludge titration you are also calculating one more time it is the time complexity of and in this approach to * of complexity of and in this approach to * of complexity of and in this approach to * of a graduate is time complexity Women Need Not Wash And Software Doings Calling Two Functions To Calculate The Right Left Side Right Side Soft Will Fall Flat Settled On Left Side Notes Detend And They Calculate The Thing Will Go Deep Into The Right Side Of Notification Video Subscribe to Subscribe Times Aug 20th * Wrist Watch In This After Taking One From * Wrist Watch In This After Taking One From * Wrist Watch In This After Taking One From Sorrow And Condition Resident Evil Acts For Android Software Doing By A Given In This Will He Be Completed By Mid-2012 Embroidery President Of United Way Normal nfo Normal Traversal In The Tree of Knowledge Subscribe to that your time compiled knowledge is a certificate and right knowledge see memories and the time meditation for this flash light that your my wife looked wicked pass education wise and stupid love hundred percent ahead of fade and measure that Dashrath in this video you like it guys if you have different problem solution scooter comment tightening a comment many such twitter time line
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
1,909
Hello Guys Suggest Solve Another Letter Problem Which Name Just Remove One Element To Make The Are Strictly Increasing Listen Versus Prostitutes Is That The Young Men Or This Darkness Viscometer No. 9 This To Return True Facts Can Be Strictly Increasing After Removing And Return For Subscribing To Solve this problem subscribe element in president subscribe The Channel subscribe The Amazing 2011 250 grams paneer wwc2 1057 hua tha and editing c is remote 1000 se are will get steel engraving are listen for another example where does withdraw element points 151 string for example 231 does not Consider 12312 Nine Nidhi Free Mode On The Road To Does Not Strong And Effective Work To That 2320 Ton Steel Engraving Amazing To Remove The Last Moment To So Will Get 2018 201 9 Nikli Increasing Productivity Of Another Example 1238 Already Subscribe Must Subscribe Channel To And Comment That And Will Release Him With 0 That And Will Take Another Available Oldest And Will Release That With The Last Statement Of The Best Wishes Are Listen Vegetables From This And Salute For Ed With Five The First President Of The Year Celebration At Will Through Which Is The Largest Dam 999 Twitter The Amazing Last Current Element Prove Will The Phone 200 Hua Green Account Will Be Given Her And Will Destroy Gather Verses After 10 Loot Will Update The Last One Right Subscribe To Width Last Year When Will The Distance Cleared Stool Officer Will Return Minimum Of Account And Account License Equal To One So And It's True Than They Consider Increasing By Remove Withdraw And Tell I Will Write The Code For This Problem But Highly Recommended To Render Code For this problem neuron first and different country any problem or near you can see the question just listen to lax tak na dhandhe ko subscribe to ajay ko loot lo kar do hua hai ajay ko Kar Do Hua Hai Kar Do Hua Hai Kar Do Hua Hai Kar Do MP3 [ MP3 [ MP3 Ajay Ko Kar Do [ Kar Do [ Kar Do Ajay Ko Kar Do 9th Mein 100 Dashrath For This Video Guys IF I Learn Something New in this video and have tried to make more videos from the list ko problem aur consistently font and take n9ne kar do aur sunao show more hua hai ki a
Remove One Element to Make the Array Strictly Increasing
buildings-with-an-ocean-view
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).` **Example 1:** **Input:** nums = \[1,2,10,5,7\] **Output:** true **Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\]. \[1,2,5,7\] is strictly increasing, so return true. **Example 2:** **Input:** nums = \[2,3,1,2\] **Output:** false **Explanation:** \[3,1,2\] is the result of removing the element at index 0. \[2,1,2\] is the result of removing the element at index 1. \[2,3,2\] is the result of removing the element at index 2. \[2,3,1\] is the result of removing the element at index 3. No resulting array is strictly increasing, so return false. **Example 3:** **Input:** nums = \[1,1,1\] **Output:** false **Explanation:** The result of removing any element is \[1,1\]. \[1,1\] is not strictly increasing, so return false. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Array,Stack,Monotonic Stack
Medium
1305