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
227
hello and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 227 basic calculator 2. let's read the question prompt given a string s which represents an expression evaluate this expression and return its value the integer division should truncate to zero and you may assume that the given expression is always valid all intermediate results will always be within the range of a 32-bit integer within the range of a 32-bit integer within the range of a 32-bit integer note you are not allowed to use any built-in function which evaluates built-in function which evaluates built-in function which evaluates strings as mathematical expressions such as eval let's look at some examples so we have this string s which is 3 plus 2 times 2. so obviously we know from order of operations that we should do the multiplication um of these twos first right so we would multiply the twos we get a four here and now we need to add the three so that's how we get the seven that we need right so here in this example we have s equals three divided by two and you know this is really one point five but uh okay one point five but since we're truncating down it just becomes one so that's why we expect one is our answer here and for this problem you know it's going to be the same as the first one where we want to do the division first because that's order of operations if you don't remember it's pemdas so parentheses exponents multiplication division addition and then subtraction so we want to do the division first so 5 divided by 2 is 2.5 but since we're divided by 2 is 2.5 but since we're divided by 2 is 2.5 but since we're truncating down it's just 2 and then 2 plus 3 is going to be 5. so that's why we expect 5 as a solution there so this problem is actually one of the easier basic calculators um despite being the second question in the series it's actually the easiest one um it's also a medium question on leak code so before we think about how to solve this let's think about the most simple case here which is this that we have um you know addition so say we had you know three plus five plus seven plus two right in this case you know we don't have to worry about any sort of like multiplication or division all we can do is you know we can have our result you know it's currently zero and then when we get to a number we just add it to whatever the current result is and now it's three okay so now we're only adding here so you know we're not going to worry about um you know any of these signs and then we get to the five so we can add five to whatever the previous result is so we get eight and then we get the seven so this is going to be 15 and then we get to the two and then we're going to be at 17. so this is easy because we can simply just take our current number and add it to whatever our previous result was and keep going from left to right and the same thing is going to be true if we have minuses in here where you know this time all we need to do is subtract the current number from the previous result um so that means that you know we need to keep track of whatever our operation here is but what happens when you know we're working with you know a string like this now what we don't want to do is you know parse the string find all the divisions do them and then go through the string again ideally what we want to do is make one pass through our string and evaluate it from left to right but the issue is here is we're gonna see things uh in an order that might not actually be that you know order of operations so for example if we're going from left to right you know our current sum okay so we see the three so now we have a three here and then we see this five and we're gonna be like okay well we need to add because the last operation was an ad so we're actually gonna get an eight and then we're gonna get to this two and now if we divide because that last operation is a divide then we'd say four but we know that it needs to be five because this one needs to happen first so in this case what we need to do is we actually need to undo the last operation to fetch whatever value was last there so what we're gonna do is we're actually gonna maintain whatever the last number was and we're going to maintain what the current result is and the reason that we're going to do this is you know we get here and we see that we need to divide well we saw that we can't divide 8 by 2 because we'll get the wrong answer so what we need to do is to actually undo the um you know the previous number uh the previous operation that we did so what we need to do is we need to actually take eight and we need to say okay well we need to get rid of uh whatever the previous number was so from eight the previous number was three so we need to get rid of three uh and then we're left with five and now we do the division and we're gonna add that back to whatever the previous number was and now we should get our correct answer and we're going to do the same thing for um you know multiplication we need to undo that last operation so for example this one if we have let's just erase everything here if we have um you know three plus two times two so if we're going from left to right we're gonna see three first so we're gonna have three and then we're gonna see the plus two so now we're gonna have five as our results and our previous number is going to be 3 and now we see that we have to multiply by 2. again if we just multiplied this we'd get 10 which is not our answer that we expect so what we need to do is we need to take our current result which is the 5 remove whatever the previous number was so it's going to be this 2 and you know now we're left with um oh sorry the previous number was 3 sorry so that means that we're left with 2 now we can multiply that number by our current which is this 2 we get 4 and then we add back the um oops i don't think you'll actually be able to see that um then we add back this number here and then that's how we'll get seven so this may be a little bit confusing but what you basically need to understand is that we need to undo an operation every time we see a division or a multiplication because we're going from left to right and we're taking operations in a greedy manner so hopefully that makes sense if it doesn't when we write the code i'm going to walk through everything line by line and it should uh click in place it is a little bit hard to visualize but once you see the code and you can see how we're actually um writing it out it should make a lot more sense so i'm going to go over to the code editor now and we can actually write the code line by line and i'll explain what we're gonna do here so i'll see you there okay back to the code editor and now it's time to write the code remember that we're gonna go from left to right through our string here and we're going to do the operation as we go so to keep track of where we are we need an index pointer to keep track of our current um index also what we're going to need is we're going to keep track of the current number that we're working with we're going to keep track of the previous number that we're working with in the case that we need to undo an operation remember that when we have you know divisions or multiplications we need to undo what the previous operation was so we can parse out that number that we should have been multiplying with and we're going to keep track of our results which is going to you know basically just keep track of uh our results as we go through the actual processing here so let's define those variables we're going to say cur equals prev equals res it's going to be equal to 0 and we're going to keep track of the current operation which initially is going to be set to plus and the reason that we set it to plus is because the first number that we see you know going from left to right we're simply just gonna add that to our you know current results which is zero so like when we see this three uh you know we would just wanna like add a three so the current number we'd be working with is three so hopefully that makes sense on how we set up the problem now it's actually time to go through the while loop so we're going to say while i oops less than len geez less than len s what we're going to do is we're going to parse out the current character so we're going to say current character is going to be s of whatever the i index is and now there's three cases uh here we could have a digit we could have a mathematical operation or as you can see we can actually have a white space so let's handle the case where we have a digit and do note that it is possible to have more than one digit right it could be like 3 4 plus 32 it's not just guaranteed to be a single digit so we need to parse out the entire number and not just assume that it's going to be a single digit unfortunately that would make the problem easier but we can't assume that so what we're going to do is parse it out so we're going to say if the current character is digit we're going to say okay we need to parse it so we're gonna say while i is less than length of string and the current um character and s is oops is did jesus is digit then what we wanna do is we wanna parse so we're going to say cur equals curve times 10 plus integer of whatever the current value is and then we want to move our i pointer up at this point when this while loop breaks either we're at the end of the string or we have now encountered a non you know digit character in our string uh at this point actually we need to decrement our i pointer because let's think about it so we have the string three four plus three four you know we'll start at the three we'll see it's a digit and then we'll continue parsing so we'll parse the three then we'll parse the second three and then we'll parse the four and then notice that you know this while loop you know we'll still go i plus one and then we'll end up at the plus which is the case where this will break so the while loop will stop but now our i is still going to be here and actually in our while loop we're just going to have a global increment of the i so we would actually skip over this one when the i gets incremented at the end of the loop so we actually want to reset it back down to four so we cannot interfere with that global um you know i plus one at the end of this while loop you could just do it separately but just keep things nice and concise i like to just have one global and then i will just decrement it manually here so that's the reason we have the i minus equals to one uh hopefully that makes sense so from here what we need to do is we now need to apply whatever the previous operation was right so if we parse this 2 we need to apply you know whatever the previous operation was to whatever the previous number was because we've now parsed out the number that we're working with so we're going to say if cur operation is equal to a plus then what we want to do is we want to say okay we're simply just going to add the current number to our results and we're going to say that the previous number is now our current number right makes sense otherwise if the current operation is going to be a minus then instead of adding to the result we simply just need to subtract the current number from the result and now our previous is going to be minus curve right uh because obviously we have a minus here so now we get into the more complicated cases where we have the actual you know geez i can't type today uh we have the actual multiplication so how do we do this well we remember that we need to undo the previous number so let's remove it from our operation from our result and we're going to undo it by subtracting the previous from the result and now we're going to add to the result the correct number which is actually going to be the previous number times what our current number and then we need to set our previous number equal to whatever the current number is times whatever the previous is to account for that multiplication so that's going to be how you can handle the multiplication case and the last case for us to do is simply the division so again we need to get rid of whatever the previous calculation was because it shouldn't have been applied because obviously we have not respected the order of operations now we need to undo it so we can apply it correctly so we're going to again subtract from result the previous value and then we're going to you know increment result correctly this time and we're going to say int of prev divided by curve and the reason that we use int here instead of the you know integer division is in python if you have negative numbers here and you try to use the you know uh integer division it will actually round incorrectly and you're going to get the wrong answer for this problem so you actually need to use int here on a regular division operator to get it to truncate correctly otherwise like i said you're going to get the wrong operation if you don't believe me you can try it with the um if you get rid of this int and then just do prev divided by curve but you're not going to get the right answer so um yeah you need to use in here be careful about that and then again we're going to say prev is now going to equal to prev divided by curve so pretty straightforward and then now that we have processed our number um you know it is no longer the current number that we're working with so we simply need to reset it back down to zero because now we have processed it we obviously don't want the next number we see to still have remnants of whatever the cur the last number was because that number is now going to be housed in prep so current needs to be reset back down to zero otherwise you're not going to get the right answer so now we've handled the case where you know it's a number remember that there's two other cases there's going to be a white space case and there's going to be a mathematical operation case so what we're going to do is we're going to handle the mathematical operation case because in the white space case we don't want to do anything we just want to increment our i and continue through the string so we're going to say else if the curve oops yeah the current character does not equal to a white space then what we want to do is we want to say the current operation is going to equal to the current character and that's really all we need to do we just need to increment our i now and you know we're going to continue through the while loop and essentially this will process out the string and it's going to do all the calculations as we go and at this stage all we need to do is simply return res and let me just make sure i haven't indented this correct incorrectly okay cool so if we submit this we see that our function is going to work and our code will be accepted so what is the actual time and space complexity here well like i said we're only going from left to right through our string so this means our time complexity is going to be big o of n right we only have to go through the string one time from left to right so this is going to depend on the size of the string which means it's going to be a big o of n runtime what is the space complexity well we've actually not you know used the stack like some other solutions might and all we've allocated is just constant space you know pointers here um for our calculations so this is actually going to be a constant space solution because we haven't actually defined any extra data structures for this problem so this is actually going to be your most optimal solution there is one where you can use a stack and it is a little bit simpler to write the code for but your interviewer is most likely going to want you to do it in constant space so this is definitely going to be the solutions that you want to go with so definitely want to know um that's how you solve basic calculator 2 hope you enjoyed this video if you did please leave a like subscribe to my channel and leave in the comment section below if um you want to see any other videos just let me know the problem number or any topics you want me to cover um just interviewing basics in general um and i'll be happy to get back to you just let me know what you want to see and i'll do my best otherwise have a nice day and bye
Basic Calculator II
basic-calculator-ii
Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "3+2\*2" **Output:** 7 **Example 2:** **Input:** s = " 3/2 " **Output:** 1 **Example 3:** **Input:** s = " 3+5 / 2 " **Output:** 5 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces. * `s` represents **a valid expression**. * All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`. * The answer is **guaranteed** to fit in a **32-bit integer**.
null
Math,String,Stack
Medium
224,282,785
559
so hey guys what's up in this video we are going to see about the maximum depth of the generic tree right so how to find the height of a generic tree so if you are new to my channel do hit like share and subscribe to my channel and if you haven't watched my previous videos on generic tree i would highly recommend you to please watch them so as to develop an intuition about solving this problem now let's go and code up the solution now we know that in basically a binary tree we have at most two childs so how do we find the height of this we will recursively call for the height of the left child that is this and recursively call for the height of the right child that is this and whoever has the maximum of them we'll choose that one right and we'll add one to it and return it to the root as a simple idea that we followed on the binary tree right here in the generic trees we don't have at most two we have n number of child nodes right so what we can do is similar is the case and similar will be the logic we'll be finding the maximum height of each of these childs whosoever will be the maximum one will be adding one to it and be returning to its root right it's parent right so here when i'm at one i'll recursively call for its chart that is three two and four i'll say that a3 tell me what's your height it will say my height is h1 similarly 2 will say my height is h2 and l4 will say my height is h3 so what will be the height of 1 it will be the maximum of h1 h2 and h3 whosoever will be the maximum of these three right i'll select that one and i'll add one to it and i'll be returning to its root that is one similar is the case for three right when i'll recursively call for five and six right five will basically check for its left it's it is null right it is done similarly six is null sorry the right of five is null right so if it is null we'll write a condition here that if left or right is null right that is essentially if the root is null when i'm calling for 5 right it will call for your subsequent childs and what it has as a child it has null because it don't have any child right so when it call for null i'll simply return 0 right it will return 0 essentially right and this will return zero and we have discussed here that will we have to choose the maximum of the ice that the child returns right what the child returns zero returns our left child of the five returns zero right what is the maximum of them that is 0 i'll add 1 to it and return it to the parent so basically 5 will have a value of 1 similar to the case for 6 it will also have the value of 1 that is height of 6 will be 1 now 3 has called for its child height of the child that is 5.6 the child that is 5.6 the child that is 5.6 what these two guys will return one and one i will choose what the maximum them what is the maximum one and one that is one right i'll add one to it and i'll return so this will have two because one and one the maximum of them will be one right and i'll one add one to it and i'll return that is why we had two here similar will be the case for this level right so if you calculate for this you will find that 2 is maximum here and we want 1 to it and we have 3 this step and this answer that we have that is 1 has a height of 3 is depicted in this solution as well right so basically this is the solid question that is given on lead code and it has as for the root or height of the root right so i have explained you the example that we have discussed exactly here right so this is basically this example that is given here and it has a height of three so we have understood how it actually works with the help of recursive call that we make to its child and ask for that height and then we choose the maximum of the heights of the child and add one to it and return to its parent right so that's a simple idea we follow now let's go and code up the solution so now what we'll do is we'll be calling for each of its child and asking them what is your height right and we'll be choosing the maximum of them and we'll be adding one to it and return right so let me initialize the answer variable as zero itself right i'll traverse through the values or the root children's right that is stored in the vector right that is children right here it has a property of children right the root has a property of children and i'll be iterating through it like so and i'll ask each of its children that is x that is right what is your height right and the height will get by simply calling here and we'll assume that it returns as the value or the height of the child x right once we got the value of the height of x right we'll be choosing the maximum of them like so answer and the height that we got from the child and once we find the maximum all of them will return one plus the maximum of all the heights that we found in the answer variables now let's give it a shot and see whether it works or not i think this should work let's give it a summit and see whether it works or not okay it's a runtime error because we haven't handled the best case when you just handle a base case that if root does not exist right just return zero right that's a simple case we need to consider now let's initially consider this case right like so and see whether it works or not yes it does let's give it again and see whether it works or not hope so this will do yes it does hopes you guys enjoyed the video and learned how to intuitively have a recursive function so if you like my video like share and subscribe to my channel till then stay safe stay tuned
Maximum Depth of N-ary Tree
maximum-depth-of-n-ary-tree
Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. _Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._ **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** 3 **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** 5 **Constraints:** * The total number of nodes is in the range `[0, 104]`. * The depth of the n-ary tree is less than or equal to `1000`.
null
null
Easy
null
1,022
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you're not like the video please like it subscribe to my channel so that you get notified when i post a new video so without any further ado let's get started so uh the problem is you sum of root to leaf binary numbers we are given the root of a binary tree where each node has value zero or one so it's a binary tree it will have value zero or one each root to leave path represents a binary number starting with the most significant bit what does this mean that root to leave path will represent a binary number with the most significant at the start that is if this is root to leave path then this is the most significant bit and this is the least significant bit right for example if the path is this then this could be represented as zero this is the most significant this is the root and this is the leaf which is least significant and in if you convert this to decimal this is 30. so for all leaves in the tree consider the number represented by path from root to that leaf so uh all these from root to leaf these all are the different binary numbers and we need to return the sum of these numbers so this is just the like just the constraint so let's see the input this is the test case given to us so this is root and all these are leaves so there are four leaves means there will be four binary numbers right so if you see this is one binary number one zero one is the most significant and zero is the least significant then the other number is one zero one another number is 1 0 and another number is 1 so these four are the binary numbers if you see this is a 4 this is 5 this is 6 and this is 7 in decimal so if you add all these you will get 12 and 11 uh so this will be 20 2 i think sorry this is 11 and 15 and 70 22 so the output if you see the output will be 20. so let's see how we'll approach it we'll discuss the brute force first so see uh it's very easy to get the you know this binary number now we'll start from root where we have a let's say answer string in which we will store that binary number which we are getting initially it will be empty we go to root we add this one in this string then we go to this left side left child of the root zero we add this in the string so the string will become one zero then we go again to the left side of this so we will get to this 0 and then we will add this to string again and this so now we have reached the leaf node we will check what is this binary number we will convert it into decimal and we will have a sum variable let's we have to like this sum variable will be initialized to zero and when we reach to this leaf we will convert this binary string to decimal and we will add that decimal number in this so this will be 4 so some will become 4. this is one approach what is problem in this approach it's it will give correct answer nothing wrong in the approach what we are doing is we are finding the string and when we reach the leaf node we convert it into binary to decimal we are doing this now see reaching to this will be of end time if we see from root to leaf so now this approach is absolutely correct nothing wrong with approach just one thing that whenever we reach to every leaf node we have this binary string and we convert it into decimal so then we have to every time we have to convert it into decimal so that will be of some complexity right so uh at each leaf node see at each leaf node you will be doing the same thing you will be converting binary to decimal what if along with the traversal along with a traversal only we uh we or calculate the value which we need to add in the sum that means when we are traversing this binary string uh when we are going through the tree then only when we reach the leaf we have the value 4 which we just simply added into some into the sum so let's see how we'll do that so see now what we are trying to think is that we were earlier what we were doing we were going through the tree uh till from root to leaf and we were calculating the binary we get the binary string and then we converted into decimal this was this we were doing but then we think of that okay when we are traversing only then only we will find the value right so now let's see how we'll do that let's take a variable sum is its initialize to zero see we will be starting from root we'll start from root so we know that okay root will be it will be like this will be zero index only in the string and how do we convert a binary string to a decimal see if we have something like this binary string we do this in texting and we multiply this 0th index 2 raise to power 0 and we multiply it with this value 1 similarly we do 2 raise to power this index and we multiply it with the value and similarly we have 2 raised to the power this index and we multiply it by this value so this is how we calculate the dash binary from decimal same thing we'll be doing same thing let's see how just make this clear that whenever we get this value this is the zeroth bit and zero one is calculating using uh is converted using this now that two raised to power is zero since its zeroth index so it will be two raised to power 0 into whatever here it is value and 2 raised to power 0 is 1 so it will be value only right see now we are going from this we have 1 so what we will do is we will be doing every time value will be value into 2 plus the root value see how initially we will be taking value as 0. so what we are doing first of all value is 0 into 2 plus root value is 1 so over here we are just simply taking the value as we saw that whatever we add we are adding at the end you'll understand let's uh turn in first so root value is one so it will become one value will become one now this value will be passed to the left child value is 1 now so we will calculate this val again for this 0 so value will be value which is 1 into 2 plus the current value root which is 0 so see this will become 2 plus 0 2 you will be thinking that why we are taking why we are not multiplying this with the 2 because uh we are adding c this will become one zero will be added in the zeroth index the least significant bit if we convert to decimal we simply just add it we simply just add v the value because it's 2 raised to the power 0 2 h plus 0 is 1 so that's why we are taking only value here like we are just simply adding we are not multiplying it with 2 i hope you understood now this value becomes 2 so this will again pass to the next child and over here we will get we will again calculate this value for this 0 so value into 2 value is 2 into 2 plus the current value current root value which is 0 so this will become 4 so you see we have traversed this we reach the leaf and also along with it we calculated our value which will be added to sum so 4 sum will become 4 similarly over here when we will when we uh right now what we did was we have uh from this root we go to left child now we will go to the right side so first of all from here you will go to the right side so over here it will be value is 1 into 2 plus the root value is this 0 right root value is 0 so this will be 2 then you will go here and for this value will be 2 then you will calculate value here so it will be 2 into 2 plus 1 is the root value so this will become 5 so see 1 0 1 it's 5 right so you will add this 5 and you'll get 9. similarly you will go and you will do for this and you will go and do for this so what's the logic behind what's the uh thinking behind this is see every time we have initially one then we had one zero then we have 1 0 so whenever the new bit new number is adding first of all it's adding at the lowest bit lowest significant bit right that is one thing so since it is adding at the lowest significant bit we will just simply whatever the current value is we will add that root value to it just simply add or you can write it 2 raise to the power 0 also but 2 raised to the power 0 is obviously you know 1 so that's why we are not writing it root value now why we are multiplying this with value because we this is we are doing left shift see why we are multiplying it with two if you know about left shift uh one zero like if this is uh let's say we have this number we have and 0 will come and then it will become 100 so what we are doing is we are doing this numbers left shift that this position becomes empty so we are shifting each bit by one position to the left and then we add the zeroth number which comes at the lowest uh this lowest significant bit so since we are doing left shift means to uh to shift uh the bit by one so if we do this like this is a current number and we do it's left shift by one y by one because left shift if x is left shift by one it means 2 raised to the power y into x so that means we are we over here what we are doing we are this is our x and this is our y so 2 raised to the power y means 2 raised to the power 1 into current number right so what we are doing we are multi we are the current number is multiplying by 2 and like this is the current number we are multiplying it by 2 why are multiplying because we are doing left shift so that this position becomes empty and then we add the whatever the current root value at that position so i hope you understood what i am trying to tell like i am trying to tell why this formula we are using over here so this is for the left shifting so that the position becomes empty and this is we are uh adding that bit so it's value we are adding so let's see the code quickly once if you have any doubt let me know in the comments i know it's bit confusing for someone who doesn't know about left shift but again watch the video and do some research on left shift you'll understand so this is some root to leaf form function and over here we are given root and we have taken a value which is initially zero if the root is not null if the root is null will return 0 otherwise we'll calculate the value and if the if it is the leaf node like this will means this means that it is leaf node so if leaf node is there just return this value otherwise do the left call pass the value and do the right call pass the value and we will add them whatever the result will come from these two for example from this end um from this side we got four and from this side we got five so we'll do four plus five and we'll pass nine here similarly from this side you will get a 6 and from this side you will get so 7 and then you will pass 30 right so i hope you understood it let's discuss the time complexity so see we are calculating in the earlier approach we were uh calculate we are converting binary to decimal every time so that was not efficient so over here we are calculating the value along with the traversal so the time complexity will be o of n and the space complexity since we are not using any extra space just the recursive calls are there but since uh there is a recursive stack so for that max calls at a time will be o of h where h is the height of tree because at a time either left call will be there for any level or right call will be there for any level right that means uh if you see uh let's take if this is the tree right like this is a tree if we are going left so one recursive call of left other recursive call of left and then so this is the height number of calls if height three is the height three calls will be at max and the recursive stack so i hope you understood the problem if you like the video please like it subscribe to my channel any doubts please let me know in the comments and i'll see in the next video thank you
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
930
hey what's going on guys it's ilya bailly here i recorded stuff on youtube chat description for all my information i do all liquid problems uh make sure you subscribe to this channel give me a big thumbs up to support it and this is called uh binary sub-race with sum uh binary sub-race with sum uh binary sub-race with sum in an array a of zeros and ones how many non-empty sub-rays have some how many non-empty sub-rays have some how many non-empty sub-rays have some s for example we get this array right here as is 2 output is 4. the force of rays are volatile below node the length of this array is less than or equal to uh thirty thousand uh s is greater than or equal to zero and is less than or equal to the length of this array a the elements in this array are either zeros or ones um we can solve this problem using sliding window approach uh basically we got two pointers i and j whatever uh we try to extend the window we got like a window like a sliding window right we got a window and we try to extend uh the size of that window as big as we can um go for it first we implement the helper method helper um and a an array and as you can think of s as the capacity for example we got a tank right like a fuel tank and we try to use all this capacity available in the case when the capacity is less than zero means uh that end is empty there is nothing to do with that we return zero otherwise um create two variables the first one i is zero uh result is zero next create the for loop into j is zero j is less than the length of this array j plus at each duration we subtract the value at the position of uh j in this array from the capacity s minus equal um a additional j in the case uh when the capacity is less than zero the tank is empty we are return we fill the tank we add the value which is the position of i and increment i by one we move i to your right and we keep doing that until um tank is empty keep filming this tank uh also calculate the result we say uh j minus i plus one and finally return the result that's the whole problem right here return uh the difference a and s minus uh l4 helper a and s minus one the difference uh you can think of that as a j pointer and i pointer the difference let's run this code accept it good let's submit the time complexity for this problem is linear big of n uh space complexity is constant we use right here two variables and right here one variable yeah thank you guys for watching leave your comments below i wanna know what you think uh follow me on social medias i do all liquid problems again uh follow me on instagram i'm on snapchat and i wish you all the best bye
Binary Subarrays With Sum
all-possible-full-binary-trees
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0,1\] \[**1,0,1,0**,1\] \[1,**0,1,0,1**\] \[1,0,**1,0,1**\] **Example 2:** **Input:** nums = \[0,0,0,0,0\], goal = 0 **Output:** 15 **Constraints:** * `1 <= nums.length <= 3 * 104` * `nums[i]` is either `0` or `1`. * `0 <= goal <= nums.length`
null
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
Medium
null
1,546
uh hey everybody this is larry this is maximum number of non-overlapped maximum number of non-overlapped maximum number of non-overlapped things sub arrays if somebody goes to target uh this is the q3 of a recent contest so this is another prefix sum problem uh the thing to notice is that you want to get you know for the prefix sum uh so the two things right one is greedy meaning that if the multiple uh like let's say you're at this index on a comma between uh and they're multiple paths to the target 10 because they're negative numbers uh you want the shortest one because you want them to have the most non-overlapping so therefore you want non-overlapping so therefore you want non-overlapping so therefore you want the shortest one right so that means that you want to get the one that's closest to you and then from that you could think of it as um longest uh longest path in the dag and where an edge is from every um sub arrays which equals to target right so if there's a six then there's a path from before five to one there's a path from four to two and so forth um and there's also one from apparently three to all this stuff uh but then as a result using dynamic programming um you can do this calculation and get the most overlapping from that as uh by the reduction from the longest path in the dag so this is my code i keep a prefix and this is linear because everything is you know we only look at each node once uh and we this is constant time um yeah uh so basically we keep a running sum for the prefix sum uh we look at the best you know if nothing else we don't add a segment so then we just do this thing where we take the best from the previous index otherwise if we find our targeted prefix sum in the prefix we just take that plus one or the best of whatever we have right now and then we update the prefix sum of the running sum to the current index because if it already exists you want to move it to the latest as possible if it didn't exist then just set it anyway um and that's pretty much all there is to this bomb and you could watch me solve it live next all right you hmm that's not quite you
Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
find-the-quiet-students-in-all-exams
Given an array `nums` and an integer `target`, return _the maximum number of **non-empty** **non-overlapping** subarrays such that the sum of values in each subarray is equal to_ `target`. **Example 1:** **Input:** nums = \[1,1,1,1,1\], target = 2 **Output:** 2 **Explanation:** There are 2 non-overlapping subarrays \[**1,1**,1,**1,1**\] with sum equals to target(2). **Example 2:** **Input:** nums = \[-1,3,5,1,4,2,-9\], target = 6 **Output:** 2 **Explanation:** There are 3 subarrays with sum equal to 6. (\[5,1\], \[4,2\], \[3,5,1,4,2,-9\]) but only the first 2 are non-overlapping. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `0 <= target <= 106`
null
Database
Hard
null
1,689
in this video we are going to partition a decimal number into different dc binary numbers so first of all what is a deci binary number so a number is a dc binary if you can if the digits are themselves just binary that is they consist of either 0 or 1 and we will ignore the leading zeros so no need to write that for example 1 0 1 this is a dc binary number although we will read it as 101 and not the binary value which is 1 plus 4 that is 5. so it's not 5 but it's 101 but its digits are 0 and 1 and we will not generally write like this leading 0s so but that does not make a difference in this case for our case so uh we have to make this number using dc binary numbers so for example if we have let's say 2 3 4 then we can write it as sum of 1 plus so when we subtract 1 from this we get 1 2 3 again subtract 1 we get 0 1 2 so these 2 sum up to 222 12 is remaining so again we will add 1 so plus 1 and then we subtract it's 0 and this is 1 so next we will add 1. so if you sum these four numbers since these four uh dc binary numbers you will get 234 so in this case we will return 4. we have to just return the numbers and not the actual values just the count similarly let's say we have this value 82734 so we have to just add a decimal value just subtract decimal values which are formed from 0 or 1. so if none of the numbers are 0 zero then we will subtract all the ones our goal is to quickly reach to zero we have to find the minimum such value maximum what would be we would keep adding 1 in fact so you can keep adding 1 so you will get maximum but in this case the target is minimum so we will try to reduce all these numbers to 0 we have to reduce all of these to 0 so our goal should be to subtract the maximum possible value so if we subtract 1 it becomes 7 1 6 2 3 again subtract 1 now it's 6 0 5 1 2 now you see there is a 0 here so uh instead of 1 so whichever digits are 0 make that 0 because we cannot subtract any number greater than 0 from this so 1 0 uh 1 of course we can subtract 1 from all of these but our goal is to take the maximum such possible value so if five digit value is possible then we will take that if there are leading zeros then we are bound to take a smaller number of digits now again this is 5 0 4 0 1 so now 2 0 so 1 0 1 4 0 3 0 now 1 0 now it's 3 0 2 0 again 1 0 so 2 0 one zero next one zero and it's one zero next subtract this number itself one zero and you get zero so this is 1 2 3 4 5 6 7 8. so if you add these 8 dc binary numbers you will get 8 2 7 3 4 and the order does not make a difference so you have to bring all those numbers to 0 so whatever is the maximum digit so you have to subtract at least 8 times from this to make it 0 you cannot subtract 2 from this because 2 cannot be part of deci binary number so you have to subtract a bigger value consisting of 1 at this digit whatever digit this 8 is the maximum digit 8 times at least so in this case the answer will be equivalent to the same maximum value so this the order of digits does not make a difference so let's take the same digits 8 two seven three four but now we will take two seven eight three four same digits just change the places so that we get leading zeros so one it's one 6 7 2 3 1 0 5 6 1 2 so if you compare 0 5 6 1 2 digits remain same just they are changed in the same order so uh here we had taken this uh one zero one so now zero will come in the front zero one so you can forget the zero that does not make any difference and here also again we are doing the same thing so maximum digit is at third place so if you see third place it's getting reduced one each time so other digits will become 0 before 8 since 8 is the largest so whenever they become 0 we put 0 in the dc binary numbers there as simple as that so now it's 4 5 0 1 so again this is 0 so it's very simple 1 0 1 again 3 4 0 so this maximum is reducing by one time and it will take eight steps and before that all the other digits would have already become zero this is the maximum so clearly the answer is whatever is the maximum digit so our goal reduces to find max digit in a decimal number so this question is equivalent to that so how can we do that just iterate through all the digits and keep track of maximum so it will take order of uh if number of digits is d so o of d and if a number is number itself is n the number of digits is order of log n so it's just a matter of notation if you are writing in terms of the number itself so here n denotes 27834 then it's login and if you are talking about number of digits so d is in this case five digit number so it will be of d both are equivalent so now we all know how to do that you even there are ready-made functions in all there are ready-made functions in all there are ready-made functions in all the major languages to find the maximum digit for example in c plus first we have max element and we pass a string to iterators so first is s dot begin if this is s and then s dot end and then this will return the character and then we will subtract a sky value of 0 to get the actual digit or we can just run a loop or till this number is greater than 0 and take the units digit or iterate over these characters if it's in the form of a string so you get the idea so now let's write the code in java c plus and python so you can go through a few more examples and you can go to the hint in fact gives you enough clue so let's keep track of maximum int max is equal to zero and four so dot get confused with this max variable this is the variable max underscore and this max is the function and let's try so let's write 82734 so this seems to work let's submit and the solution is accepted the same thing in java and python if you want you can also try that other thing the ready-made function and this solution is also accepted now let's write the same logic in java and python so here we will write a loop into i equal to 0 i less than n dot length plus i uh and it should be math.max and it should be math.max and it should be math.max and n i n dot care at minus zero so let's see so i think c is small care at and this seems to work so let's submit and the solution is accepted now the same thing in python so in python we need to we cannot directly subtract two characters we need to explicitly get the sky value using this overd function and now we will return the max and the solution is accepted in python also
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
146
hi guys in this video i'm going to go through this little 146 uh lru cache so we need to design a data structure uh that constraint of a lyu cache so um we need to initialize the lyu cache by the capacity and also we need to write a function get so we need to get return the value to key if the keys already exist otherwise if this it does not exist with the negative one and also um we also need to write another function put and what it does is update the value of the key if the case already exists otherwise we push a new key radio pair to the cache if the number of keys exceed the coupon so uh if the number of keys that sees the capacity we have to remove the least recently used the lrc key and the function that we implemented the getting function as the put function must be run uh on a big of one average time complexity so immediately that tells me that we need to use the hashmap or dictionary to implement those operations because if we use a list they're gonna not that's gonna take uh more than uh the dpo one so let's look at some example in here so um we have uh this lru cache and so we first initialize the capacity so we have the capacity of two and we push um the two uh key value pair uh one and two and after we push them so you can see uh they are there in the dictionary and they were refreshed let me get uh get the data by input the key of one so we enter the value correspond to that key and then we insert so immediately when we fetch the data for and then for the one month this pair and then that becomes a the most recently used and the tutu becomes the lru the least recently used um pair and so when we subsequently push another pair and the lr you can get deleted as you can see the lru that of 2 is getting it because we have to constrain of capacity of 2 that's why we can only uh save the pf2 that's why we subsequently called the key of two and it's no longer there and then at the same time after the pair three get pushed in and then the one becomes the lru and when we insert another pair and then the one or you get removed from the list at the same time so when we get from for one month it's no longer there and when we get from three so it's still there get from four still there and this question was uh asked by uh well very popular for microsoft and other companies so um so let's dive into see how can we implement it we need to use a duplicate list because the problem with um with the dictionary is only um there's no ordering for the elements in the dictionary so in order to implement the ordering we need to use this uh duplicate list and so compared to the traditional linkedin list there is a two-way linkedin list there is a two-way linkedin list there is a two-way two-way links and one is the prior two-way links and one is the prior two-way links and one is the prior links to the prior and another one is the next link to the next note and also it has a value um we also have the key as well uh in addition to this uh additional to the image so we have basically we'll have a dictionary so a dictionary and the key is going to be the key is going to be um yeah the key is gonna be the key and the value is gonna be the w the duplicate length note so let's implement that okay and we need to uh initiate a new class so it's gonna be called the w link node and we need the init function and uh we need the key we use the default key will be zero the value will be 0 so um we need is the self dot key and self.value key and self.value key and self.value is value and this is going to wait it's a two-way and this is going to wait it's a two-way and this is going to wait it's a two-way linkage so self-dot graph equals to none at the beginning i'll just uh it's just a initialization we will put the connection uh in the lrc cache uh cost uh and then the next it's none as well so and uh for and then now we can jump into um so again this is a dl note it's for capturing the ordering uh the priority of the note of the key and key while pair so self.gap capacity self.gap capacity self.gap capacity and then we need a dummy node self dot dummy then we had equals to um a new node and uh the key it's gonna be one zero and it doesn't really matter actually just a dummy uh so basically the head is capturing everything uh more recently used and the tail is capturing the carriage capturing the release recently used so every anything is close to the head is more it's recently used most recent and the note is close to the dummy tail it's gonna be the least region so and then we all the nodes will be um stay in between and then we can see the priority and the frequency of the being used which one is most recent results on this region so tail and then we put the connection dot next is equal to the tail and uh detail dot press equals to the head okay so um also we need these two functions to be filled out as well yeah so we'll figure out these the two functions later uh these three functions um the get function yeah so what it does is we turn the value of the key if the characters already exist otherwise it's between the negative one so um how do we do that to check if the key is already there so um if oh yes also we need a hashtag self dot uh cash sorry look hash is cash dick that so if sell stick dot get key uh if that's not none i mean else means it's not all right we probably don't need this one anymore so ours means is none the key does not exist and for this function noise just some helper function that we will figure out later put in the cache um yeah we know the scroll here okay so let's pause this as well so i will throw out this function later um yeah so if the key exists and how well we need to update right update that node so we need a node to the update to update and that is just that node right because again so the value of the dictionary actually is a note and update most region bring that note so after we get information at the value for that note and we need we update the free i mean the that note becomes the most frequently used because we just used it right so let's update the uh update that at the same time we need to return the value of the node yeah so we need to see this key is there update here the nodes will be updated also we update that to be now it's most recently used let me update it and then return the value okay perfect so yeah so this is the get function and now it's the put function and um so we have to update the value of the key uh if the key authority exists otherwise we just insert it and also push out the lru so this is the rule for this function um so first thing is to check if the keys already exist not so uh same thing right same if statement else i mean and then we need to check the capacity we have to ensure if yeah i use the lens with the length of the cache dictionary is greater than capacity and that um we need to push out um the lru i will fill up all these if statements later on so let's get this first so now uh we are um pulling so in this statement it is where uh the keys already exist right so in that case uh updated similar to this part so uh node will be updated and same thing in here and also but uh we instead of returning we just update the data value dot well it comes to the body so that's how we update the value and at the same time oh sorry so it can call this function called self see listen yes and this one is already in this dictionary so we don't have to worry about that anymore um yep so that's that and um otherwise it is not already existed create new node it goes to uh dl here node and uh in key and value it's just the input let's give it a nice keys key row is value so we create a new node and also let me do it that dictionary thing so dictionary dot key is equal to the new note yes so um and then we insert right so we will throughout this uh function later and we will press this one is newly in newly created so that's why we are most recently used cache right so um we will do a self dot insert means that it's just inserted just right beside right next to the dummy dot hat because it's most recently used so uh insert the newly created note okay so uh at the same time if we checking the capacity that's greater than the allowed capacity uh what we need to do is to remove so we've got the no dot let's know to remove and it's gonna be just right beside the tail it's gonna be yourself dot dummy tell top craft seven um yeah at the same time you need to uh pop it off from the dictionary so excel for cash take dot pop the key that's why we need to save the key in this uh dl note and itself dot remove node it's the noto remove okay good so um now i mean the two big function has already finished and now we need to um finish this three helper function so insert basically we reset it to um to just right beside the dummy hat yeah um so it is uh itself so it's a no top next is equal to um dot mix this is equal to the dummies let me hide itself right because we basically insert it in the middle and then self dot dummy hat dot next dot path is equal to the note so he's inserting between on the other side and oops yes so that's how we insert it uh this is your function and then uh remove we remove from the w tail um yeah so node to remove have a pref 10 okay good yes and stop next time equals two that should be next time go prep and craft can well so basically we just um removing from the middle and then now we do this update most reason so basically we have the uh after we have do these two functions is this um let's utilize them so we need to be moving first and then we need to it and that will become the most recent okay i think that's pretty much it yes it works and uh yeah it looks okay um yeah that's my solution to this uh nicole problem 146 using the dictionary also the double doubling note and i hope you enjoyed it and if you do please like and subscribe and hopefully i can see you next time in the videos thank you bye
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
392
hi guys welcome to algorithms made easy today we will go through the day 9 problem is subsequence please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a string s and a string t check if s is a subsequence of t a subsequence of a string is a new string which is formed from the original string by deleting some or none of the characters without disturbing the relative position of the remaining characters that is ace is a subsequence of abcde while aec is not applying this to the examples we can find out the result there are a few boundary conditions or constraints also given with this problem there are different approaches for this question let's go through one of them the two pointer approach taking a first example we will take two pointers initially both will be at the starting point and we will see if these characters match as they do we shift the pointers one position for both the strings and now let's compare these two characters as they do not match we will move the target string pointer ahead as these match we move both the pointers ahead we continue it till we reach the end on both the strings as we have reached the end for string s and t and all the characters have matched from s in t we say s is a subsequence of t formulating an algorithm from what we saw previously let's consider string s and t and we want to find if s is a subsequence of t if s is empty or null we simply return true otherwise we initialize a variable match index with -1 we then iterate over each with -1 we then iterate over each with -1 we then iterate over each character in string t we check if match index is not the end of the string s and if the character of t is same as character at matching x 1 in the string s if the condition is satisfied we increment the match index at the end we return if match index is the end of s that is if we have matched all the characters of f in the target string p the time complexity for this algorithm is o of t where t is the length of string t while the space complexity is o of one we can also do it the other way round instead of iterating over t we can iterate over s and check if the characters are present in t in the same sequence we could have also solved this using dp by finding the longest common subsequence in s and t and then if the length of longest common subsequence is equal to the length of s we return true else false we did this in edit distance question previously the link for it is given in the description here's the code snippet also check out the link to the java code in the description below thanks for watching the video if you like the video please hit the like button and if you are new please subscribe to our channel
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
15
hi everyone so we are back with another video in our need code 150 DS question series and today's problem is three sum so this is a very important problem and has been repeatedly asked in multiple interviews so make sure to watch the video till the end right and before proceeding further guys make sure that you are solving the previous questions also right so I have provided the playlist Link in the description so make sure that you are following the series top l in a sequence okay so let's get started with the problem statement now the problem says given an integer array nums return all the triplets nums I nums J nums K such that I not equal to J I not equal to K and J not equal to K and nums of I plus nums of J plus nums of k equal zero also the solution set must not contain duplicate rets So Yesterday only we have solve toome problem right we solve two some problem where uh where what we were having where the array was sorted right and before that also we have solved a problem to sum only where the array was not sorted and we have used hashmap to solve this particular problem right so today's problem is three sum I would suggest to watch the these videos before two sum and two Su second where the given array sorted and then Hope on to this one you will get better understanding and probably you'll be able to solve the question by yourself only right so here what is given to us that we have to find the triplet such that nums of I plus nums of J plus nums of K is equal to zero and given that the index is I not equal to J I not equal to K and J not equal to K also the solution set should not contain duplicate triplet so what does it actually mean let's understand so here we are having example nums equal to - 1 0 1 2 -1 -4 in the output these are - 1 0 1 2 -1 -4 in the output these are - 1 0 1 2 -1 -4 in the output these are the triplets we are having which you if you will sum them up you will get zero so Min -1 + -1 + 2 you will get zero so Min -1 + -1 + 2 you will get zero so Min -1 + -1 + 2 you will get zero similarly here also if you will sum them up you will get zero right so if here you will check so we can take minus1 01 this one and again this minus one also we have right so this minus one and this 0o one but if you take this another triplet also considering this W minus one then what we will have the triplet would be repeated and they have clearly mentioned that the solution set must not contain duplicate Trix right because if you will take minus one 01 and from here also you will take this minus one and this 01 then again the triplets are same only right so that's what here if you will check so there is no such template which is going to give us zero on some on addition so we are getting empty list right and here also if you will check so here everything is zero only so that's why we are getting this is the triplet the only possible triplet sums up to zero right so I hope the problem statement is clear and those who have already solved two sum and two sum second given input is sorted they'll be able to solve this particular problem most probably you will be able to think I mean like okay how we are going to solve this particular problem all right so let's first talk about the Brute Force approach that you will think of ke like how we will be solving this problem so the most basic or The Brute Force approach I would say that many of you must be able to think of is that uh let's consider three elements so first we took this one right so we are just choosing the elements how you will choose that you will have three Loops in I equal to Z within that in J equal to Z within that in k equal to Z so we'll be having three Loops right and I equal to0 sorry I equal to Z see we don't have to repeat the indexes right sorry so I equal to Z so you have chosen this element so next element would be from I + 1 right next element would be from I + 1 right next element would be from I + 1 right then PST that next element would be from J + one so this I element would be from J + one so this I element would be from J + one so this I JK we have so now what we can do we can just sum them up we can just take this nums of I plus nums of J plus nums of K and we can just simply check if they are equal to zero or not right they're equal to zero or not if they're equal to zero means we have got a triplet and now as it given in the question that uh we need what we need uh duplicate should not be there so what we can do let's say uh first triplet that we will get is minus one 01 because this igk we will take right so uh if you will sum them up you will get zero so we our condition got satisfied so these are the firstat that we have got now we have to take care of duplicate triplets also so what we will do we will um sort the triplet that we have got so if you will sort it so yeah on sorting you will get minus one 01 only and we will put this in a set right put this in a set this list of integer that we have got we are going to put this in the set so next time also when we will continue itating in the loops we will continue rating in the loops when we will come across this scenario that u i is this J is this and let's say k is this so again the condition will be satisfied but set is already having this pair minus one01 so this entry won't be included right so this is the first and the most uh basic approach that most of you must be able to come up with now if talking about a time complexity so this is approximately like big of n CU if talking about this particular solution the boot Force One so obviously if you will come up with this one then the interview is not going to be happy with you with this particular approach and as we have already solved the problem to some two some second given AR is sorted so I hope most of you must be able to think of that we can solve this problem using two-p pointer solve this problem using two-p pointer solve this problem using two-p pointer approach so we will discuss about that and we will yeah obviously discuss about the code related to that so yeah so first thing is that Let's do let's sort our array so first thing that we will do we will sort our array so if let's say we are taking this one this array and on sorting this is how our array will look like now if you will think this problem in the two Su way only in the two sum way only that we have the problem that we have solved yesterday so what we need is that so we have been given x + y + z is that so we have been given x + y + z is that so we have been given x + y + z equal to Z or we can say that x + y equal to Z or we can say that x + y equal to Z or we can say that x + y should be equal to minus Z so we can say minus that is the target element that we are looking for so we have to find are two X and Y whose uh whose summation is equal to that of the target element which is nothing but minus that right so let's say so what we will do we have started from this one so what will be our Target element four we need four is our Target element right so this element would be fixed this is our Target and this would be fixed that we need two elements which come up to minus so element was What minus so minus four and again we need minus so minus became plus right minus plus so we need to element which sum up to four so we will again follow the same two pointer approach only where what is going to happen that our uh J and K will start from I + 1 so J will be pointing to this from I + 1 so J will be pointing to this from I + 1 so J will be pointing to this index one and K will be pointing to what k will be pointing to this last Index right so again just what we will do the summation so min-1 + 2 - 1 + 2 - 1 + 2 is going to min-1 + 2 - 1 + 2 - 1 + 2 is going to min-1 + 2 - 1 + 2 - 1 + 2 is going to give you what 1 so what is our Target is four so one is what one is less than that of Target means we need we have to increase the what we have to increase the summation we have to increase the sum so in that scenario what we will do we will increment the value of what because po again we are having What minus one so minus one-1 + 2 still we will get one minus one-1 + 2 still we will get one minus one-1 + 2 still we will get one similarly Z again 0 + 2 this will give us two again 0 + 2 this will give us two again 0 + 2 this will give us two SIM so it simply means that we didn't got any pair which is equal to that of Target now I value is going to be incremented so I is going to be I value is going to be incremented so now whatever Target is this is our Target means this is our Target Z is What minus 1 so minus 1 we will get one so our Target is what one now and again so left pointer will be moving to because left pointer will be ahead of that of I right so left pointer will be pointing to this index two and right pointer will be here only at the last so again we will do the uh we will do the summation so minus1 + uh we will do the summation so minus1 + uh we will do the summation so minus1 + 2 this time you have got one means we have got the target we have got the Target right we have got the target so we have got the triplets so we are going to store them so what are our triplets uh nums of I which is nothing but minus one nums of J which is nothing but minus one and two right we have got this right so since we have got this now what we are going to do we are going to uh we are going to increment the value of R we are going to increment the value of left pointer as well as right pointer so now left pointer would be at zero and right pointer would be at one now this also zero and one this also 0 + 1 0 + 1 is one this also 0 + 1 0 + 1 is one this also 0 + 1 0 + 1 is also going to give us one only means Target so again we have got our again we have got a uh what do we say again we have got uh the target so minus what are the pairs we are going to put them minus 1 0 1 right so next time the left pointer will exceed the right pointer so we will come out of the loop so again I value will be incremented and what is the I value this time minus one minus Comm one previously also it was minus Comm one so minus common minus Comm gave us one which is the Target right because we are doing minus Z right minus Z so or you can just write it if it is causing any confusion so left plus right minus I right so but we have already calculated the triplets for this particular Target that is one I is What minus one so minus one is going to give us what one but we have already calculated the for this particular Target right and we don't have to repeat ourselves we have to avoid a duplicates so what we will do you can just simply put a check this is the check for the same that if I is greater than zero because see if I is zero then obviously in the left side we not going to have anything right so just we are putting this that if ier than zero and nums of I is equal nums of I minus one which is the scenario is getting satisfied in this particular case so continue we don't need to calculate for that one we have already did right continue so now we have continued so I is going to be zero this time I is going to be zero oh sorry yeah I is going to be further incremented and this time our Target is going to be what Target is going to be zero and again we will calculate so yeah it won't be satisfied so the two uh tripletes that we have got are going to be this one only the two that we going to get is going to be -1 -1 2 -1 going to be -1 -1 2 -1 going to be -1 -1 2 -1 01 right um I hope that it does make sense right so similar thing that the logic that I have just explained the similar thing that we have implemented in the code that what we are doing is that the first thing that you can check in the starting itself if the length of the AR itself is less than three then no like triplets we do need right so at the time it return the result otherwise what we will continue with the process so we have to sort the array and see this Outer Loop anyhow we are sure that it will execute see when I was just doing the dry run so we continued for the I till here only right that it will continue till n minus 2 only so that's why in IAL 0 i l than n minus 2 I ++ now to avoid the duplicates minus 2 I ++ now to avoid the duplicates minus 2 I ++ now to avoid the duplicates so here we have done if I greater than zero and nums of I equal nums of I minus one continue otherwise this is our Target is as I already explained left pointer would be ahead of one step ahead of I so I + 1 and right would be the end of I so I + 1 and right would be the end of I so I + 1 and right would be the end index so n minus one so we will continue the same approach the two pointer approach left less than right so if the summation nums left plus nums right is less than Target so we have to increment the value of left if it is greater than that of Target so we have to decrement the value of right if it is not then obviously the last possibility is that the summation is equal to that of Target so we are going to add these values these triplets nums I nums left nums right and our result in our result list and now most of you could be confused that why do we need this particular U condition here right why do we need this particular condition here just let me in simple terms if I will tell you that this is to avoid or this is to es skip duplicate triplets because we don't want to contain or we don't want to consider duplicate so let me help you to understand his name with the help of an example so here let's say this is the array we are having and if you will sort it so we will get minus 2 um 0 22 right already sorted right so this is what we're going to get right so the same logic here also so what is our Target is going to be minus two is this so minus into minus then obviously two so two is our Target left would be here and right would be here right so 0 plus 2 we have got our Target means we have got our triplet so triplet is minus 2 0 two cool right Tri is minus 2 02 then what would happen What would happen that left and right pointer left will be incremented and right would be decremented so left would be here and right would be here then again see this is also right again we are going to like we are having a Target if this PA if this left and right you will consider the sumission is equal to that of Target that is true right so if you will again consider this thing so we will have min-2 02 but this triplet and will have min-2 02 but this triplet and will have min-2 02 but this triplet and this triplet is same only right same only we don't have to consider the duplicate triplate right so that's why to avoid this thing see here we will check that if left we have to be in Bound we have to be in this limit this condition should be true that left still is less than that of right and nums of left so what is nums of left is right now nums of left before incrementing itself like we are checking nums of left is this one if it is equal to that of nums of left plus one so this zero and this zero is equal so we are saying increment the value of left right now again we will check the same thing so this zero and two we have now they are not similar right now here same thing we are checking for here that right is right now here only right is as of now here only so we are checking if nums of Rights so which is nothing but two is equal to nums of right minus one so at right minus one also we do have two so decrement the value of right so right is now pointing to this one again we will check the same thing so what is nums of right now two and at right minus one nums right minus one we have zero so this is not equal so we will come out of the loop so now we are saying left increment the value of left so left is where left is as of now here itself so increment the value of left decrement the value of right and left will exceed or left will move Beyond right and we will come out of the loop right so this is also to avoid the duplicate right I hope that it does make sense now right going to Simply return result right so yeah this is what the approach was for threeome problem we will solve the next problem tomorrow I hope you were able to understand the approach so let me know if you were able to solve this problem by yourself or you watch the video or how it was thank you so much for watching this video guys keep coding keep learning and maintain the consistency thank you everyone bye-bye
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
77
hi everyone just so little question called combinations so given to integer n and k we want to return all possible combinations of k numbers out of this range are 1 to n increasingly and we can't announce it in any order let's check example one to help understand example one here we have n equals to four this means the range is a one two three and four right and six k two we can pick uh a two element from this array so let's see we pick a one first element then the second mp have been either be two three and four right and let's say we pick two for the first element then second cannot be one because the two one is the duplicates with one two so we can either pick a three or four as second element so get two three and uh two four and if we pick three at the first segment we cannot pick three one because three one is duplicates always this one three right and we also cannot pick three two because thirsty two is duplicate with this two three so the only thing we can pick is three and four and what if we start with four if we start at four we cannot pick uh four one four two four three because there are duplicates with previous elements right okay now this is entire thing we want to append all this at the subway form in the result array and we're done okay i think the problem description and quite straightforward now let's think about how to solve this problem so if you watch my previous video you know for this combination permutation uh subset problem i would prefer uh to use backtracking solution which is each one stand and efficient so let's check uh with example here so let's say our numbers is one two three so i'll scroll down to make it clear and let's further suppose uh our k is equal to one and this means we have to pick one element from this one array okay so write k equal to 1 here uk equal to 1 so you see in this framework we just continue on the search that we're reading the subset problem if k equal to 1 this means we have to find uh the length so past equal to one right now is there any elements uh in here that equal to r1 for the lens you see here we have this single one so lens is one and here we have this single two and the lens uh is also one and here we have this single three so this lens and also one so if k equal to one the only thing one to return is uh these three sub array right so like that and let's suppose we have changed a k to two okay so like k to two here if k equal to two this means the length although all these paths should be two right you want to search the paths that have length equal to two and do we have a length uh past equal to two here obviously this one has a lens equal to two and this one has density and finally this one also has last two so you only want to return it these three elements uh if the lens surprise is equal to two okay then finally let's suppose we have changed k from two to three so this means our length part is three right okay in that case we want to search the element always the length equal to 3 for the pass and here we have only this one two three right which has the lens equal to three so we just i written this element in the resultary okay now this is a graphical explanation the next thing to write code so just clearly solve and write code i in this part okay the first thing to initialize number three so just use this point sonic way all the way from one to n plus one because you know python if you stop and plus one you can only reach the end right okay now if we should initialize numbers is not seen to neutralize the plus which is empty array and also the result should be initialized empty array okay now fish there's next thing we call helper function to update uh the parasite and result in nouns so that's called how the function process is variables if i return the results the main function okay notification main function next in it to write the hubble function right so the top function the first thing to consider okay if the lancer pass what you place you want to append this specific part to a result array and otherwise you just run the equation through the entire array so just following python and then uh that's called the help function passing numbers all the way from n plus one uh to the end right and the part should be divided by the current number say i and the result should be inherited from private result okay now let's meet how this works oh sorry i forget the k in here so add k here and let's meet the result again okay here should also be okay sorry okay you see the time capacity and the usage of this solution is not bad right and i think the code is a very short eastern stand and similar with the previous subset and permutation framework okay if you like this video please subscribe to my channel and i'll see you next time thank you
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
376
hello friends today in this video we'll be understanding the wiggly sequence problem from the lead code difficulty level marked for this question is medium now let's first understand the question and the problem constraints that are given to you so now let's first understand what is a wiggly sequence so wiggly sequence is a sequence where the difference between this successive numbers is always alternating that means if the difference between the first two pairs is positive like greater than zero then the difference between the next consecutive pairs would be negative that is minus zero so if you see in this example uh the difference between these two pair is positive that is plus six and if you see the difference between these two pairs it is minus three and then again if you go towards this place it is again positive plus 5 and so on so this is a perfect example of a wiggly sequence array and if you see this one you don't find the sequence alternating it's always either increasing or decreasing too much so it's not a perfect example for a weekly sequence now the in the problem statement they are asking us to find out the maximum length of the wiggly sequence you can remove many elements any number of elements from the given array and try to find or figure out if there exists a sequence if there does not exist a sequence that also you need to figure out so let's understand that with an example what should be the output in case uh if the complete error is not totally following the weekly sequence that we'll understand with an example but let's first understand the constraints before we start understanding the example so over here they are mentioning that number of elements that would be given to you in the array would vary from one element to thousand element and any number in that array would be ranging from zero to thousand that means you would not have negative numbers or any number greater than thousand now let's understand few examples and then come up with an approach to the solution and we'll probably try to figure out a big o in uh time complexity so now i'll also discuss few edge cases with you guys because that is clearly also mentioned in the question because it's mentioning that there if a sequence is having only one element then the sequence or with two non or a sequence with two non-equal element is sequence with two non-equal element is sequence with two non-equal element is also a wiggly sequence so we will have to figure out this edge case also so let's take an example of this edge case and understand this so let's say i have an integer array with only one element now you see the difference that are is possible is nothing so you cannot find difference because there does not exist any other element so this is a perfect example and the maximum length of the wiggly subsequence would be one if we have one comma two then so this is having one pair and that one pair also has a difference of one that is why uh this is also wiggly sequence and the maximum subsequence length is two but what happens if these are both same one comma one then the difference is neither less than zero or greater than zero it is exactly zero so that's why it is not considered completely as a wiggly sequence so we'll just uh mark only one element we'll only consider one element as in the weekly sequence because that follows the first case so the maximum subsequence length would be one so these are few edge cases that were given to you in the question and you'll have to take care of these cases as well in your code now let's take with a valid example where we have a valid length of array and we keep removing few elements if in case needed to make that complete array as a wiggly area now let's take that example now let's see this example and try to figure out if this complete array that is given to you is following the wiggly sequence properties or not if this is not following then we will try to figure out what elements we have to remove from this array to make the resultant array to follow the weekly sequence uh strictly now let's try and understand the difference find the difference of the consecutive pairs and see if this is following the weekly sequence or not so over here if you see this is a difference the of positive 16 then the difference becomes negative 12 then again if you see compare these two elements the difference is positive 5 but if you see over here the difference is again positive that means it has broken the wiggly sequence subsequence property now because this element now should have been a negative value now to make this negative value uh we don't have anything right now but what we can do is we can strictly skip 13 from our element array so if we skip 13 so we don't have to find this difference and we will go ahead finding difference for the next element with 10 so the next element with 10 pair would be again 15 and the difference is again plus 5 so this is again not following the wiggly sequence so let's remove this 15 as well from my array and let's see if the next consecutive pair uh with 10 which forms with 10 does it follow the wiggly sequence or not so if i go ahead and i subtract 10 with 10 this also does not seems to follow because over here the difference is 0 so i will also try to remove 10 from my sub array so i have till now remove three elements when i am on 10 i have counted till 10 so now let's go ahead and see if the consecutive element after this value does it allow us to follow the wiggly sequence so if we consider this element so the difference is negative yes so now so if my resultant array is somewhat like 1 17 5 10 then comma 5 now let's leave 16 and 8 as it is because we have not done anything with them and now let's see so over here the difference is 16 over here the difference is minus 12 over here the difference is again positive over here the difference is negative over here the difference is again positive 11 and if you see over here it is minus eight so this is my final wiggly sequence which is strictly following the complete property so practically what i have done is i have removed three elements from my exact input array and i've got the subsequence so what is the length of this subsequence so the length over here is 7 that means from this array we can form a wiggly array of length 7 that's the maximum length that is possible for us now what algorithm do you think is applicable over here so understanding this example there is a particular algorithm that we just followed and i would just want you guys to take a pause first for a minute and try to figure out what's the condition and how the algorithm has worked and try to figure out that yourself now let's take an another example where we have few uh elements that are same so let's take an example where let's say we have 3 comma 2 comma 5 so this is let's say my array that was given to me now let's try to figure out what is the maximum length of wiggly subsequence over here now if i do a difference between these two elements that is 0 that means this is not the subsequence that i would want to have in my release subsequence if i do the difference over here again zero if i do the subsequence difference over here this is negative one so that means my wiggly subsequence starts from this element now i will go ahead with after three so after three if you see three and two forms a negative difference so then two and five should pause find a positive difference so which you see is a positive difference so max so we'll practically be removing these two elements because the resultant difference due to these two elements was becoming zero and that would not have helped in forming the wiggly sequence so i've removed these two array and my resultant array is again three comma two comma five so the length of maximum subsequence that follows the wiggly properties is three so this is the second example now if you try to figure out the algorithm you will feel that if the difference of my current pair is less than 0 then my difference of the previous pair should be positive or if my difference of my current pair that i am comparing is positive then the last one should be negative if this is positive uh sorry if this is negative then the last pair should be positive so this is how it should be and if that does not follow this property then i'll not increment my counter that's a very basic property that we can uh right now figure out so let's write a basic algorithm and then let's take that up with one more example and let's see if that helps us in finding the maximum length of wiggly subsequence or not now let's understand the algorithm that we just decoded in last two examples so over here i have written in the first step if the array length is equal to 1 then definitely will return 1 because that was the edge case that we had and we had discussed that now if the array length is greater than z 1 so that means we have at least two elements in the array so we'll find the difference of the first two elements and if that is not equal to zero that means both the elements are distinct then we'll set the count to be two so now we know that at least these two elements are distinct so at least my less my minimum length of my wiggly subsequence would be two because these two elements are non equal if they're equal then i would set the count as one because we'll discard the first element and remove it and we'll just have the second element as my weekly sequence and we'll keep that up now in the third step if the array length is now greater than 2 then this step would come into picture because we start iterating from i equal to 2 to n minus 1 both inclusive that means my array my iteration would start from i equal to 2 and would end up to n minus 1 both inclusive and i'll try to find out the current difference this is my current difference if you see so current difference is array element ith element and its previous element the difference between these two so if my current difference is greater than zero and last six last difference was equal to zero uh or less than zero or let's say my current difference is less than zero and my last difference is greater than equal to zero so this clearly states that there is an alternate between these three elements now why three elements because two elements we are considering in the current difference and two elements was were considered in the last difference so these three elements are in the wiggly sequence so we would we could increase the count variable to plus one because we have just arrived one more position and that helps in following the wiggly subsequence and we'll store the last difference in our last our current difference variable in my last difference variable and keep running this loop and by the end of the loop we'll have the count variable having the maximum length of wiggly subsequence that is possible now let's try to understand this algorithm with an example and let's see if this algorithm needs some changes or will it work in all scenarios or not now let's understand this example with our algorithm in line with our algorithm and see if this algorithm stands true for this example or not so in my example i have these elements where i have few repeating elements as well if you see and let's see let's try and decode so over here if i see the length of the array is not equal to 1 that means my first step of checking is done so i don't return anything now my array length is greater than 0 that means i'll find the difference between the first two numbers so first two numbers and i'll store that in my last difference so first two number is seven and four so difference between these two is definitely minus three so this is my last difference that have been stored now i got and this is not equal to zero that's why my count variable uh i'll also have the count variable let's have the count variable over here so that means my count variable over here is 2 now let's start with i equal to 2 so i equal to 2 that means uh this one this element so i equal to 2 and i equal to 1 what is the difference between these two so the difference between these two pair is 2 so this is sorry the current difference becomes 2 now if i match this with the condition the current difference is greater than zero and large difference is less than zero that means i would increment my count variable so now my count variable becomes three and my last difference becomes two now if i go to i equal to 3 so i equal to 3 that is this variable so this one so not this one i'll remove this so the difference between these two is equal to zero so my current difference is equal to zero and last difference is two so if you go ahead and see so this does not match to any condition over here so current difference is greater than zero or current difference is less than zero i don't have an equal to condition so nothing would happen and my last difference would be as it is 2 and my count will remain 2 3 sorry now i go to i is equal to 4 for i is equal to 4 that means i am on this element that is uh i4 so 7 so the difference between 7 and 6 but it is positive that means plus 1 so my current difference is plus 1 now if i check this condition the current difference is greater than zero yes the last difference should be less than or equal to zero which does not match if i go ahead and see this my current difference should be less than zero this is also not matching that means i'm not having this as uh true so these two variables will remain same now if i go to i is equal to five that means uh to this fifth uh index uh if i see this so the difference between that these two consecutive elements is minus 2 so my current difference is less than minus 2 and last difference is greater than or equal to 2 that means my count will increase to 4 and my last difference would become minus 2 now i go to i is equal to 6 so the difference over here is again minus 2 so current difference is minus 2 which is not following this condition so we'll do nothing over here no changes so practically we have till now we have removed one six and this three we have removed and so on so we are we have till now remove three elements uh from here so yes now let's go to next index where i is equal to 7 so that is this one so if i see this is 4 so my current difference is from the last two elements is 3 and four the difference is always plus one so the difference is one and the difference the last difference was my negative so that means this would follow this condition i would increment my counter to five last difference would become 1 i is equal to 8 is over here the difference is positive this and the difference over here is not alternating that's why we have no changes over here we remove this we move to next element that is 5 i is equal to 9 the difference between these two elements is negative minus 1 this satisfies as condition that's why the current uh the large difference would be this and the count variable would be increased now i is equal to 10 so difference between these two is current difference is 0 and this is not following any of these conditions so i'll leave everything as it is now let's move to i is equal to 11 eleven so the difference between these two is minus two uh sorry positive two current difference is positive the last difference is negative it follows our condition that's why the last difference becomes two the length becomes the count becomes 7 now i go to i is equal to 12 so i is equal to 12 is practically the last element of our original array so over here the difference is minus 1 so this last difference becomes minus one the count becomes eight so my final answer is eight now if you see this with a normal uh case as well if i go ahead with removing the elements that should be removed for wiggly sequence the array would become 7 4 then again 7 because this is decreasing then increasing then decreasing five then increase uh this is decreasing we'll remove uh till we get an increasing term this is six then we go to five then we go to 7 and then we go to 6 so this has an length of 8 so if you see 3 elements and 2 elements that is 8 so this is my final count so that means our algorithm stands true for this example as well now this algorithm has a time complexity of big o n now why time complexity as big o n because we are just iterating on the complete array once so we are starting from index two to index n minus one that is in step three so that is one iteration uh from index two and one uh we have do we are doing over here so practically it is iterating from for all the elements over uh over one time so that means my time complexity becomes big o of n and space complexity becomes o of one because we are not creating any new array or anything so we are not practically having any new space that has been created so the algorithm is this that we just discussed and let's see this algorithm in place in a code now the code that i have written is in golan you can go ahead and write the code in any language of your choice whether python dot net c sharp uh or c plus c java any language that you want to write it in just try to follow this algorithm and it should be done in your language let's see the code in golan now this is the code that i've written in golan so if you see and uh understand so this is my step one where i am comparing the length of the array uh with one so if the length of the array that is n so n over here is the length of the array so if the length is equal to 1 i would return 1 definitely now i find the last difference with n with the arrays first element and 0th element and if that is not equal to 0 that means my count is 2 so this is practically step 2 where we have just found the count variable otherwise my count was actually initialized to 1. so if this would not have happened my count would have remained 1 over here now i start my i with 2 to n less than n so that means that it would only run till n minus 1 element i find the current difference by in nums i and num i minus 1 and then have this condition where i say if the current is greater than 0 the large should be less than or equal to 0 or if current is less than zero the large should be greater than or equal to zero if this is satisfying then i'll increase my count variable to one and i'll update my last difference to my current difference and in the end i return the count so this is my step three and my time complexity becomes big o of n and space complexity if you see becomes big o of one so this is the final code at which you can write in any language of your choice now if you see this and you follow this so that's it for this video today and in case you liked the video and it was helpful for you please do not forget to like share and subscribe to our youtube channel also comment down below in case you want any particular question from lead good or geeks for geeks to be solved by us on golan or any other topics that you want us to cover for you guys using golan so go ahead and comment down below as much as you want any topic on uh go line using gold and we appreciate you guys to do that
Wiggle Subsequence
wiggle-subsequence
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. * For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. * In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. **Example 1:** **Input:** nums = \[1,7,4,9,2,5\] **Output:** 6 **Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). **Example 2:** **Input:** nums = \[1,17,5,10,13,15,10,5,16,8\] **Output:** 7 **Explanation:** There are several subsequences that achieve this length. One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8). **Example 3:** **Input:** nums = \[1,2,3,4,5,6,7,8,9\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` **Follow up:** Could you solve this in `O(n)` time?
null
Array,Dynamic Programming,Greedy
Medium
2271
6
hello everyone welcome back to another video today we have an interesting coding problem to tackle converting a given string into a zigzag pattern with a specified number of rows this is number six on the code it's called zigzag conversion and today we'll be solving in C plus our solution uses a vector of strings to efficiently construct the pattern now before we get into the code if you guys want to see more videos like this drop a like down below it helps us out tremendously with the YouTube algorithm without the way let's hop right into it thanks all right so we're given a class name solution that contains a method called convert which converts the input string s into the zigzag pattern with the specified number of rows numbers to handle the special case when numerals is one we have a quick check at the beginning if numbers is one we simply return the original string S as it won't have any zigzag pattern next we create a vector of strings called rows the size of the vector is determined by the minimum number of num rows and the length of the input string s each element in this Vector will represent a row in the zigzag pattern we initialize Cur row to keep track of the current row we're processing and going down as a flag to indicate whether we're moving up or down in the zigzag pattern we then iterate through each character C in the input string s inside the loop we append the current character C to the corresponding Row in the rows Vector using the curve row index this way we build the zigzag pattern row by row we check if curve row is at the topmost row index 0 or the bottommost row index num rows minus one if so we need to change the direction of the movement by updating the going down flag using the logical not operator after processing each character we increment or decrement curve row based on the value of the going down flag using the ternary operator efficiently moving us up or down in the zigzag pattern once we've constructed the zigzag pattern we connected the strings in each row to form the final converted string stored in the variable red we then return the converted string which is our answer so now let's go ahead and run it right that's going to be it for this video If you guys enjoyed or found it helpful drop a like down below drop a comment if you have any questions subscribe for more and we'll catch you in the next one
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
208
our next problem is called Implement a try um or a prefix Tre basically a try pronounced as try is a or prefix Tre is a Tre data structure used to efficiently store in three keys in a data set of strengths um it is being used for um things like autocomplete or spell checker most commonly we have to implement a tri class basically containing a Constructor and then we have like three methods the first method will insert a new word inside the try and the search and starts with we basically do a performance search on that uh on inserted words so in the search we are searching for the exact word inside the try and for the swi we are basically doing the prefix part of the prefix three so we are checking if there's a word that begins with a certain prefix if it if there is we return true and if it doesn't like we just return false so um here in example we are basically just constructing first try and then we are inserting um apple and when we try to search for Apple we will return true because we are searching for the exact word Apple now in the example of searching for app uh we will return false because we don't have the exact word app inside try uh when we start to but when we do the prefix search for app uh basically apples uh is prefixed by the app so we return through next when we uh try first to insert the app inside the try and then search it we'll we will now we will get the uh true because that word exists inside of the try now we'll see what do we have for the uh constraints for this problem and con are the following the word and the prefix that are being used to insert or search inside the try are from one uh the length your length is from 1 to 2,000 the word and prefi is from 1 to 2,000 the word and prefi is from 1 to 2,000 the word and prefi consist of only lower case English letters so this basically when we are uh dealing with tries uh it's uh the first question that you should ask is like um uh what does the string contains like what uh what does the string consist of basically so in this case it's only lowercase English letters now we also have that we will have at most three times uh 10 to the four CS in total will be made to insert search and sofware when it comes to Tri there are two things that we have to Define we have to define the uh children relation so children how many children a node can have because basically tries are um uh kind of similar to Binary trees but uh the only difference that they can have as many children as uh as we want uh so each node can have as many children as we want so how do we Define the uh children and then the second uh what additional um kind of data are we storing for each note so basically that's the data that we are storing in each node depending on the problem that we have so in this problem we have basically we have to solve the insert so how do we insert into a try and then we have to basically uh implement the search and uh starts with so prefix and the complete search for the complete search uh basically we have to know that a certain node represents the end letter of a certain word that has been insert already inserted in a try so for each note we will have the array of children basically the relation to the children and we will also have the indication a Boolean flag whether that node is an end letter of any of the words that have been inserted to a try uh that's basically enough to uh do to perform the search for the word uh for the prefix basically we don't have to check if there is uh if there's the if the note is marked by uh by that flag it's just enough to find um some sequence of characters that represent the prefix if you find it inside of the tree that basically means that the is a word that starts with that prefix now we will go through an example of how we insert and how we search inside of the tree so let's just say we are inserting the word car and the word uh app and the word Apple inside of the tree so because we have only lowercase English letters we can Define the children relation as for each node as a constant size array with 26 letters because that's the maximum of uh children that we have we can have because those are the all the number all the letters lowercase letters in the English alphabet so we'll start with our root and then once while we are inserting we are basically we will be creating a new note if it already doesn't exist so for example for the um for the first uh letter we will have C and uh we will just insert it here and that will basically continue because we don't have an A after C we will just insert a and then we will insert r R now when it comes to the second word we will basically we will check if we have a we will again start from the root we'll check if we have a node with uh with the value a we don't so we create one and we continue basically to do the same for the rest of the nodes now for the Apple we already have a p and p so the only thing that we have to add is the L and the E and basically this will be the representation of f but this will be the representation of apple and also for this note we will have a special tag is word and it will be set to true the default value will be false so here we'll have false here we will have false but here because this is the end of the app it's a worded hasus been inserting the try then we will also have true here so then when we start to uh basically search for a certain word let's say we are searching for word uh car will basically iterate over each letter and we will move uh throughout our triy so basically in we are looking first for we are start from the root and we are looking for the letters uh C the note that corresponds to the letter C in this case that's the that's this note so we have that note and we can continue with the iteration so then we start from that note and we check if we have a and then we have R so for example if you try to search for some for a word um cars for example we will come to R and we will check if we have the node with the letter s with the value s in this case we don't so basically we will the search will just return null and we will know that there's not an exact word that um that corresponds to cars basically it hasn't been inserted into the try and uh if you're search for the exact word we have to check if this note has the is word set to true if it does then we basically know that the word exists inside of the try uh if you only search for the prefix it's enough basically to get to the end um end letter so in example if you're searching for prefix uh AP we'll just go to AP and we'll basically have a n p so basically there is a prefix there are some words in this case app and apple that are prefixed by AP so we'll just return through but if our prefix is for example uh D we will check for the we'll start from the root and we check for D but we don't have D so basically we'll just return false now when it comes to time and space complexity basically here we'll have um uh we will have uh reads and writes so if you mark them by read and write uh and both of these operation will be dominated by the number of nodes that we have inside of the TR so no matter how many times we call it basically the if you mark our number of words that we are inserting in the into three by n let's just say and the average uh average length of the word will be l so for us to build and to build the tri and insert all the words we need n * L time complexity the same we need n * L time complexity the same we need n * L time complexity the same goes for the word Searcher so if you have n uh N word searches or and prefix searches and the average length of the word is l then for each word we will basically spend L um l noes to perform the search so basically we can also say that this is uh the sum of the length for each of the words that we have so basically that's our time in space complexity because at the end the trve will all of these uh words that have been inserted to it so first of all we have to present our try notes uh in some way so for that we will Define our private class called try node and for each node we will basically have to define the number of Childrens uh in this case uh the Constructor will just initialize the number of children to an array of try notes so each note can contain 26 uh children total which corresponds to the number of lowercase single SS that we have the uh besides that we also need some of additional data because we will be searching for exact words we have to mark a spe one of the notes that basically represent the end letter of a word that being CER try we have to represent it by some flag and to represent it we are using is word and the default value will be false next we will Define our try note rout it should basically be just a starting point for uh each of the operation that we'll have on the try in the try we'll just initialize that through to an uh to a Noe try note uh next for the basically for search and star s they are basically the same almost the same methods the only difference is basically that for search we have to check if the this word is set to uh to true so uh to not repeat our code we will just Define search per prefix uh and we will pass the prefix as the argument so we are just start trying to find the pre the prefix and we will use this method for both the search and start with method so we'll start by declaring our to be put be pointing at the same location at as the root so we are starting from the root and then uh for each letter in the uh prefix uh we will first get it and then uh we will basically check if the uh if it's defined if we have uh if the current node has the trial node that corresponds to that letter if it doesn't we will just return null because we don't have that prefix we don't have the next letter in the prefix but if it does then we'll just move to that Noe and to move we can use the children array relation to basically could just uh move to it uh then after we are uh if we crossed all of the letters inside the prefix the basically the current node will correspond to the last letter that we have uh that we have observed the last letter of the prefix next we insert we will basically have a s logic we will start from the root and then for each of the letters inside of the word uh we will uh first get it and then we will check if uh if it's undefined if it's correctly undefined so if we don't have it inside of the TR try if we if you don't have it then we have to create a new node for the new children child node for the current node that corresponds to that letter and then uh we basically move to that uh to that new node so we can start from the next letter of the word uh finally uh we'll just put uh the last note will be pointing to the uh we'll have the value of the last uh letter inside of the word so we just put the flag is word to through now for the search we'll just use the search prefix we will bypass the word that is um given to us by the um first parameter to this search function and uh the search perfix will return the node that corresponds to the last uh letter inside of the word if such exists if it doesn't exist then we'll just return null so first of all uh to be sure that the node is not null and if we have the that certain prefix we will check if the node is not null and then because we have to have an exact word we'll check if the node has the flag is word set to true if it is then basically that means that the word has been inserted ins inside the try next we start with basically we have the same uh same thing as for the word but in this case we U we just use the search prefix um uh method and we just pass the prefix that's given to us by the input parameter and we just check if the return value of that search prefix is not equal to null Bally basically that means that we uh get the last note that represents the last letter of the prefix so we can be sure that there is there are some words multiple words only one that starts with this certain prefix and that's basically all of the operation that we have to um have to implement
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
1,010
hello everyone welcome back to another lead code problem solving session today we're going to be solving pairs of songs with total durations divisible by 60. so we are given a list of songs where the I song has a duration of time I second return the number of pairs of songs force their total duration in seconds divisible by 60. normally we want the number of indices i j such that I is less than J with time I plus time J mod 60 equals zero so the I guess we could do an N squared Loop the length of our time array is a bit long for that so it's probably not going to be our final solution but quickly just going through the naive solution is essentially would iterate over uh sorry a lot of time for Jane range five plus one line of time and we would check if I'm I plus time J not 60 equals zero whereas plus equals one and then we'll return our rest so this sadly isn't going to work since N squared is going to be very large in this case but this is an event squared solution if you were struggling with this problem in an interview you could at least show them hey I know how to code it's just I don't exactly know the optimal solution to this problem but essentially what we want to do is notice that there's only really let's look at this example here quickly so we look at let's say 20 and 100. we'll notice that those add up to 120 which is divisible by 60. now if we look at 20 well 20 mod 60 is 20 and then 100 mod 60 is 40. if we add up 20 and 40 both mod 60 well we get 60 mod 60 which is zero let's say it was like 21 and 99 well we would have 21 mod 60 and then we would this would be 39 mod 60. so 21 plus 39 equals 60. and we know that we have a pair there so what we can do is we can keep a hash map of it doesn't even need to be a hash map it could actually just be an array where we have zero for I in range 60. essentially it's the count of the number of songs that we've seen where the total number of seconds is zero mod 60 one mod 60 two mod 60 all the way up to 59 Watts 60. so we go through each time and now what we're going to do is you know obviously get the mod 60. we're actually going to change this whereas to be times or yeah res equals zero res plus equals and then 60 minus X mod 60. just in case X is zero we need this mod 60 here because otherwise we would get 60 and then we would go out of range for the array we can do this and then we can do times x plus equals one that's so just double checking 30 20 okay 60 but three and let's just see if we submit this awesome so yeah this solution was essentially a hash map but we were able to fit everything into an array of size 60. but we were using it like we would a hash map if the keys weren't integers yeah thank you so much for watching if you guys have any questions about the solution please leave a comment down below and if you guys like this video please like And subscribe I'll see you guys next time
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
1,433
Hello viewers welcome back to my channel I hope you are doing all problems the time uploading history become subscribe To My Channel Please Share and subscribe this problem this channel subscribe to subscribe can break communication of subscribe and subscribe to subscribe our A True RFSU Chem Back end one should improve half but what is there exactly definition of string can break and subscribe button on both side the effects of a greater noida request wife in alphabetical order for all is between 0 and minor slits property set point is greater than or equal To Wife In Order For All Side 101 Subscribe To Understand As One Is Equal To A B C To Do Subscribe Bill Is A Scam Break And Am Calling List A Takes Itself And Was Not Accept You Know It No More Is Greater Noida To Wife But Not Break Up My Device Will Great This Grade One Or Grade C Means That Why Can Be Explained Twister Scholar 08 All The Place Disruption More 250 Words Key Wife Can Almost Expired Duplicate Why Can Break X Puberty Questions Hazy Festivals Loot Electronic Like Busy Schedule To Be Is Equal To A CEO That 6125 Background Check Weather That Can Be Quite A Great Way To Video Subscribe That Goa Galaxy Voice That One Takes A Great Day On Canvas Definitely Side Effects Servi Spice Half Noida Did Not Wrong Side Do n't forget to subscribe Thanks for the Day 100 Vidyalaya Simple Examples to Eat But What Were Missing Here from this article In chief voice of the record and subscribe it is straight networks so this cigarette no na what is satire false radhe lift subscribe that not just a string of events of might not distract from person communication reddy to check all sorts of that History So Adjust Enjoy Little Bit Been Done Test Series Such-Such After Done Test Series Such-Such After Done Test Series Such-Such After Minutes Ago Asc So Let's Cleanse And End Put Air Chief Suna Garlic Through Screen Directly God's Exam Record Walk With Time Prove Want To Return Gift Veer VHP Check Competition Commission of Give and Take Good subscribe And subscribe The Amazing and subscribe that thank you can find the a character in 2nd place but I want to show in that case problem it is already subscribe our video number for the word you see how many characters in length This problem subscribe like subscribe Video plz like Share and subscribe the two and subscribe for half an hour I English letters from A to Z so they need to check weather a person can break two or two can break and information of one can break up two And Subscribe 19 That Gets Attracted Minimum Pingbacks A Very Good But Always Going Down Loose Combinations Of Medicines Not Really So Well Device Them Without Setting Off The But Still Dharamveer Vijendra A String Into Another Big Dipper Kya Hai That Dakshin Sakti Thi Character Inspector At Rates Just Enter ₹100 Subscribe At Rates Just Enter ₹100 Subscribe At Rates Just Enter ₹100 Subscribe Industry Subscribe Chief Seervi Chief The Way Want This One Plus One Which Ajwain F1 Destroy Crisis Character Number 110 Subscribe Now To Describe A Hai So All Both Were Checked One Can Break S2 And S2 Came Back With Sacrifice In The Interest of speed note back to go back and makes you came back saw what they want to front then check again and also like this problem we can edit problem * problem we can edit problem * problem we can edit problem * problem number 90 0share 0 the scenes1 d0 flu 5434 year 2009 who is the Current Se Zafar District Presidents Election We Shape Determine Weather In One Convenient Subscribe Always Doing What Is The Definition Of This What Is The Different Effects Of Life Can Be Greater Than Wife Reverse Means The Great Number Of A Number Of First Number Five Is On Thursday What is dare not welcome back blouse gas if you have not subscribed then friends please subscribe more in the mornings and different subscribe to that last this world famous from the discount switch gotra rudra operations abstinence character time difference 2012 information of warm water and Definition of which should only one can pretext or the impression that one can break points 212 that will fall on December's discount offer ribbon character vacant most stronghold is the account is more in next to back picture they can expect to the Video then subscribe to the Difference 20 That You Can Just Give You aFriend as Two Parts to Get Back Soon Sudhir Vyas's Into-Do List is up-to-date with a Vyas's Into-Do List is up-to-date with a Vyas's Into-Do List is up-to-date with a Big Way and All Six Pack Abs Isn't Going All the Missions Breaking Property Act Came Into Prosperity In State Open Curtains Hain So Here S1 Greater Friends We Quality Sewn Are And Seats Per Get Current Subscribe Select Electronic Data Crush Looking For The Red This Simple 500 It Is Sizing Reference 6-Wicket Win Only In English Reference 6-Wicket Win Only In English Reference 6-Wicket Win Only In English Chapter Veer With U 158 Shoulder Min Ki Share0 S Representative Account Of His Back Ki Contact S End When First And A Specific Count Of 20 Back Flash Light Ko Of Stone 500 To 1000 In Next Electronic Filing Return Quantum Subscribe To Connect With Win The Current President is a sensitive issue that sister development differences in the scene are on Vanshi Gond specific playlist heard and including two variables can break one can break Stuart Mil Jayenge is you can break through the air through this subscribe must not subscribe that police on pilot open Just Give Better Rebuilding A In Situ Is Equal To Sewn Front Particular Character Doing Anything But Tips Even Is Grade To Do And Different Shades And Fluid And Different And Subscribe Time Different Ghosh Ne Cambridge I Have Repeated Say Must Subscribe Share And Subscribe To That This Place this increase move in the refrigerator and different Subscribe Timed and finally what you want you can practice e was in this true or destroy into chemistry of soil water in the effigy can break want you back to back at the interactive elements are only can Not subscribe kare subscribe Like the video and subscribe to the Calculating differences in lion one second do this for him * Saunf second do this for him * Saunf second do this for him * Saunf subscribe to tight jeans price rise I am amazed in that case ke dushman will be developed and you guys and destroy all Sauger ai me so che guevara order to and this point and after death at what they are doing a comparison till 60 subscribe to improve total time complexity will be andhra hai agra hai to and class 6 solutions will remove all the content from Being and notification when they speak correct order of endangered total time complexity of that Lucknow Express work on 400g space where you are using are warned are chup re tasty but what is the president situ subscribe to the Page if you liked The Video then subscribe to How to Speed ​​Up During Startup Titu How to Speed ​​Up During Startup Titu How to Speed ​​Up During Startup Titu Sincere Imo 2010a Special Awards Constant Peace Will Remain Actually Item Users Comes and Space and Time Complexity of Islam in Questions Please let us know in the comment section Business Thank you for watching subscribe To My Channel Please subscribe and Share Friends please subscribe my videos very soon
Check If a String Can Break Another String
encrypt-and-decrypt-strings
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0` and `n-1`. **Example 1:** **Input:** s1 = "abc ", s2 = "xya " **Output:** true **Explanation:** "ayx " is a permutation of s2= "xya " which can break to string "abc " which is a permutation of s1= "abc ". **Example 2:** **Input:** s1 = "abe ", s2 = "acd " **Output:** false **Explanation:** All permutations for s1= "abe " are: "abe ", "aeb ", "bae ", "bea ", "eab " and "eba " and all permutation for s2= "acd " are: "acd ", "adc ", "cad ", "cda ", "dac " and "dca ". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa. **Example 3:** **Input:** s1 = "leetcodee ", s2 = "interview " **Output:** true **Constraints:** * `s1.length == n` * `s2.length == n` * `1 <= n <= 10^5` * All strings consist of lowercase English letters.
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
Array,Hash Table,String,Design,Trie
Hard
208,212,1949
1,669
welcome to march's lego challenge today's problem is intersection of two linked lists write a program to find the note at which the intersection of two singly linked lists begins for example if we have these two linked lists we want to return c1 because that's the point where it gets merged here we want to return eight here two and if they don't intersect we're just going to return nothing now you do have a couple notes here basically your code should preferably run in all of n time and use only all one memory uh there's nothing distinct about the values themselves uh you can have repeats like one so that's gonna be a problem okay so if we didn't care about memory we could do this in oven time pretty easily right what we could do is just traverse through one linked list keep track of all the visited nodes that we visited and then traverse the other list and see whichever one that we see that is inside the visited list we turn that the first one that is because that's the first point that it gets merged so let's start off by going with that solution what i'll do is have a current pointer for a and b this will be head a and head b and we'll first traverse through our first linked list and we will add to our visit set the node and then we'll just move that ahead so next we'll do the same thing here with b and we'll say if per b and visited then we return that otherwise we move our current pointer for b ahead and if we don't find anything then we'll just return i suppose so this does use of memory because of the set but it would be the most intuitive straightforward and it totally works gets accepted now how can we solve this without using extra memory that's going to be a lot trickier so let's kind of think about how we can do this so you can see in the notes that we aren't allowed to change the original structure in any way so we have to retain the original structure we can assume there's no cycles and blah so if we want to use o and space really doesn't have many options here there's no cycles so we can't do any like slow and fast pointers um what value could we save here for one value to calculate like what we can you know determine uh well one thing you can realize is there's an overlap if they do merge the length is going to be the same of the overlapped part right so the first linked list has a length of five and the second linked list has a length of six now the three here is going to be the same so really the only difference is going to be between b and a so if we like found the absolute difference between these two we can see that there's going to be a difference of one now knowing that we could just move our pointer for the longer linked list ahead that difference so here there's a difference of one so we'll move this pointer here and then we'll just traverse to both pointers uh the same distance until they have the same node that's going to be the same thing here we can see a difference of two so we'll move this one point two and then we'll start traversing down to see where it meets up if it never meets up then we just return nothing because both of them will point to a nun eventually and we'll just return to none there okay so that's gonna be a lot trickier but let's see how we can do this all right so the first thing we want to do is we have our current pointers we also want to let's see we want to store the lengths so i'll just call it a and b 0. and let's first move through the first linked list what we can do is increase our a as we move our current pointer ahead and we'll do the same thing for b okay so now we should have the lengths of both a and b now we got to determine which one is longer so if a is greater than b then let's see we're going to call this current long and we'll make that equal to the current a pointer that's pointing out symbol to head a instead we'll also store the difference between the two so that's going to be a minus b and i suppose we should also uh set our short pointer to the head b here now otherwise we'll do current long equals head b difference equals b minus a and current s equals curve a or not curve sorry headay okay so now we have our difference we want to move our pointer for the long linked list ahead however many different points there are so i'll just do that straight forward here while i is less than diff we will move our pointer up to the current long to equal curve l dot next like this okay now this is going to be the point at which we want to move both right all right so while per l does not equal curve s we will move ahead both and then we return parallel well either one's probably fine but at the certain point where they're gonna be the same that means that's the point that they got merged so let's make sure this works it looks like it did so let's go and submit it and there we go accepted so this is all one space we do make two passes because we want to calculate the length i did see some really clever solutions where you could kind of do the both of these at the same time but it was pretty unintuitive so i didn't want to go into that this is the way you do it i'm sure you can clean it up if you'd like but there we go so thanks for watching my channel and remember do not trust me i know nothing
Merge In Between Linked Lists
minimum-cost-to-cut-a-stick
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Array,Dynamic Programming
Hard
2251
95
Hello gas welcome to me YouTube channel, so today we are going to solve the problem of finding 95 unique binding factories, okay and the answer is that it can be in any order, meaning this binary tree can be in the front and this one can be in the back. It can also be R, meaning it is not necessary, it can be kept in any order, okay, so what is binary, whose note is in the tree, all the children in it, each note cannot have more than two. It can be two, it's okay, like this one is a tree, 12, it's 3, it's okay, it ca n't be, it can be one, the note is its note, and the one on the left is smaller than the note, and the one on the right, so no, any one, it is smaller than you. If it is bigger than that, then three will come here and here, you will come on the side, three, tu can be made different from three, then this one and on its right side, like if you want to make it from tu, then one will be on the left of tu, and here it will be smaller than 3. Now You will make it bigger on the right side. 34 37 will come on the left side and four will come on the right side. It is the biggest one that will come on the left side. Nothing will come on the right side. So look here, what is left for 3 and what is right. And on the right, for n, the left and right a will be different, like if the value of l is one, then one can be made from one, for this, one more can be made from one, if the left side will be bigger, then only one can be made, possible three. For see, both the values ​​from three are one tu to left me aayega one both the values ​​from three are one tu to left me aayega one both the values ​​from three are one tu to left me aayega one tu three tu one is a, so from the start I minus one, after doing this tomorrow, it will give the record, okay, what is my less, it is as much as it is left, as much as Right, merge it with the left and right of the root, okay, see what will be the value of root, final tap, then made a note and returned it, put it in the vector, start, what will happen like see, now see here, now we start send. Now take the value here, like we had 3.23, so what will happen on the left side tomorrow, one on the left side, you on the right side, it has someone bigger, otherwise this side will come here only, do it tomorrow, now see what it is, four three. And whatever is yours has become smaller than this, so from the start, what will happen in this one, for this, the start will be made here tomorrow itself, and what will happen here is 21 and this one here is 43, so what we are doing is that if first a map Made it so that if the answer is a calculator then give it again and that's it, your code is ok, see you in the next video, please like and subscribe my channel.
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
134
the first approach is the brute force method in this method we calculate all possible combinations of starting stations and check if they're valid tour is possible for each starting station we iterate through all the stations in the circular manner calculating the remaining fuel at each step if the remaining fuel ever becomes negative we move on to the next starting station this Brute Force approach exhaustively explores all possibilities until a valid tour is found or all starting stations are checked the second approach is the greedy algorithm starting at a gas station we keep track of the remaining fuel as we visit each subsequent station the idea is to always select the next station with the lowest fuel cost if at any point the total fuel becomes negative it indicates that the current starting station cannot lead to a valid tour in such cases we backtrack and start again from the next station resetting the remaining fuel this process continues until a valid towards found or all gas stations are exhausted
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
111
hey everyone today we are going to service a little question minimum depth of binary tree so you are given binary and find the find its minimum depth so the minimum depth is a number of nodes along the shortest path from the root node down to the nearest Leaf node now if node is a node with no child no children so let's see the example so you are given this binary tree output is 2 because our minimum depth should be here so we have a two nodes so that's why output is two in this case okay so let's write Circle I'll show you two ways to solve discussion and the first of all I use a depth first search so if not root so you can't know there is no return zero and check left side self mean defs and a root top left in the check right side do the same thing so mean fifths and the root light and then check if left equals zero so we should return write plus one so if there's no right side in the case return left transform so if both sides we have both sides and take a in that case take a minimum depths left and the right and then plus one so yeah maybe someone is confused so especially here so why we shoot it down um light plus one if left is new so let I think our easiest example is like a one is a root node and then so we have a right side only right side so let's think about this case so in this case uh there is no left side right so but this in this case um minimum depth is not one actually two because uh this is a root no not Leaf node so that's why in this case we should return to so in this case uh left is no right so that means left equals zero so in that case um so there's a possibility that right side is a minimum depth and actually it is so that's why we should return so we should care about the right side if left side is no on the other hand if right side is no so we should care about our website so that's why uh highlighter program like this and if both case so if we have both child um we should return like a minimum number of left or right and the plus one yeah so let me submit it yeah looks good in the time complexity of this solution should be order of N and the space is order of H so N is a number of node H is a height of binary tree so easy example is like a binary tree is like a skewed and it looks like a linked list so in this case we have to visit all nulls so that's why a Time is on and the space also um so every time um we use like a stack space so that's why um space in the worst case space is the order of H height of three yeah so next I'll show you how to solve a discussion with a breast massage is a like a easier than this was such to understand okay so let me solve a discussion with um breast massage so if not loot in the case we should return zero if not the case um so initialized Q so I use DQ and Q dot append and we have two data in the queue so one is a current node and a current depth so first of all one and then start traversing while Q has data so we use a one more full loop and four in range and the length or Q and the first of all take the most left value over Q so node and the depths equal to Dot and pop left and if not node.lift node.lift node.lift or node dot right in that case we should return defs easy right and if node.left in that case um out of this left child to Q so Q Dot append and uh node.rift and the devs plus one and uh node.rift and the devs plus one and uh node.rift and the devs plus one if um node dot right so there is a right child we do the same thing Q dot append and uh node.bright node.bright node.bright and the devs plus one yeah that's it REM is submitted looks good in the time complexity of this version should be order of n where n is the number of nodes so in the worst case we need to visit all nodes of the binary tree to determine the minimum depth so that's why time complexity is order of N and the space complexity is also order of n so in the worst case so when binary three is a completely complete binary tree the maximum number of nodes in a level would be like a roughly any divide two so we eliminate the constant number so resulting o n space complexity yeah that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
1,644
hello and welcome back to another video today we're going to be working on lowest common ancestor of a binary tree too so in this problem you're given a binary tree and you want to return the lowest common ancestor of two given nodes P or q and I'm going to show you what this is going to look like in these examples essentially so let's go through number one so we have a tree here three five six this is not a binary search for it's just a normal binary tree and then or hero and so let me actually draw this in a different colors to give you some intuition so here we have nodes five and one right so here's node five and here's node one so essentially what you need to do is you need to find like the first ancestor of these two nodes so in this case it's actually gonna be the roux right like the node that connects them okay so it's going to be the root in this case it's the first note that like their path interacts that so that's going to be that for that one now we have another one and we have two different nodes so we have five and four so here's five and four and two nodes can be on the same path so if you actually go from four you hit this two node and then you hit this five node and now this five node is the lowest common ancestor because both of these nodes are on this path right so that can happen they can be on the same path they can also be on different paths so for example if we had like six and two their lowest common ancestor would be this five and now I think you should be getting the hang of it you know if we had six and four their lowest common ancestor is this five so it's essentially like if you draw a path from what both of these nodes to the root then it's going to be like what's the node that they first hit that's the same node okay so let's go to the last one so the last one is going to be five and ten doesn't actually exist in here so we need to return false so like I said um what you need to actually be doing is need to find the two nodes and you need to figure out like what node do they intersect at and there's going to be a few scenarios right they're either going to be on like they're either going to intersect somewhere or they're just going to be on the same path right we'll just like four and five and so we need to find how to actually do this and ideally we want to be able to do that in linear time so how do we actually do this like how do we Traverse a tree and what do we want to return or you know like to figure out what are our nodes so let's go for this example this six and four example right so we have node six and we have nodes four and we want to figure out how do we Traverse a tree and figure out the first node they intersect that it should be this node five let's say for this example right so how do we actually do that efficiently well what we can actually do is we can just Traverse down and we can just say like if we find one of the nodes we can return some value and then we can just check so for every node there's going to be a left right there's going to be a left a right and the node itself let's just call that maybe node right so if you think about it for two nodes to connect at a path that means that two of these have to be true either the left and the right or the node or whatever and let's take a look at some examples here so let's actually go back to this let's go back up here so let's we need the five and the one right so we're gonna go up here and you can see for this node three the left and the right are both a node that we care about so the left and the right are true here and then let's look at the five and the four so the five and the four once we go back up to this five right for the five the node and the right are nodes we care about right we're gonna pass up like we're gonna pass up some value so the note and the right are nodes we care about so essentially this is what we're going to be doing so what do we actually want to be returning right so we're going to have some result we're gonna set it equal to null just to start off right we're going to set equal to null and then what do we actually want to be doing so let's see what this is going to look like so we actually are going to start at node three we're gonna let's just say we go left first then we go right or something so we're gonna go here okay and we're gonna go here now this node we're going to go to a child right so we're gonna go to the child and the other child and let's just return we just want to know if a node we traversed actually contained a value we care about so what we can actually do is we can just return false if it doesn't so like for this node here we can just say like okay for the left child if the node doesn't exist let's return false so this left child will return false we're going to Traverse down to it's going to return false we're going to go to the right child we can return false you could all you could also skip this check you could just say like if the nodes children don't exist or return false that's fine too and now what we're going to actually do is for the note itself we're going to say if the node is equal to one of these values then let's return or let's set that node equal to true so for example for node six what's the left and the right going to be here so the left is going to be false the right is going to be false and the node is going to be true right it is a node we care about and then finally what we need to do is we actually need to return saying that we found like we either found one of these values or we didn't so we can just return if any one of these is true let's just return true so for six we're actually going to return true up to five so we're going to return true here now we are at five we want to go right now so we go right and now remember we go left first so we go left here okay for the so for this node seven what is this going to do let's delete all these for these node seven the left is false right because there is no left the right is false and for the actual value of the seven it's not a nobody care about so it's gonna be false the seven is going to turn false up to this uh so we're just going to write it up here it's going to return false okay what about four right we're gonna recurse back up to two we're gonna go to this right child over here so what about four the left is false because there is no left the right is false and the node is true so here we're going to return true so now let's go back up to this too what do we need to return so if either the node or one of the children is true we're going to turn true so we're actually going to return true here and now when we're up here so for this true by the way before we returned we need to check the left or right and the node right so for the left array and the node for this two so the left is false the right is true and the node is false right so we need two of these to be true to have a valid node so here we're going to return false now we go back up to this five okay let's take a look so sorry actually for this true we need to return true right because any one of these needs to be true to return true but two of them need to be true for it to be our lowest common ancestor so here we're actually going to return true so now for the five the node is false the left is true and the right is true so here actually we do have two of them being true so if two of them are true that is our lowest common answer session because that means we ran into both of these nodes right we were looking for two nodes and we found them and this is the first place that we found them so here we're going to update this result to be the five right essentially we're going to delete this null and we're going to say okay our result is five but how do we prevent ourselves from overriding this result so it's pretty straightforward we're just going to return true here right because only one of these needs to be true in order to return true so this five is going to return true now for this we're gonna go over here and then we're gonna go over here so for the zero obviously none of them are true because so the for the zero it's going to be false right false because it doesn't have a left or right and it's not a value camera so that's going to be false same thing for the eight I'm not going to write that out but for the eight it's also going to be false so this is going to return false now this one is also going to return false because it's not a value we care about and the left and right trials aren't either so that's going to return false now this we need to make sure that like somehow we don't override so and the nice thing is because we're only returning one value there's only going to be one node that's going to have two True Values so this node had two True Values sent into it right because the left and the right were true but the note was false but when we return we're only returning One True Value so now for this node three when we actually look at it the left is true the right is false and then it is false so there's only going to be one spot in the whole tree if you're just returning like this that two of the values are going to be true and so here if this is going to return true but it's not going to override our result so let's actually write down our steps we can make sense of it so Traverse the tree right recurs left then recurse right then if two of the values from Left Right node are true then update results to be that node finally return true if left or right or node are true else false right so that's what we're going to be doing and there's only going to be one node in the tree where this is going to be true and that's going to be this node here for this example but it's always going to be the case for this for any kind of problem because you're going to have one node with two True Values and then we're only going to be returning One True Value so we need two we're only going to be returning one so there's not going to be any other node that's going to be true or sorry it's not going to have this condition of two nodes being true this condition here okay so that's our algorithm Traverse left Traverse right and then if any of the values from the left or the right are true uh you need two of them you need two of those two of the values need to be true that means we found our lowest common ancestor okay so now we have enough to code this so let's just say we can just make a variable that we're gonna use later on so we could just say like non-local or we don't even know we'll non-local or we don't even know we'll non-local or we don't even know we'll just say result we're going to set equal to null initially and that way if we don't find the lowest common answer so we're going to be returning the result but we would have never have updated it okay so now let's make a helper function and that's just gonna take a note and so if not node that's like if a node is an empty node we're just going to return false okay now we're going to make a is not space correctly so now we're going to say uh let's go left so left equals Traverse no dot left then right equals Traverse no dot right now finally we need to check uh so we can just say value right so let's get the value of the node so we can say value equals one if uh no dot vowel equals P dot val or no dot vowel equals Q dot val LC here so actually we want this to be true or false right so false yeah and true so we're essentially saying if the no if the value if like the value of the node is equal to one of these then the node is a node we care about otherwise it's not so now we need to check do we have two of these so we can just say if left and you can actually add booleans and it'll just treat you as one so you can say F left plus right plus valve equals two right if two of these are true then let's update this result so we can just say non-local result because can just say non-local result because can just say non-local result because it's not in the scope of our function so we can't so we can read it but we can't change it unless we do this non-local or you have it be like a class non-local or you have it be like a class non-local or you have it be like a class variable you could say with self.rez variable you could say with self.rez variable you could say with self.rez there's a bunch of ways you can do it you can also make it on a radio like one element but so now he's going to say res equals this node so we're going to say node and then finally what are we returning we're going to return node uh or sorry we're going to turn vowel or left or right in the picture if one of these is true we need to be returning true now we're going to call Traverse on the root and then we should be able to return the result and we'll see if you screw anything up probably good but let's take a look okay so this should be none okay so you can see it's uh really efficient and it does work so let's actually go through the time and space complexity time we're just doing a standard um traversal right we're doing a I guess this would be a post order traversal we're checking the left we're checking the right and we're checking the root so that's just a little vent traversal um yeah for space so this tree is not guaranteed to be once again for all these Street problems usually trees aren't guaranteed to be balanced right so we can have something like delete this for a second so let's say our tree looks like this right that means we need to maintain a recursive call stack of all of these nodes so worst case scenario our whole path is just like this and then we need to go through this whole tree so then this would be a big o n complexity because you need to maintain a call stack of every single node as you're going down but for a balance tree so you could say this like if you were asked on an interview you know what would be the worst case space and will be the average would be like log in if the tree is reasonably balanced because then you're cutting off half the tree every time and then you're only going log in down so for a tree of you know nine nodes or what not nine nodes for a tree of eight nodes you would go only go down like three levels right so like this tree right here is not counting this part is seven nodes and you're only going down two to the third level so that's going to be the way it is okay so it's actually gonna be it for this problem hopefully you like it I definitely think it's a good one to know I think it's a pretty common interview question so I definitely make sure you know it and if you did like this video then please leave a like And subscribe to the channel and I'll see you in the next one thanks for watching
Lowest Common Ancestor of a Binary Tree II
maximum-number-of-non-overlapping-substrings
Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**. According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes `p` and `q` in a binary tree `T` is the lowest node that has both `p` and `q` as **descendants** (where we allow **a node to be a descendant of itself**) ". 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\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 10 **Output:** null **Explanation:** Node 10 does not exist in the tree, so return null. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` **Follow up:** Can you find the LCA traversing the tree, without checking nodes existence?
Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with smaller/larger starting/ending index). Sort the valid substrings by length and greedily take those with the smallest length, discarding the ones that overlap those we took.
String,Greedy
Hard
null
904
Hi gas welcome and welcome back to my channel so today our problem is fruit in basket so what is given to us in this problem statement is given to you here not you are visiting a form where what is yours a single There are fruit trees in the room which have been arranged from left to right. Here, I have given you one with the name of Fruits and where your fruits are representing all, the type of fruit is okay and the woman who is producing it. This is the type and here you have been given some conditions. What do you have to do while filling the condition? If you want to find the maximum number of fruits, then what is the condition here, we have to see what is given here. Right, you have only two baskets, okay, and one thing, you can keep only one type of foods in the basket, and in the second basket too, if you are keeping other types of fruits, you will keep the same type of foods, that is, it is okay. There will be different types of fruits in both the baskets. If seen from the father, whatever you pick will be only two types of foods because you cannot pick the third one because whatever you want to pick, you have to do it in the basket. Okay, now your second one. What is the point that exactly from the van tree you can move van feet from left to right. What you have to do is to pick one fruit, if it is possible then ok what is the third condition, once you see the rich tree with fruit date cannot fit in your basket you must stop i.e. fit in your basket you must stop i.e. fit in your basket you must stop i.e. you know that you can keep only two types in both the baskets, one If we find food of a third type in the second basket of one type in the basket, then we have to stop there. Okay, in this way, what you have to do is change your starting point and see from where we will start picking so that What can we do to find the maximum number of fruits? Okay, so you can say the starting point in a way, you are taking the decision about the starting point, so let's go through that thing with Samjhaungi. Let us understand first through the problem example, okay. What I was explaining till now is the problem statement, now what you will understand is the problem statement only, you will just understand it as a way of thinking, then we will see the code, how we will do it, okay, so what have I given you in the example here, I have given you give. Okay, so what is this is of one type, this type of this has also been given here, you will go left and you will go right, now what do you have to do, you have to take two baskets which You will also keep it in the basket. You can keep it in these two baskets only. It is okay, you cannot take it in the basket. You have only two given to you and it has been told that if you keep one type in this basket, then you cannot keep the other type in it. If you have put any other type in it, then you cannot put any other type in it, meaning if you have put any fruit of one type then you cannot put anything of the other type and no matter the number of fruits you can put, there is no limit to it. Okay on this, now you come here from here, suppose you have started, choose and get van type fruit, you came to know that we are adding van type food in it, okay then you got different type of fruit, then you will tell. Can't keep it in this, let's keep it in this. Okay, after that, is it of van type? Have you already kept this type of food? Have you kept it in this? We can keep it here, that is, from this tree, we can take a fruit from this tea. One fruit, one street, one fruit means total three foods, now it is over, you do not have any train, that is, we can take all three one by one, that means the answer will be our three, okay, now let us look at the second example, what is the second example? Look here, there will be two baskets, there will be zero, there is a van, you are there, you are my support, you start taking fruits from here, it is okay, found zero type, insert 0 here, then the van is here, so insert the van here. Then what will you do? Now tell me if you want it in both of them, yes, it is not possible for you in practical, according to the condition, because understand that you cannot take part in this because you took the team in zero type, then who knows, in future you will get the same meaning. If you don't get the maximum in both of these, then see how much you can carry till now till the van, how much you can carry till the van, then you can take the foods till zero van, now what do we do considering this, we start from here. Will pick, now let's remove these two brother, remove Jio type and van type from here, okay, we will start from here, then put van type in it, then move ahead, put tu type in it, then next also we got tu type. So, given the team in this, okay, next, if any three is found, then what do we have to do? Next, if there is any supos three type food here, then you have to stop here, you have to find where you started from now. Look, what will be your maximum? What will be the maximum here? Take one fruit from this, take one fruit from this, because you are inserting till here, it is not in your map, so from here you three people have already given you If you are now three, then what will be the maximum? What will be the answer for this? What will be three? Now for this example, look here is the van, you have inserted the van, start from here and propose, from here you are, you have given the team. Okay, then what is it that you have come on three, okay on three, we cannot add easy type of fruit now, so who knows, we can get the maximum in future, we will see here, how much maximum we have found till now, so let us know because We will have two fruits, one of this type and one of this type. Okay, now you take this as the starting point, neither of the man, nor of you, start from here, so here, starting from tu, you remove this, van and remove tu. From here this is the type, here there is no count, this is the type, okay this is tu hai tu type, you inserted it, then you got three type, then you did three type, then here you got tu type, then insert it in this. You can type in this what can you do i.e. from here till what can you do i.e. from here till what can you do i.e. from here till here we can take fruits from all the trees 1 2 3 4 then our answer will be four that was already there, now it is four, our decision depends on it i.e. If it is possible for us to take from here to here, it is depends on it i.e. If it is possible for us to take from here to here, it is depends on it i.e. If it is possible for us to take from here to here, it is valid for us to pick, then we can take from here to here. If this window was ours from here to here, then we could only take you. Okay, we took it from here to here. What happened to us, you are there are four in this, so four will be our maximum, we will take this window, so the window here will be a variable, so what you have to do is, if you have to handle this, then how will you do that, let me show you what we do. And if we understand through the third example, then see what is 12322 Now this is whether we will take the basket or we will do something, so for that we take the map and we know what we will do in the map, the condition we have to keep in mind. It will happen that whenever the third type is ours, which is not possible according to the condition, we have to take care of this, okay, so what do we do, take measurements, it is suggested that this is your map, here the type will be there and the value of its type. How much of this type has been found till now, this will be the answer. Okay, from here you take a left and a right. Okay, so your account will be van of feet. How will you find that, van is yours, this is yours till now in the answer. It was found out that there is a van in the answer, okay, you are of van type, you will put it in the basket or we are of van type, you have picked fruits in the basket, you have an account of this, you have also picked this one, so what will be the update in the answer, will it be yours, right? Maximum of Van and L - R + 1 i.e. 1 - 0 Van and L - R + 1 i.e. 1 - 0 Van and L - R + 1 i.e. 1 - 0 + 1 i.e. 2. Maximum of both. + 1 i.e. 2. Maximum of both. + 1 i.e. 2. Maximum of both. Your answer is 2. Okay, after that what you have to do is to come here. Okay, now we are here. What do you do? First put a team in it, then you check here whether this is the size of your map. Give it a greater. 2. Is it done? Give a greater. 2. Okay. So what to do now? We have to remove it. Okay, L. Now we have to increase our Let us see, if we remove only this then the size will remain but we will have to remove this also, so what will we do with the raise function? Why do we do the raise function because we have to remove both the key and the value, which means we have to remove the key also. So in this condition, we will erase it by doing this because its count is one, okay, we have deleted it, so we have deleted it, OK, now where is our L, where is A, from here, now ours is starting from here, OK, so here is your R. There is still a photo of the size that will come, okay now see what is your count, the answer will be L - R what is your count, the answer will be L - R what is your count, the answer will be L - R + 1 i.e. 2, here you will be here, now you will + 1 i.e. 2, here you will be here, now you will + 1 i.e. 2, here you will be here, now you will come here, you are of the type, you are already of the type, enter it and count. Two, its size is still 22, that is, our value is valid, we can pick it will be out L - R - L + 1, this is your three, if the count is - R - L + 1, this is your three, if the count is - R - L + 1, this is your three, if the count is more than three, then this will be the answer, then you go ahead to R. Congratulations, next, what is your 2, if you are there, you will become three here, has its size been increased? No, because we have only two types of foods, 2 and 3, so we will consider it as four, we got L, this R. This is L R - N + 1 got L, this R. This is L R - N + 1 got L, this R. This is L R - N + 1 so this is ok now let me show you the code also which was the mistake I made I did not explain this thing sorry for the date so look here in the previous video I made the mistake I am full When I uploaded it and the comments were so good that now I feel like making a video again, no problem, see, we will take the answer, in which we will return the answer, take a map, the value of intent type in it is ours, now we will come to this. We will keep moving forward till we reach the end. Okay, what will we do in Fruits MP? We will update the type of fruits and in the meantime we will also check whether its size is greater. If it is done then it is not done. What to do if there is one count then remove it from there because if you remove it then only you pick the value then its size will still remain &gt; 2 so what you have to do is &gt; 2 so what you have to do is &gt; 2 so what you have to do is erase it and do minus from here and k plus Keep doing it, okay, that is, what do you do on the left side here? J + 1 answer will keep J + 1 answer will keep J + 1 answer will keep updating and I plus will keep getting plus. In this way, what will you do, you will find the answer, then here you will return the answer. Okay, so I hope you have understood. If you liked the video, please like, share and subscribe. Do it and please do n't be negative with me because if you want to give me some feedback then please give it in a positive way. If you look at it in a negative way then I will definitely feel bad. Somehow you are affecting your personality negatively. If you are doing well then thank you. Thanks for the suggestion.
Fruit Into Baskets
leaf-similar-trees
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Tree,Depth-First Search,Binary Tree
Easy
null
37
hello everyone in this video we will be solving the problem sudoku solver its number is 37 on lead code yesterday we solved the problem valid sudoku where we were going through all the entries in the board and verifying if the sudoku board is valid or not and here we will be solving the sudoku problem the basic rules of sudoku are each digit from 1 to 9 must occur exactly once in each row each column and each box the boxes like three by three boxes so usually in a sudoku board there are nine boxes nine rows and nine columns here we are given a board with few numbers already added we need to fill out all of the empty spaces this is a hard problem or need code so i really recommend you to just spend some time understanding the approach that i am going to be taking in solving this problem and once you understand that i'm sure you'll be able to solve it in no time without wasting any time let's switch to our whiteboard session and discuss how it can be sorted i will be using the example given in our problem statement so if you look at this problem and the first approach that you would think about is to try all possible combination in each of the empty spaces and see if the board is valid or not but if you think about the complexity and the runtime it would take to solve the problem that would be pretty huge that brute force approach will definitely take much longer to solve the problem i want to first start with talking about how it can be solved using brute force and then find out ways of improving it usually the approach would go something like you would start with iterating through all the numbers so you are pointing at 5 is already available and the problem statement states the numbers that we are already given are the valid ones we only have to solve it by filling out the values in the empty spaces no changes with 5 then the next number is 3 again no changes now we stumbled upon an empty space here we need to try all possible combination starting from 1 all the way to 9 and then verify if that number is a valid number based on three criterias row column and box is that number unique in the row is the number unique in a column and is a number unique in the box if all three criterias are satisfied we can put that number in that empty space but we cannot be sure that number is supposed to be there we won't be able to confirm that unless we continue and solve the whole sudoku problem so if i go with this logic here i am iterating through all the numbers if i try one is unique in this whole row one is unique in this whole column and one is unique in this whole box the first box where it belongs so one is definitely a potential candidate that i can put over there so i will put one for now and then continue iterating so now i am on i am pointing to this location and again i will start with iterating to all the numbers because it's an empty space so i will try with one i cannot put over here because there is already a one in the row so this becomes invalid also one is there in the column two so one is not the right choice now i will try 2 so let's try 2 is unique in this whole row 2 is unique in the column and 2 is unique in this box so 2 is definitely valid number to be added to that space similarly we will keep on adding values to the empty spaces and validate if our row column and box validations pass at some point if you haven't made any mistake in our assumption the validations will fail and we will not be able to add a value in a box because it is either failing the row or a column or a box validation so now we will have to go back to the first spot where we made the assumption and try a different pair because the number that we tried did not work so we will have to do it again i will have to update this first value to 2 and then continue the iteration forward as you may have noticed we will have to make a lot of combinations and trial and errors to solve this problem using brute force this approach will definitely solve the problem but it is not a viable solution because of its runtime complexity so now let's think about how we can modify this solution to make it better the main problem in brute forces we are restarting the whole assumption process from scratch instead of doing that how about we just do a backtrack approach where we just go a layer above or the previous assumption and try to change that and continue the loop so instead of going to the first empty space that we made an assumption for we will just go a layer above the previous empty space and then try to change the value and continue the loop so here again iterating through the first the second no changes in the third one i will try one is valid so i will go to the next one now here i will try two after going through all the iterations let's say i'm adding all the values here which i think are going to be valid so i'm adding eight here let's say i'm adding 9 here just like before let's assume in the next spot i do not have any valid values from 1 to 9 that i can add there without breaking any of the rules instead of going back to the first assumption we will go to the previous assumption we made so we will go to 9 instead of trying out 9 here we will try the next possible number in our list because this is 9 there is no number after 9 so this also becomes invalid so we will go to the previous assumption we made before and try to change that so here i am at eight so eight is not a valid number here per my calculation so far so i will try to make this nine so with this as nine i will continue my loop forward so basically i am going to do a backtrack of all the steps that i did to solve the problem if it work well good enough it does not work i will undo the change and try something else at this spot my current value is 8 and i will update it to 9 continue the flow and see how far i can get we will start the process of assuming what values we can put in the next spot and make it valid if i'm still unable to find a valid value for the empty space i will backtrack to the last change that i made try undo that change and try a different combination and continue the flow to see if that one i hope you are able to understand the logic that i am trying to implement here let me show you the c sharp implementation of this logic to solve this problem here is the c sharp implementation and this is the main method i am first validating if the board that is provided as an input is not null then i start with calling this helper method called solve where i trade through all the numbers give all the spaces in the board if the value of that space is a dot or empty only then i am going further or else i'm skipping over all the spaces which has a value already i validate if it is an empty space or not then i have to try all possible combination that i can enter in that space so i have created this variable nums which contains all the characters 1 to 9. so i iterate through all the combination and then using that number and the row index and the column index i am validating if i were to add that number in that row column or box is it going to be valid or not so in each of the method i am validating if i were to add this number in this row index will it work i'm getting the corresponding row in checking if there is already an item in the row that matches to the number that i'm trying to add the same logic applies to the column where i am looping through all the entries in that column by index and then checking if it is equal to num that i'm trying to add if there is an entry then return false else we are returning true for validating the box part it's slightly different i am taking the upper range and lower range of the box for column and row index because there are going to be a range if i am looking at box number 0 the first box basically or the range of row is going to be 0 to 2 the same applies for the column so i am using that logic to calculate the range for row and column and i've created the simple and readable code that gets me those range so if my i or the index is less than 3 it means my range should be 0 to 2. this can be solved mathematically as well but just for readability and simplicity i wrote it down using if else condition after getting the row range and the column range i am looping through only though only the box where that number is supposed to be added and then checking if that number already exists if the number exists it will return false assuming if all the three validations pass then we are setting the number in that board and then calling the method again it will keep on iterating through all the values until all the combination return true if any of the combination returns false it means we need to undo the change so we will go to the else condition and reset the space value to md so that it we can try a different combination using this for each loop in case we are not able to find any valid number to be added to that space we return false this will tell us that we have made some error and we have added some incorrect value in the previous assumptions and we need to fix that i hope you were able to follow my solution if you have any questions or concerns please feel free to reach out to me this solution is available on my github repository i will be adding the link to this solution in the description below i will also add a link to this valid sudoku problem from where i got some idea about how we can solve this you can check that out as well thank you for watching this video and i will see you in the next one
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy **all of the following rules**: 1. Each of the digits `1-9` must occur exactly once in each row. 2. Each of the digits `1-9` must occur exactly once in each column. 3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid. The `'.'` character indicates empty cells. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\] **Explanation:** The input board is shown above and the only valid solution is shown below: **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit or `'.'`. * It is **guaranteed** that the input board has only one solution.
null
Array,Backtracking,Matrix
Hard
36,1022
253
hello friends today I will share my solution to the meeting room to and I have tried to solve this problem many times so I want to share my solution with you okay given a array of meeting time intervals consisting on start and end times find the minimum number of conference rooms required let us see the example first the start time 0 and hummus 30 and because we haven't had any room so we and at this time we need a one room and then we see the second meeting start hummus fight in the N times 10 and then we can see the start Hamid's smaller than the previous meeting which is anti 13 so we need another room and we see the third meeting the start Hamid's 15 and it is less than the previous meeting which start honeys but anthem is 10 so we can use their room we do not need a narrow room so in total we need the two rooms so and we can see first we should thoughtful these intervals by their startin in this case we can schedule the meetings but how do we check if we can reviews a reuse previous rooms as just to compare the current interval starting with the earliest ender meetings and TAM in this case a priority queue can be used which in the minimum heap so because we saw we solve these intervals and force the time capacity will at least be an logon and then are you we use a priority queue and which each ad and the remove will use okay K is the size of the priority queue and their peak minimum use constant time so in total the time capacity will be a noggin and what the space capacity will be Locker healthy oh and because we will oh we will Space Camp a sir will be all K which K is the size over the priority queue and enlasa which a certain the hip size which is minimum number of conference rooms are required so let's cook but after we do some education check is intervals now for intervals lens 0 to 0 which after return 0 because we have no meeting to do then we sort of this all right intervals and as I 0 I will get you a zero start I'm sorry start minus Phi 1 start so now this interval sorted and now we need up try already Q which we just needed to save the integer which is the anthem of the meeting which is a minimal hip and you priority queue and okay let's do the iteration for into War I in there even indoors in which case it should are we in each case issue that we reuse a room that will be their hips size larger than zero and the HIPAA topic is less for accordion the recurrent intervals start huh in this case we don't do not need that you allocate another hip so we pour this end time and we should update their newer end time which is I thought Enter so finally we just two returns or hit the size so let's see example the first in the one is nearer 30 and now the hips are equal to zero so we just offered the inhalation thirty into the hip now hip size is 1 then we see the second two five 10 hip size in margin one but the hip peak which is thirty is larger than the five so we do hip after the ten into this hip Indiana size issue the last interval which is 15 and 20 hip size is eco is larger than zero and the hip peak which is Tim is smaller than the 15 so we pour the always end time and offer our new intern in the yeah I think another will be right okay that's all um thank you for
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
83
in this video we'll be going over remove duplicates from sorted lists so given the head of a sorted linked list delete all duplicates such that each element appears only once return to linked list sorted as well so in this first example we have one and two if we remove the duplicates one we get one and two sorry that's our result let's go over the dot process since the input list is sorted and sorted in ascending order all of the duplicate nodes are grouped together this means for each of the elements for each of the node x we will first check if x dot next has the same value as x if x dot next does contain the same value we will want to skip the current node we will only append the last node of each duplicate group so for example you have x and you have three node stats are the same we only take the last node to only take this node let's go do the pseudo code so create two variables just um the sentinel head of the new list and estelle the sentinel tail of the new list so it will be initially has head and node our current location inside input list so while node is not known we'll first search for the last node of a duplicate group so while node.next node.next node.next is not known and node.next is not known and node.next is not known and node.next that value is the same as current node while the next node has the same value as current node we're going to move our pointer forward set node to node.next now we want to append to node.next now we want to append to node.next now we want to append the current node to our resulting list so set as tail.next i'll we'll first disconnect as tail.next i'll we'll first disconnect as tail.next i'll we'll first disconnect the current node first so create a variable next and set it to node.next and set it to node.next and set it to node.next set node.next to node and set and then we'll append the kernel to our new list set the tail down next to the node and then update the tail to the current node now we want to move our pointer forward to the next node set node to next then we can return the sentinelhead.next which will be the sentinelhead.next which will be the sentinelhead.next which will be the head of the new list without duplicates now let's go over the time and space complexity so time complexity is equal to o of n where n is the number of nodes in the input list all that is visit each node once and my space complexity let's go to off one because we just modify the input list so let's create our two variables oh our three variables beginning so while node is not good to know i want to skip over the duplicates we want to append the current node to our resulting list but before that we need to save the next node append the current node to a resulting list and then move my pointer forward to next and then return the head of the new list let me know if you have any questions in the comment section below 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
498
hello so this question is diagonal driver so you're giving an environment tree and then you have to return an array of all the elements of the array in a diagonal order so uh this is a question and then let me just summarize it very quickly so you're starting from zero sorry zero index and there's only two direction you can go one is called top right the other one is called bottleneck so when you go from top right uh you can start them from here starting from here and for the bottom that you're starting from here right so how do you uh how do you know uh which position you are going to start the direction uh this is going to be based on what your index so just for example and this is zero this is one this is two this is zero this is one this is to run so if you notice I uh follow for all value in the cells right which is called what the top right and then the value in the an even value in the cells is called bottom left but this is not a point this is uh the value inside the metric can be changed but for the but the index cannot be changed right so if you notice the index which is even like if I uh if I say 0 plus 0 and this is going to be zero plus two right this is what two zero plus uh there's no oh there's no zero so it's going to be one plus one two plus zero right equal to two and this is what two plus two so if you know this is what even number right and this is for top right and then on the other side uh this is definitely what the all the R value right so this is what top right this is bottom left so uh once again like once you know this index and you can basically just uh Traverse the array and then let me just start coding so uh let's get it so I'm going to say and we go to match with the lens I only go to make sure at zero dollars which is column and we'll write now I'm going to assign car equal to zero and c equal to zero which is going to be my uh matte index in there I also need to create a rate right in Array I'm going for results I'm going to take new ends subscribers so I'm going to assign a value into the result array right so it's going to be from 0 to end of the result and I plus so uh I can what I can definitely just assign the value into the result array right so I'm going to say r AI is equal Y is equal to mat s r is C right so R and C represent the index for the 2D array and I represent the index for the 1D array which is the array you want to return so I can just check if R plus c mod by 2 is equal to zero this is going to be what even number right and I also this is like all number and then once again I already know this is not what go top right and this is for thousand sometimes right all right so uh there's two scenario when r equal to zero right uh you either you move the colon uh value by one or what you move the R value uh by one right so uh which one go first this is actually matter right uh because the order matters so if you say if our if r equal to zero and then you move your colon and I'll save our c equal to uh the last column should be what a minus one and then you say um R plus right so when you hit this point this is r equal to zero this is or equal to zero right but at least one you increment the column but at least when you uh you increment your column but it's already out of bound right so you have to check if this is the last column so uh the words come first right so if you say this is the last column then you increment your row by one if this is or equal to zero then your income your column by one and everything just go uh top right so when you say top right it's going to be what uh top right is for uh R minus C plus right and this is going to be exactly the same thing for bottom left right so they are choosing or you have to worry about right uh if you hit the last row or what or C equals zero right so uh I'm gonna just say R is equal to y n minus 1. so this is the last row then you increment your column by one I'll see if c equal to zero right so the order matter so just follow the pattern right and it's c equal to zero then you increment your r and else so this is just the order you want to go from Top uh top right to the bottom left right so this is what um R plus C minus and at the end basically you just work return results so this is the solution so let me run it so hopefully I don't have a mistake so long 18. this is the typo all right submit all right so uh without any doubt like this is super simple and just a little bit math and for the timing space this is uh this is a space complexity this is M times n which is raw times color for the time uh all of M10 right the length of the array is n times n so this is solution so uh if we're fine then you can watch the debug mode so I'm really just but sorry let me use console develop I'm going to pause right over here and then default and I quickly just go over one by one and then if you have any questions you can just watch it right so going keep going so just look at it in this when they change right and then you also go get the update value in the array so here we go so that's it so if you have any question leave a comment below and I will see you later bye
Diagonal Traverse
diagonal-traverse
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `-105 <= mat[i][j] <= 105`
null
Array,Matrix,Simulation
Medium
2197
1,857
welcome to Pomodoro Joe for Sunday April 9th 2023. today we're doing leapco problem 1857 largest color value in a directed graph this is a hard problem all right so there is a directed graph of n colored nodes and M edges the nodes are numbered from 0 to n minus 1. you are given a string colors where colors index I is a lowercase English letter representing the color of the ith node in the graph you are also given a 2d array edges where edges index J is equal to ajbj indicates that there's a directed Edge from node a to node B a valid path in the graph is a sequence of nodes such that there is a directed Edge from X to x i plus one for every one less than or equal to I less than or equal to K blah okay the color value of the path is the number of nodes that are colored the most frequently occurring color along that path return the largest color value of any valid path in the given graph or negative one if the graph contains a cycle whoo alrighty so let's break this down a little bit we are given a graph which is basically a set of nodes with directed edges a valid path in the graph goes from some start node to some end node and along the way each node contributes a color value to the path now we're trying to find the path with the highest frequency or the greatest count of one particular color so for example in this one we've got a couple different red colors a blue and a purple so we're looking for this path which has three Reds and the answer will be three okay so man this is going to be a hard one all right well let's put 25 minutes on the Pomodoro Timer and we will get started so the first thing I'll note with this problem is that we're not given a number of nodes so we have to derive that from the number of colors because it says colors at index J is or colors index I will represent the color of the ith node so we know how many nodes there are by how many colors in our color list uh I think it's a little bit confusing so this is not necessarily the number of colors there are this is the number of nodes there are and this is the color of that node so we'll start out we'll have some result we'll set it to negative one to start and we will return a result at the end now let's get a couple Basics out of the way so we'll have some node count that's going to be the length of our colors so this is the node count and not the color count the colors are represented by a lowercase English letter so that means there can only be 26 colors because there are 26 letters in the alphabet so the first thing I like to do in a problem like this is let's convert these edges into a format that we can actually use so let's see we'll have an edge map not just to be a default dictionary see that'll be a default dictionary of list so in the edge map our key is a node and the value will be a list of connected nodes all right so for every Edge and our edges we can actually unpack this so let's say for every source and destination in our edges then our Edge map for this Source will include the destination so this will come in useful when we actually Traverse our graph so now we can say for a given node give me all the connected nodes okay one thing I'll point out here is we are not given a root node we don't know where we're going to start which means that any node could potentially be a starting point but I think we can narrow that down a little bit because we can actually look for nodes that have no inputs okay so that's going to be key so if we're looking for nodes and their inputs there are a couple things that tells us number one we can find all of our start nodes and number two that's a good indication that we might want to use something called cons algorithm so this is called what do they call this topological sorting something like that anyway the idea with this algorithm is we'll find all of our start nodes then we'll Traverse our graph by processing that start node then we will push our result down to the connected nodes and then we'll burn that connection just like burn that bridge so we'll start at node zero we'll push whatever result we have to two and one and then we'll burn that connection then we'll look for new start nodes so once we burn these connections now we look for nodes that have no inputs so 2 no longer has an input and one no longer has an input so then we'll process two and one we'll push the results from two down to three and burn this node or burn this connection then we'll look for new start nodes that'll be three and so on and so forth so the basic process in cons algorithm is find start nodes by looking for nodes that have no incoming connections then for every start node do the processing push your results down to the next set of nodes burning that bridge and then look for new start nodes so when you burn this bridge you can just check hey does this node still have any connections if it doesn't then that becomes a new start node so let's maybe just work on that part of it and then we'll come back to the colors later okay so in order to do this properly then we actually need to keep track of how many incoming node or incoming connections we have so in addition to our Edge map we'll have an input Edge map or count let me separate this because it has a different meaning so the input Edge count where the key although I think we're just going to be using an array here the key will be the node I'm going to Value will equal the count of input edges sometimes this is called an in degree but I'm going to call it the input Edge count here and that's going to be let's see we're going to start at zero for every node so that's going to be our node count it's going to be an array of zeros of the length of the number of nodes we have okay so that's our input Edge count so every time we get an incoming Edge we'll increment this so we have an input Edge count that's of our destination and we'll add one okay so now we have two things we have an easy way to get all of the connected nodes from a starting node and we have how many input connections a given node has so now we can do our traversal so first we'll have to find our starting nodes all right I'll just call it start nodes so what is our start node is just a node that has no inputs so in this example zero is our start node that just means that there are no nodes that can lead up to this node so this node has to be the starting point there can't be anything before this one all right so for node all right so we're looking for every node in the input Edge count but we actually are looking for the node count being zero so we're going to enumerate this so enumerate we'll return our index which is our node number and the count which is how many edges our input edges to this node now if count is equal to zero well then this node is a start node Okay so we've found our start nodes all right so now we do a traversal this will be very similar to like a depth first search traversal we'll keep a q of all the nodes that we need to process we'll pop a node out of the queue we'll do the processing and then any new nodes that we need to add We'll add those to the queue and we'll keep going until we run out of nodes in our queue when our queue is empty then we're done so we'll have some starting queue now our starting queue in this case is just the start nodes and while we still have some nodes in our queue we'll pop a node out it doesn't really matter what order but I'll do pop at zero so we'll pop a node out of our queue now we need to process this node now I'm not going to go through what we're doing for the processing just yet at this point we're just going through the traversal part of the algorithm then we'll go back and figure out how do we actually process these nodes so we'll come back to the processing part now once we process the node then we have to go to all the child nodes or all the connected nodes burn that bridge and put any new start nodes into our queue so for connected node in let's see that's going to be in our Edge map for this node so we will be pushing our data down to these nodes but for now I'll pass on that as well so for every connected node we'll go through we'll push our data down to that node now what are the two things we need to do after that we need to burn this bridge and then check to see if this node becomes a new start node so we can just say input Edge count for this connected node we'll take this bridge away this Edge disappears so we're cutting these edges and now we check to see if our input count is zero so let's see we'll just grab the same thing and if this is zero then this node becomes a start node so we can add it to our queue all right so this is our basic con style graph traversal we have a bunch of start nodes the start nodes are any node that has no input Edge that means it has to be the start of some path we'll put those in a queue then for every node in the queue we'll pop the node out of the queue we'll do some processing we'll come back to that then for every connected node so for that node we go through every connected node and we disconnect it we basically break that edge so we'll remove one Edge from its connected node count now for every node that no longer has any input edges we check if it has no input edges it becomes a new start node so we add it to the queue all right so that's our basic traversal now there's a couple things here one is detecting Cycles so we can detect Cycles basically by counting how many nodes we've processed so I'll call that processed node count and we'll start it at zero now as soon as we pop a node we will increment our account all right so if we go through and we process every single node one time then we've got no Cycles however if we go through and we miss nodes we don't process them that means we've got a cycle so down here we can just check if our process node count does not equal our node count that means we had some cycle and we can return negative one okay so this gives us our basic traversal this should at least run it won't cause any Loops infinite loops but we're still missing the main piece processing the note so when we get to this node at this point we want to know what are all the colors or the color frequencies that led to this node now some paths that lead to this node might have a ton of purples other paths might have a ton of green at this point we don't really know which path is going to give us the best answer so we're going to choose essentially all of the paths we're going to keep track of the maximum of every color that got us to this node because at some point down the line we'll get to a node that just needs to know what's the maximum overall now you might say well if I'm keeping track of the maximum purple here and the maximum green there's no path that has both of those maximum values and that's correct there is no single path with both the maximum purple and the maximum green probably but it doesn't really matter let's say you choose the Green Path ends up being the right answer now the purple path we would have the wrong count for the purple path for that specific Green Path but it doesn't matter we're not keeping track of the actual accounts of all the colors we're just trying to find the maximum of the maximums so in this case processing this node means keeping track of the maximum colors that got us to this node we are totally going to run out of time okay so we need to keep track of the colors that led up to this node so the maximum frequencies for all the colors that got us to this node which means we need to keep some storage of colors for node it's a mapping of node to color frequencies so let's create something out here for that let's see I'll do this up here I'll have a key and that's going to be the node and again I think I'm just going to make this a 2d array so we'll have a key quote key that's the node and the value will be a count of colors or per color count I'll call it that okay so that means for every node we will have an array of 26 values those values will represent the count for every color because there can be up to 26 colors because every color is represented by one letter of the alphabet and they're only 26 letters all right so this will be color count for node and that's going to be an array of let's see zero times 26 for the colors and that's going to be 4 all right so this basically creates a two-dimensional array where on the one two-dimensional array where on the one two-dimensional array where on the one dimension and we're at a time all right I'm just going to push through we're ignoring the Pomodoro Timer sorry folks I just need to get this done so here we go so we create color counts for node so this is going to be a two-dimensional this is going to be a two-dimensional this is going to be a two-dimensional array where the First Dimension or the row is going to be the node and the second dimension will be a count of all the colors now in that color account the index is the color and the value will be the count of the color so you can think of this as like a grid where we have a node on one axis like our y-axis and our colors on the like our y-axis and our colors on the like our y-axis and our colors on the x-axis and it's just a color count okay so the color count for the node what does this mean well this is going to help us as we go through we're going to say from our start node what's our color count well at the start it's going to be zeros well then we will process the node and by process we will basically be saying let's add our color to our color counts for this node all right so the color counts for this node at this color well we're going to have to do a little bit of fudging here so let's just have a function call index color index or index for color I'll do that so I'll have a function giving us the index for the color and our color is just our colors for this node I'll actually break that out I'll say color is equal to colors at this node all right so this node's color and we're going to get the index of that color and we will increment it by one because now that we're at this node we have one more of that color in our path all right so what's our index for color function well let's see I'll Define that up here well so this is just a conversion from a character a lowercase English letter to an index and our index range will be from 0 to 25 so we will just return we can use ORD now ORD will give you the ASCII value of a particular character so we'll take the ASCII value or the ORD of color and we'll subtract ORD of lowercase a so basically if we have a we subtract a it will give us 0 B we subtract a will give us one so this will give us our index for that color okay so we're processing the node by adding our color to our counts of colors so far and now when we push our data down we'll be pushing these set of colors the same set of colors down okay so how do we push the data down this is a little bit tricky so we will be saying I want to keep the maximum values for every color between my set of colors and this connected node set of colors I'll write it and see if it makes sense okay all right so we're going to get the colors for this connected node by basically grabbing it out of the colors counts for node and passing in the connected node as our index so this will be our connected node's current set of colors now we just want to keep the maximum colors for each one of these sets of colors so we have our own sets of Colors Let's see I can get that out here Okay so we've processed the node by incrementing our color the color of this node in our set of colors that led to this node we're going to keep track of that current set of colors now we're going to go through our connected nodes colors and we're just going to keep the maximum of those two so let's see I in range 26 so we go through every color okay so we're gonna grab our connected nodes colors then we'll go through every color if our current color has a greater value than our connected node color it means that we could take a path that gets us to this node that has a greater chance of or a greater frequency of this particular color so we're going to update our connected node colors at this index to match our current node colors at this index okay so this handles our processing one final piece of the puzzle so this will give us all of our connected nodes and all their frequencies of their colors we want to find the maximum so at this point I'm going to update the result we could wait till we get to the end but I think I want to update my results now so I'll say my result is going to be the maximum of my current result or the maximum of this connected colors so let's see I'll call it connected colors Max don't want to do it here yeah I'll do it here I guess I could do it here that might be better actually yeah let's do that so we'll update a result out here our result will be either our current result or this new value whichever one's higher oh man let's see if this works I'm a little bit nervous too many there we go start nodes plural oh I need to get the max of this set of colors actually I could just do this that might be a little bit slower because we're making the same function call twice but we'll give it a shot and we pass oh and we actually crush it holy smokes we beat 95 for runtime and 78 from memory whoa I was not expecting that all right well sweet I'm super pumped awesome well it's a lot of code I'm sure there's ways to clean this up but I'm going to leave it here because we're out of time hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`. A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path. Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_. **Example 1:** **Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\] **Output:** 3 **Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`. **Example 2:** **Input:** colors = "a ", edges = \[\[0,0\]\] **Output:** -1 **Explanation:** There is a cycle from 0 to 0. **Constraints:** * `n == colors.length` * `m == edges.length` * `1 <= n <= 105` * `0 <= m <= 105` * `colors` consists of lowercase English letters. * `0 <= aj, bj < n`
null
null
Hard
null
494
okay so welcome back and it's another day like a problem so today it's called Target sum so this is a medium level dynamic programming problem where essentially you're just given an array called nums here as well as a Target and so this type of problem is basically you want to find out all the different kind of expressions or really combinations of these numbers that can build to this target but the only thing that you're really doing here is you're just taking these numbers and flipping their signs and so you can see there can be just sets of combinations of variances of which ones you're making a positive sign and which ones are making a negative sign so to do this the first thing that I thought of and this is what I typically do is try to decide what the recursive relationship will look like and so basically you just want to have some pointer that's pointing to whatever current number you're considering and so initially we're going to have that index set to zero which is saying okay what are we going to set this sign as until you can go down kind of two paths here you can either make this a positive one or you can make it like a negative one and so from here then you can kind of increase uh this index to then be considering a basically an index one here and then you're looking at okay do I want to basically add one here to get to 2 or do I want to subtract one by making this a negative sign it's basically bring us back to a sum of zero and so if we keep expanding here so now we're at index two so we're considering this number here we can once again either decide to do plus one which will bring from two to three or you could say subtract one which is minus one by negating this and then bring it back to two but basically you just want to sum up all the possible ways where basically you're reaching um that Target number of three in well this is actually a one case there so to kind of translate this into an actual coded solution typically what you want to do for dynamic programming is you want to Define some recursive function here so this will be a top-down function here so this will be a top-down function here so this will be a top-down kind of memorization approach and so once again we need to Define like what index we're currently pointing at as well as like what is the current running number that we have and so why don't we kind of start at our Target so when reach zero that's kind of our base case and we propagate that answer up and so initially we're going to be looking at the first value right and deciding do I want to negate this or make it a positive sign but we want to start with this target number that we're trying to achieve and so we'll just specify that as n and I in our function here so once again because this is for cursive in nature you need kind of that base case and so that's going to be okay if our index is basically equal to the length of our numbers then naturally we've kind of Hit the last number in this array and we don't have anything else to consider and so in that case okay let's return true or return like true as in this is a possible combination um if we've actually hit zero you could also do this inverted so you could say okay we could set this as zero and once this is equal to or return true if we hit our Target but I kind of like uh starting out our Target and going downwards so why don't we return one to represent this is one pulse combination as long as our current number is basically equal to zero otherwise let's just return zero because this isn't a possible a combination otherwise then we want to make those two different choices that I talked about and so that's just going to be basically two different uh recursive calls here to this function but for each one we're going to want to move on to the next number of course but one of them will be okay why don't we use the positive version of this right and so that would be whatever number is that I and we're basically adding uh whatever current whatever number we're currently at or we can do the opposite of okay um why don't we do I plus 1 and then basically negate it now I think I just realized uh what I did wrong here and so because we're adding here we don't really want to do that in this case uh since we're going top down so why don't we uh instead or actually this should work if we cache it oh uh and we want to add here because we're doing positives operand type because we need nums at the current index looks good and success so this is one possible on path what was kind of slipping up there is that you can also do it this way where okay why don't we specify it as zero and then if we hit our Target then this should also work here yeah sorry about that so just a second ago I thought the math wasn't working out but you can do it both ways so uh yeah in terms of time and space complexity um there are going to be uh the same thing in this case where essentially you're dealing with an O of basically your target number I'm multiplied by basically the length of this nums array and that's because in the worst case this nums array is going to be just a whole bunch of set of ones and so you're going to have to iterate through all those ones but then also um you'll be only like subtracting one each iteration so it's going to go all the way to basically whatever this target size is okay so yeah I hope this helped a little bit and good luck with the rest your algorithms thanks for watching
Target Sum
target-sum
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`. Return the number of different **expressions** that you can build, which evaluates to `target`. **Example 1:** **Input:** nums = \[1,1,1,1,1\], target = 3 **Output:** 5 **Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 **Example 2:** **Input:** nums = \[1\], target = 1 **Output:** 1 **Constraints:** * `1 <= nums.length <= 20` * `0 <= nums[i] <= 1000` * `0 <= sum(nums[i]) <= 1000` * `-1000 <= target <= 1000`
null
Array,Dynamic Programming,Backtracking
Medium
282
252
hey and welcome today we will solve meeting rooms interview question which mostly asked by top companies like that so let's get into it first example here we have a two-dimensional array which we have a two-dimensional array which we have a two-dimensional array which contains array elements that holds start and end time for each meeting I thought instead of explaining this a visual of what is happening could be way much more explanatory so here we are as you can see we have conflicts one person cannot attend two meetings at the same time so that is why the result is false here second example this time every meeting happens in distinct time intervals so that is why we are returning true as a result we can definitely come up with a brute first solution as a starting point where we compare intervals by having a helper method called overlap and passing two intervals into it so what does this overlap function do is simple against some visuals if you consider two distinct meetings the minimum end time of those two literally I'm pointing to the end time of earlier meeting might be less or equal to whatever the max of start time of Bose will give us literally this time we are talking about the start time of second meeting if that is the case we might return false from this function because they are distinct right they don't conflict with each other but this will not be the case for meetings that are overlapping the minimum end time of those two meeting will be larger than the maximum of starting time of those two here and that is the conflict Zoom there so we might return true for that indicating these two intervals are overlapping this is completely a fair logic but the downside is that it happens inside of Double for Loop so time complexity will be all of n in power of 2 and not efficient enough well there is still a better way to solve this by help of sorting let's consider these intervals per second in order to remove the cost of our second iteration we can sort the meetings based on their starting time to get them in a correct timeline order and if we do a simple iteration over them we can check if the ending time of each meeting is not more than the starting time of the next month to it and of course if so we might return false because that's the condition for our overlap otherwise if we haven't meet that condition during our attrition like in this case here we might return true meaning that these meetings are distinct and one person can attend them all by doing this we will have a bit of optimal time complexity but don't think that since because of we will have one iteration it will give us all of end time complexity in fact we will have oauth and login more on that at the end of the video where we explore time and space complexity now let's jump right into the code so here we are in vs code this time I have two test Suites in the right hand side one for True cases and one for cases with overlap which we should return false for it and in each of them we are testing three conditions in normal distinct case only two meetings case and finally the case that intervals are unsorted so first we will sort that right based on their starting time and the point is we will not going to assign it into a new variable because it is unnecessary and it will take all of any space then it's time to do orbitration and since we are checking each value with next one in the row we might consider the last item which has no neighbor and that is why we have negative 1 after the length so as we discussed it before we will check if ending time of a meeting is larger than next month's beginning then they are overlapping and we might return false immediately and break out of the loop otherwise if we pass through or attrition without returning false we might return true indicating that there was no overlap now I will open my terminal if I run this test cases should be passing let's jump back into the slides for time and space complexity for time complexity we will have o of n because of our for Loop and O of n log n because of sorting and since sorting has bigger time complexity as you can see in a complexity chart it will dominate all of N and will take over the overall complexity for us for a space complexity it will be all of one because we just sorted the intervals array and did not assign that into a new variable because it was unnecessary so that was it for this video thanks for watching and please leave a like comment and subscribe to the channel I will put the link for erase playlist in the description to check it out in addition of a few other playlists as well and finally hope you enjoyed this video and stay tuned for the next one
Meeting Rooms
meeting-rooms
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** false **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** true **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti < endi <= 106`
null
Array,Sorting
Easy
56,253
988
Ajay Ko Hello Hi Friends Welcome To My Channel And Today We Are Going To Solve Dalil Ko Problem 98 Molesting Starting From Delhi In The Root Of Poisonous Trees Where Is Not Have Value In Dowry 100 Basically Wave In Tears From 0250 Representing The Characters Representing Return Ko Graphically subscribe zaroor chalenge is you can share subscribe to a super example in description dba with spring to do yaar given daba energy tribunal tree from lekar andhero 1234 three more students entry hair 2000 1234 340 oil subscribe and ji sabhagya arts to-do list ko subscribe Must Subscribe That Dry Fuel Lexicographical 3310 Mobile Screen Distributor DBA Video Servi Starting From The Click to The Amazing Subscribe To 200 Grams 229 Problem Actually We Are Going To You Recognition Software Going To Travel From Raw To The That Live Of Factory And Vine Traversing We Are Going To Capture The Power In Delhi Looked More Like You Will Capture And Like Lekar Andhero Din 110 300 Absolutely Aishwarya Code Weekly Hawa Implemented Some Improvement And Travels Subscribe Rooted Through It's Really Stupid And Subscribe 12th Encounter Live Want To Capture Dawood Please Subscribe Aadha to aap saunth ek swadeshi the best ke swaroop jitna ijjat return another wise withdraw its value in to-do list come and to-do list come and to-do list come and difficult encounter ali nod day spent debit the list aadat hui hai work hard through if traversal senior and junior Assistant Hui Lad At Least I Am Proud Of Us Can Capture Son Mukadme Third Hai Vicky Traversing Them Left Side And Right Side The Same Time Kuch To Fark Sample This Is Not The Traversal Day 10:00 This Is Another Driver Tomorrow Come To This List Lalitaditya 2-If Driver Please Like This To This List Lalitaditya 2-If Driver Please Like This 023 Person Time Traversal Embassy Last Traversal Preorder Traversal District On I Am Going To Actually Cord Is Travels Method Which Disawar Robin Uthapp Scientist Creator Of The Earliest And Hurdle Rate List Of India Servi Output You Install Drivers Mithila And Travels Madrid The Highest Point Where Is Getting The List Of All The Data Capture And Truth And Travels For Example In This Write-up Channel Like After A In This Write-up Channel Like After A In This Write-up Channel Like After A 20130 14102 304 Subscribe But And I'm Going To Actually Travels Dhan Avamukt Stringbuilder And Will Convert Date Of Licor In Tears Into The Characters And Latest News Today Doctrine Vikas Hui Actually I Want To Get The Worst Thing Right From The List The Fruit Fennel Badh This Is What Do You Want To Get Converted Into The Subscribe Always Keep Sharing The Smallest Country during the list do 200 dasha pratima chot saunth aur this is the tree date will discuss singh 20123 4000 abc lead dashrath graphically smallest is dedh se ki solitaire instant code a main to yaar so let's give correct answer toilet loot submit code is This suit was challenging accepted to hand over top quality 4 st and that this doctor team on st on and strong sage-sadhvi can and strong sage-sadhvi can and strong sage-sadhvi can solve the small stream starting from lift software kind of using recency 2capture on the person will just to the thing builders reverse Mitra to get up because they want to get up from a lip to the root of to 100MB left masjid aa gaya isla post ko don lagi tab account and give the link in description substitute for this helpful aa please subscribe my channel and give me like this video thank you
Smallest String Starting From Leaf
flip-equivalent-binary-trees
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Tree,Depth-First Search,Binary Tree
Medium
null
501
find mode in binary s Tre is a tree in which the middle node is the key and the left node or the present value stored in the left node is less than the root node and the right node is uh contain the value or the root value which is greater than the key node so we have given the root of a b Sy with duplicates and we have to return all the modes of it so we have to return all the node that is the mode of the tree that is the most frequently occurring element in it if the tree has more than one we have to return them in any of the order so let us see the here is the code of the question we are given first we have taken answer to store the answer and that we have to return finally and we have taken the value as integer mean we have to track each of the values and we have taken the frequency is z maximum frequency is also zero we done the inorder traversal if there is no root we have to return first we have to tr the left then if the root value equal to Value then we have to increase the frequency if it is not equal to value that we have first initially stored then you have to make the frequency one and store that value into the uh root value into the value varable IF frequency is greater than Max frequency then we have to make that Max frequency as that frequency and we have to store the root value as in the answer otherwise if it is equal to Max frequency we have to Pro and that is if multiple modes are present then you have to push it in the answer and then for the right sub you have to check the similar of the things and uh this function called is made over there and finally you have to return the answer
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
98
hey guys welcome to the quorum act if you are new to the Channel please do subscribe we solve a lot of competitive problems today's problem is very read binary search tree so what problems say is given a binary tree determine if it is a valid binary search tree or not assume a BST is a define as follows so what how to determine whether given a binary tree or given trees of BST or not so it has this two properties the left subtree of Nod contains only our nodes with key is less than the norske and the second condition is the right subtree of the node contains only nodes that with the key is greater than the nodes key what carpet says both the left and right subtree must also be binary search trees so let's understand with the example what first point says is all the nodes on the left hand side should be having a less value as compared to what we have at the current node so all the nodes on the left hand side should be minimum with respect to the current node and on the right subtree of the north's contention only nodes with the keys greater than the your current node so all the nodes on the right hand side should be higher as compared to what we have at the current node in this property first and second what third part says is the property first and second should fulfill at each node so you are at when you are at here it should fulfill for this left subtree and when you are it here at fulfil it should fulfill all right on a right hand side also okay so it needs to be fulfilled at here as well as here also if there are other nodes at the below level okay now let us understand this with a more example so I we have a two example so first one is what B is divine given a binary tree so it is satisfying the binary search tree property okay so if you see it each level if you are at a root level the first property says the all the nods on our right-hand side should be greater and right-hand side should be greater and right-hand side should be greater and left-hand side should be having a less left-hand side should be having a less left-hand side should be having a less value so if you are at a four so maximum value on this side is a three which is a again less than the what we have current no and the minimum value on the right hand side is what we have five but again that is also greater to the what current nor we have and it the same if you go to the next node three there also left hand side it is the less value as compared to what the current node same goes on our right hand side same if you see here the seven your left hand side tree having less value as compared to the current node and same goes for the right hand side so we can say that this tree is satisfying the BST property okay now if you go to the second example here we have where is a root element as a five and on a left hand side we have one so this satisfies the first property there we are good on let's see on a right hand side so if you see here minimum is a three out of it which is less than the your current truth norm so it is not satisfying on the right hand side it needs to be a higher is compared to the current node so it is not satisfying BST so for this we need to return result as Falls for this we will return a return as true okay but now let us understand the soul lives on approach okay to solve this problem at each North to take a decision whether it will satisfy a BST property or not what when you we are interested is we want to know what is a maximum value we are getting from the left hand side so let's say we will take example if you are at here and you we want to take decision from this node okay whether it will satisfy the B is the property or not so what we want is we want to know what is a maximum value or maximum value node on the left hand side okay so let's say we have some value max left okay and the same way we want to understand to know what is a minimum value from the right hand side mean off right okay now to whether it is a this will satisfy the property or nor so it needs to be this value for needs to be greater than your max left okay should be less than or equal to your current okay and your mean layer mean right okay needs to be greater than your current if this is true then we can say that this node will satisfy or a tree it is satisfying a BST property okay now the same approach we need to apply it to each node when you are ready here we also would like to know what is a max maximum value of the node on the right-hand side of the sub tree in right-hand side of the sub tree in right-hand side of the sub tree in maximum minimum right minimum will you offer not from the right-hand side of offer not from the right-hand side of offer not from the right-hand side of the and then we can understand whether this is satisfying this logic or not okay if it's true we will return a true from here to the upper node okay so if each node what we will do here when we are at here let's say three whether it this node is satisfying the property or not if it is satisfying it will return a true okay as well as we also will return what is a max value as well as mean value from the sub tree to understand what is to understand or to calculator whether it this node will satisfy or not at the same time we also satisfy we also return value from this right subtree and we will return mean and max of that sub okay so when you are at here this two data will useful to calculate whether this will this node will satisfy or it is going to be satisfied the BST property or not okay so based on that again we will again this will calculate whether it is satisfying or not it will return well you true or false and at the same time it will also return a mean and Max from there same cause on the right hand side also and it will return a true or false at each node with mean and Max okay so that way each node we can calculate this data and we can accumulate whether whole tree is going to be satisfied the BST property or not so now let's write down a code for this so the return result of recursive function return is BST will pass first truth node and at each node also we would like to pass mean and Max value so first we will pass mean as long dot mean value dot and for max we would like to pass long dot max value okay so this is the function will do in an iterative way okay now let's write down first function signature boolean is DST okay this will take your root node as the input and go along mean well and long Maxwell okay now let's first write down a base conditions so in which case we would like to return true in which case we would like to return a false so if your root node is equal to null return are true because in that case it's a correct BST now in the false if your minimum value or if you are minimum from the current pain the left-hand side if the current pain the left-hand side if the current pain the left-hand side if it is a greater than your greater than or equal to the root in that case we would like to return a false and same way your maximum value from this subtree right hand side let's say in the right hand side if it is less than or equal to your root dot value in that case we also we would like to return a false okay so let's say your mean well is greater than or equal to root dot well or your Maxwell is less than or equal to root dot well in that case we would like to return true false yes sorry okay now for rest of the things we would like to do these two things at the each node so we'll call same function or each node is valid BST first we will call for leg left side of the root node will pass root No and then when you are calling your left hand side nor our mean is going to be same if we will not have any change in that but your max value will change because on our left when we are calling the left hand side the maximum value is going to be always max is going to be always am rule dot when and same goes for the right hand side so let's say he is valid BST okay now root dot right here minimum value is going to be because on the right hand side always minimum value is going to be your root thought well you we may not have any minimum other than the root dot value and maximum we will keep it as is whatever the maximum being a passed from the bokor okay so that in the corner let's compile it okay so four two one three weather expected was true an output is also true now let's submit it okay it got submitted here time complexity of this problem as we are just traversing the each node so time complexity is going to be off N and space complexities we are not utilizing extra space so it is going to be a constant so that's it in this video hope you liked it please add comments if you have a different approach or you are looking for solution for a different problem thank you guys
Validate Binary Search Tree
validate-binary-search-tree
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[2,1,3\] **Output:** true **Example 2:** **Input:** root = \[5,1,4,null,null,3,6\] **Output:** false **Explanation:** The root node's value is 5 but its right child's value is 4. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,501
1,235
hello guys and welcome back to lead Logics this is the maximum profit in job scheduling problem from lead code this is a lead code hard and the number for this is 1 1235 so in this problem we are given with n jobs and uh every job is scheduled from start time I to end time I so we are given with the start times and the end times array consisting of the start time and the Ed time of each and every job and uh each job has also a profit of profit ey so we also have a array of profits where profit of high is the profit of job I and uh we are given with the start time and profit Aras and we have to return the maximum profit we can take such that there are no two jobs in a subset with overlapping time range so basically we have to arrange the jobs in such a way that our profit is maximized so let's suppose we have uh this example one so for example one the job is starting from uh first uh zero job let's say zero job will start at zero and end at three and uh first job will start at two uh and end at four third job will start at third three and end at five and the fourth job will start at 3 and end at 6 but we have to see the profit we have to maximize The Profit so the maximum profit if we draw the time uh time range for each and every job it will be like this in the example and we can clearly see that the maximum profit comes when the job one and the job four are arranged sequentially so let's see how we are going to do this so first of all we have taken the example the same example you see the start time 1 2 3 5 uh not the same it is a bit different but uh it is similar and we have end time as 3 5 6 7 and The Profit is 50 2070 so what is the first step that we are going to do so the first step that we are going to do is sorting the jobs and how we are going to sort that sorting in an order uh of the ending times so we have that array end time this end time so we'll sort the array according to that such that the job with smallest ending time comes first and we are going to create uh virtually we are going to create some tles like the tles will have the end time start time and the profit so the after sorting the tles become so ending time three starting time 1 and profit 50 this is the first job and then the second job is starting time ending time five starting time two and profit of 20 and then third job is six ending time starting time three profit of 100 four job ends at 7 starts at 4 and gives a profit of 70 now we have the job sorted now we have to create the DP table and the DP table is always of the n+ one the DP table is always of the n+ one the DP table is always of the n+ one size so since the N is 4 here we are going to take a DP of 5 size five and now we are going to use binary search and binary search in what format you might have seen the uh use of uh finding the upper bound using binary search if you haven't you can watch it on the stver s's channel uh binary search upperbound video uh he gives a very good explanation so you can see that for that otherwise you can watch the video I will explain in that also so in each for each job we are going to find using binary search if there is a non-conflicting job or not there is a non-conflicting job or not there is a non-conflicting job or not and we are going to check two things like if the current job can give us the maximum result out of the previous result or it is the previous result that we are going to use so here we are going to use the dynamic programming so let's see how we are going to do so for first job that is 3150 ending time three starting time 1 profit 50 we see that there are no pre previous jobs so we can simply allocate the DP of 1 to b50 now for the second job we see that the time is actually overlapping it's the first job started at 1 and ended at 3 and this is starting at 2 and ends at 5 so this is overlapping so in this case we have to consider this Max of dp1 or DP 0 + 20 so DP of 0 was 0 and DP of 0 + DP 0 + 20 so DP of 0 was 0 and DP of 0 + DP 0 + 20 so DP of 0 was 0 and DP of 0 + 20 is 20 and DP of 1 was 50 so which is Max so DP of 1 is Max so it becomes 50 so DP of 1 becomes 50 now for the third job now the third job uh ends at 6 and starts at 3 now we see that this does not overlap with the first job okay and uh so we can allocate it and also we can see that uh the DP of from this Max of DP to or DP 1 + 100 so DP of this Max of DP to or DP 1 + 100 so DP of this Max of DP to or DP 1 + 100 so DP of 1 + 100 gives 150 and DP of 2 was 1 + 100 gives 150 and DP of 2 was 1 + 100 gives 150 and DP of 2 was 50 uh so we can definitely say that uh this will give a maximum result this and then the for the fourth job similarly we are going to check which one gives the maximum and so from here we find out that DP of 2 + 70 gives the maximum result and we 2 + 70 gives the maximum result and we 2 + 70 gives the maximum result and we can simply state that the our answer is this 120 that is the DP of n so we have to Simply return the DP of N and that would be our answer so this was the code explanation now let's come to the coding section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel um a like and a subscribe can give uh very much support to me so let's start so first of all let us Define the number of jobs equal to profit. length and then we are going to create an array of job so what is this job so we are going to create a custom class or the tle what I was going what I was telling you so that tle is this job and we are going to create this now in a few seconds but before that let me write the other Logics so then we are going to iterate and initialize the tles so this will be number of jobs I ++ and here we have jobs of I equal to new job and the tle will be like the end time of I first then this then we have the start time of I and then the profit of I okay now we need to sort it and how we are going to sort it we are going to use a custom comparator as well so we are we need to sort this jobs array and for this we need to write comparator dot comp pairing int so this we need to write I think yes it is I think it is correct I am not making a mistake and this is the proper syntax job do end time so this is how we write to sort uh basically these are actually classes this every job particularly is a instance of a class now we need to write the Define the DP table so this will be of the job plus one size so now we need to extract the values from each job so that's what we are going to so we have extracted this 10 time and then the profit so we need to find now the last non-conflicting job index so which was non-conflicting job index so which was non-conflicting job index so which was the last uh job that was non-conflicting the last uh job that was non-conflicting the last uh job that was non-conflicting with the current job so for that we are going to use the upper bound of the job array and we'll give the pass the aat index along with the start time value so anything that ends before the start time of the current job uh will be a non-conflicting be a non-conflicting be a non-conflicting job so let's see so from this we can get the latest non-conflicting job as well the latest non-conflicting job as well the latest non-conflicting job as well now we need to only Define DP of I + of I + of I + 1 will be DP of uh m. Max that will be DP of either I or DP of IUS 1 plus the current jobs profit or actually this will be last non-conflicting non-conflicting non-conflicting job so I'm going to Simply copy this big variable me and then we have the profit value you can avoid using such big uh variabl names but this uh makes the code more readable and uh although it will be difficult to handle but the interviewer might like the concept of writing very clear variable names so that whenever someone else reads your code he F he doesn't find it difficult to understand what's written so now we have defined the main uh logic now we need to div Define the first the upper bound and then this jobs Class so let's define the upper bound first so the upper B consist of the jobs job the end index and the so we'll set the low equal to zero we'll set the high equal to the end index and then we'll try to find the upper bom so till the time low is less than high Met equal to low plus I by 2 and if the job. mid do end time is less than or equal to Target time that mean this particular value is a possible answer so we'll uh keep it in the low because in at the end we are going to return the low so that's why we are storing the answer in the low so mid + storing the answer in the low so mid + storing the answer in the low so mid + one and why are we doing mid + one uh one and why are we doing mid + one uh one and why are we doing mid + one uh because now we know that low is the answer but there can be a possibility that there may be answers in between the mid to the high so that's why we are going to again iterate and otherwise what will be the case otherwise we'll put the high equal to Mid and here we can return the low so this is the upper bound let's define the class as well this class consist of a end time start time and the now we Define the Constructor so this do end time equal to the end time this R start time equal to start time and this do profit equal to profit so I think we are done with the code let's try to submit it for the sample test cases so this will be capital so it run fine let's run for the hidden test cases as well it passes for the hidden test cases as well with a good time complexity and a good memory complexity so the time complexity for this solution is n login because we are iterating in the array and for every time we are using a binary search upper bound that takes login so the time complexity begins and login and the space complexity is O ofn because we are using a DP so yes I hope you understood the logic you can also check the C++ Python logic you can also check the C++ Python logic you can also check the C++ Python and the JavaScript solutions by going to the solutions panel and checking this solution post this is my solution you can find the intuition the approach entire approach written down here with the nodes complexity the Java code C++ code python code JavaScript code C++ code python code JavaScript code C++ code python code JavaScript code and yes do remember me to uport I hope you like the video understood the logic do like share subscribe the video it will show me your support guys thank you for watching the video have a nice day
Maximum Profit in Job Scheduling
maximum-profit-in-job-scheduling
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`. You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`. **Example 1:** **Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\] **Output:** 120 **Explanation:** The subset chosen is the first and fourth job. Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70. **Example 2:** **Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\] **Output:** 150 **Explanation:** The subset chosen is the first, fourth and fifth job. Profit obtained 150 = 20 + 70 + 60. **Example 3:** **Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\] **Output:** 6 **Constraints:** * `1 <= startTime.length == endTime.length == profit.length <= 5 * 104` * `1 <= startTime[i] < endTime[i] <= 109` * `1 <= profit[i] <= 104`
null
null
Hard
null
1,493
Hello everyone welcome to my channel with mike so a who is going to do video number 10 of his sliding window mechanism ok and medium level question lead code no 1493 but it is going to be a very general sliding window problem ok that's why I don't think this is medium, it is quite easy, we will make it with many triangles, we will make it with multiple approaches, right, we can make it in many ways, this is going to be very easy, it is ok, trust me, longest patience of once after deleting one element, ok This is one, it is given, there is only zero or one in it, that element has to be deleted, you should delete it is okay like mother, if this is your example, then there is zero here, otherwise it is the longest. Hey everyone, the longest one is the one in which there is only one, you can see it completely, how much is the length, it is three, but it is said that one has to be deleted, so the length will be 3 - 1 = 2, it so the length will be 3 - 1 = 2, it so the length will be 3 - 1 = 2, it means one element is deleted. It has to be done, one thing has happened, the other thing has happened, brother, it is 0, it is okay, it is the longest Sabri in which there is only one, it is not like that, anything else, the answer will be zero, okay, let us see more examples so that it becomes more clear. Look here, first of all I have an example, its length, find it and show me, in which there should be only one and you can delete one, there is zero, no, obviously you will delete only zero, if you have the option of zero, then here I am seeing zero, so which one should I delete? If I find the longest sabri, then if I delete it, then see what I get. If I find the sabri of length 1 2 3 4 5, then the answer is mine, now it is five. Now this is an important example. Look, there are all 111 in it, so the longest journey. So this is what I am seeing, but till now I have not deleted anyone because there is no zero, so in this I will have to delete only one, its length is the child, it is mine, you are ok, this thing is important, it was very important. Understand this and ask such questions to yourself at the time of exam and interview and ask what will be its answer, then he will tell himself, okay, if this is an example, then what is its output? Now what are you saying, otherwise he will explain to you that its output. You are fine, that is why it is very important to get clarity. It is okay at the time of interview after coding examples. So, first of all, know that I will not make it beautifully, so I have taken this example of mine and I will also make the code beautiful in a very simple way. Today we and British forces will also submit the solution. I think if the constant is small then it can be made even with n², so let's see if it does n't work. Look, pay attention. I know what I will do. I will take a very simple approach. I am here. Right now, this is one, yes, there is nothing to be done, further flood, this is one, yes, nothing is to be done, further flood, that is ok, I saw zero, what should I say, let's reduce it or delete this zero, let's go to this Deleted the zero. Well, I have already done what I said in the question, so let's delete it. Now this means that this doesn't exist anymore, it is fine in the picture. Now let's see the longest Sabri which has only one, whose length was not found. What is two, there is only one in it, one, this is the biggest one, there are three and 21, all of them are one, its length is one, so who got the biggest brother, if I got three, then my answer is ok, this time I deleted the zero and this. I had deleted the index number, you had deleted the zero, now this time when I came here, this time I deleted it, I will do the same again, come on, this time I deleted it's good, now I will spend the entire morning. In which there is only one of these is filled and one of this is visible, what is the length of two, what is the length of three, this time also the maximum length has come only 3, so it is still three, my answer is come someone. No problem, now it has come again, it will move on, this is one, leave it, this is one, leave this too, this is one, this is not one, it is not zero, so this time I am saying, let's delete it this time. Let's try and see what answer comes, whose lens is what? There are two, only I, only one, why me, because I skipped the middle zero because we had planned to delete it, so this time look at the length. What is one, two, three, that is, we have got a big answer, our answer is done, you are done, okay, so we have taken one more big answer and updated it, now it is here, there is a forest, next to it is a flood which has gone ahead. My answer is four, okay so look in this, if you pay attention, I am doing recruit travels twice and as soon as I get zero, I came here, like I got zero here, I decided that I have to skip index number 2. Ok that will be my answer so first what I am doing is write for i as soon as I get zero in the i index then I loop over another one and ignore the inductance with maximum i which has only one. Find out their length and lay down, okay, it is very simple, let's quickly code these 20 fruits, you will understand what I am doing, okay, I will keep taking out the length of each one like this, okay, after doing the court now, you will understand the clear cut. So, let's first do the court with fruit force. First of all, I have calculated the length and let it be n = sorry I have calculated the length and let it be n = sorry I have calculated the length and let it be n = sorry and defined it here. Okay, and a vector named result, keep let it be a variable, in which I will store the final result. The maximum length is going to be okay and see what I will do in time = 0 i &lt; What I said is that I will skip this name index and take out all the sequences whose one has only one in it and take out their maximum length which I also got the biggest patience, like I got Namsai zero, what did I do, result is equal to maximum of result comma, I am writing a function which will look at another one, find max 90 and tell me which index you have to skip because Now what is the zero element, is n't it okay, this is how you will know and I will return the result in the last, it was simple like this, now what do I think of doing this Sunday, right, now every window, every subri in which There is only one length, its length comes out to many, there can be many sabris. Well, the ISP will store the length of the current sabri. Okay, and we will keep storing the max length in it. Okay, I have to skip. Now I will tweet again in full and the length of all the sabris. It will appear in which there is only one, okay, so what I said is that if the I which is mine is equal to the skip index, then I do not have to do anything, I have to continue, that means it must have been deleted, the write is clear till now, if there is one, then I will keep accounting how much am I getting brother, the current length is equal, you are sorry, I will keep updating the max length as well, maximum or the current length that I have got till now, if and that means one Sabri, we are one Sabri in which only that has ended, now new. It will start in the morning after zero so currently let's do zero again. Okay, this is simple Bluetooth force. If you do more then you will understand very clearly. Okay, what will you do in the return, whatever is the max length, my store will be okay. So look at mine also, I did the same thing as I told that as soon as I got i = 0, I got name that as soon as I got i = 0, I got name that as soon as I got i = 0, I got name size zero, what did I do, I did a separate function yesterday and said that brother, by skipping this index, all the sub-arrangements are being found. In which all the sub-arrangements are being found. In which all the sub-arrangements are being found. In which all the length is one, all the elements are one, take out the maximum from them, so I have taken it out here by brute force method, that is why n² is there, put one n here and inside it again I am running a fruit look here, after doing this yesterday. So n² is done, okay, so now look in the question, it can also be possible that there is not even one zero, there is only one, then look at the answer in this, what is mine, whatever number of one is there, just delete one, then the name size - 1 Do not delete one element, it is then the name size - 1 Do not delete one element, it is then the name size - 1 Do not delete one element, it is written, delete one element, then I will have to keep a count that the count of zero is equal to zero. In the beginning, as soon as I get zero, I will do plus and I will write that if there is not even one zero. If the count of zero is zero, I will simply return it and make it -1. This is return it and make it -1. This is return it and make it -1. This is how I am handling this one. If there is no zero then whatever the size of Namas was, minus one and sent it because 1 kilometer has to be deleted anyway. If there is even one zero then we will reduce this one and our answer will be A in the result. Okay, let's run it and see. Let's pass the example test cases first and then submit it and see. Okay, look, I think the constraint is low, so N square. This will also work. It should be submitted. They have solved this question using root. Also, it is a good thing. It has been solved even with bread. Now let's move on. Brother, this is actually a G topic question. Okay, let's move ahead. I understand. How is this question a problem of sliding window? Okay, now let us understand why there is a question of sliding window, first of all and secondly, how will we solve it with sliding window in a very easy way. Okay, the general format is to solve by taking the IG point of the side window. We will solve it exactly the same way as we used to do, if no new thing comes, then if you take this example then what was said in the question that what you have to delete is that if you have zero in your arrangement then you have to delete only one element. You have to delete it and you have to find the biggest one which has only one, so in the morning I am seeing one which has 100 because one can skip a zero and hit right, so this one, if I am seeing this, but as soon as I have any Tried to stand, I came here, I came to know that in this Sabri, brother, two zeros have come, one is this, so two cannot be deleted, you always have to delete only one, so what can I do? I will say that brother, shrink the window from here, okay, shrink the window from here, now look at my window, this has been done, so actually you are seeing that here the window is being formed and is sliding, it is okay and generally. Something like this will always be given in the saber. There will be a discussion in the saber and it will decide which character should not be kept in the window of your saber, meaning I am repeating again, in such a question, generally it would have been given that the maximum The length has to be calculated and you will also be told which elements should be kept or not kept in Sabri. Okay, there are many such questions. I have numbered the related lead code questions in the description below. If you solve them also then you will get a clear idea, okay then it is okay, if you want to solve sliding windows, then let's start it from sliding windows and understand it from the very basic template, so see what I was telling you just a little earlier. One window is my own and if there are more than one zero in that window, it means I will have to reduce the size of the window and reduce the zeros because in one window I had to keep only one in it, I will be able to bring only one zero in it because I can delete it, I ca n't do it with more than one zero, I can't keep such a big window, okay, so we will apply the same thing here, see, like every time, we will do the same, there will be an eye point here, which will be this painter and Sense, I want to have an idea of ​​zero account, and Sense, I want to have an idea of ​​zero account, and Sense, I want to have an idea of ​​zero account, so I keep a variable that brother, how much zero account is running, right now in the beginning, it is zero till now it has been cleared and I also keep the result of a maximum window size in which I will keep tracking how much, what is the biggest window size I have got, it is clear till now let's start, look in NMPS off, now one is zero, no problem, so right now the smallest window I can see is like I. This is what I am getting, but what I have given in the question is that if you have to delete one element, then this is the window. You have got only one element in it, so one window is a window. Remember in general, how was the size of the window determined in minus and plus. One was coming out, don't you son, it was said in the question that if you have to delete it for a minute, then yes I am right, plus one is the size of the window, if you don't want to delete an element in it, then you will have to do minus one, so if this plus is cut in minus then We will find out the length of each of our windows by doing K Mins I. If it is ok then it is ok and if K Mins I is there then what is the length of zero and the length of the result is also zero so there is nothing big yet, I have not got the answer no problem now. I will remain here, we will move ahead, okay, now let's see if it is equal to zero, no, it is not equal to zero, then it doesn't matter, again the length is found out, minus I, it is okay, that is, 1 - 0, so now we know that is, 1 - 0, so now we know that is, 1 - 0, so now we know the result. The key value is zero and I have also got one, so the answer will be one. Now this one window has been found, this window has been found, you are seeing me in it, all the ones are ok but if you do not delete one, then if you delete this then the length one will come, so now. I have got one, ok, now what will we do, let's move ahead, yes, it is bigger here, ok, now I have got zero, so I will make the account of zero bigger, zero account will be made one, ok, but give a zero account, what should I give bigger, one is not one, so one is zero. If you can turn it off, then I can still take out K mines I. Okay, let's do J - I. How much will it cost brother? 2 - 0. do J - I. How much will it cost brother? 2 - 0. do J - I. How much will it cost brother? 2 - 0. Okay, how much is the size of the window. Look, this is correct. These windows are gone to me. These windows are correct. If yes, then give me the answer, I have just updated it is ok because look, pay attention in this window, what is there in this window and there is one zero and this window is also correct because I am allowed to delete one element, so I will delete only zero. Length. Look here, I got two, that is my answer, two, okay, now it is slowly becoming clear to you that now I have come here again, I got zero, I made zero account bigger by doing one, what has happened to zero account, now it is like zero account. What will I do if it becomes two, brother, I will quickly tell Aai that brother, make the window smaller till my account is reduced to zero, okay then eyeball N, let's go, okay, I will make myself smaller now Aai, what happened? I came ahead and got flooded but look there is still wind 0 account only you are there right now zero account in this window you are the only one then came ahead flooded ok still zero look in this window zero account there are only two ok now I came here ahead Now look at this small window, there is only one account in it, so I change the account from zero to one here, okay and what is the minus, see, I am right, it is zero, but I have the result. Now you are there, so it is obvious, I have a big answer already, okay, then we will move ahead, okay, now what window have I got, I have got this window, there are 4, let's see in this window, there is one zero and one, what will be one? Four minus three becomes one, if you are there in the result then I will not update, okay still zero account is only one, right here in my window, the one which is here is equal to one, the size of this window will be two, why see zero? There is one, there is one, we will delete the zero, Windows size, have you got it, there are all the ones in it, but I already have you, so I will not update, okay, big one, ok, it has come here this time, what is the element, so 6. - 3 this time, what is the element, so 6. - 3 this time, what is the element, so 6. - 3 Look, when I got the big answer, I updated it, okay, which window is this window, look in this window, there is zero, there is one, it is ok, no problem till now and everything will be cleared gradually- Slowly, I just came here, gradually- Slowly, I just came here, gradually- Slowly, I just came here, look now, I got zero, one more, so what I said, brother, I had increased the account of zero, that is, if I have to remove zero, what will I do, I will tell you, till the zero account becomes one, you Let's move ahead, so what did I do? Here I went to zero account. Now there is one account in this window. So again I made the account one. Now let's see the size of this window. By doing the minuses with J - I, what will happen? There will be three. It minuses with J - I, what will happen? There will be three. It minuses with J - I, what will happen? There will be three. It was already ready, I have no answer, let's move ahead. Now look at the very important thing which came here. Okay, now it is equal to one. If you do G-I then J-I, how much is it? It will be 8-4. do G-I then J-I, how much is it? It will be 8-4. do G-I then J-I, how much is it? It will be 8-4. Now look at my result, it is three. Updated with tax and what is this window, let's see first 1 0 1 It is from here, look at this sabri, all of them are forest and deleting an element is also allowed, so we will delete it, how much has happened? Length one, two, three, this is my tax, the answer is ok, this sliding window is so simple, ok, if you see the code of the starting window, it is not very simple, it will start from i0, ok and yes, whatever it is, keep moving forward, this is equal to you. Zero's &lt; is clear till now but was late to see which zero till the count of zero sorry account zero will decrease when i my zero must have been right meaning if i will be equal to zero now i is shifting forward is ok this I am sliding, right, the window is fine till now, it is clear, after that he used to do the same every time that my maximum length was equal to you maximum [ maximum length was equal to you maximum [ maximum length was equal to you maximum and after that a butter sliding window approach. I will tell you which will be better than this. You are seeing here that the look is going on, this is a needless hassle isn't it? I will show you another clean code and I will explain that too but let's go and code it. Okay, let's go sliding. Let's solve this from the window too, okay and take the zero account first, now there is zero in the starting point, let's take the max length, zero is okay, it started from zero and four's will also start from zero, is n't it &lt;= size J+ is n't it &lt;= size J+ is n't it &lt;= size J+ is ok as soon as the number is off I see zero, what did I do I changed the account of zero to plus ok but I will also check that as long as the zero account is greater than one then I will have to keep decreasing the zero account that means I Okay, so what will I do? F name and my max length will come out every time as it used to come out as max of max length comma return length will also have to be done okay so I will not travel each element more than twice. I am not visiting each element more than twice, so I will visit it once from here and once this Vile loop runs, it will actually be O of N plus N, which you can effectively call off else, okay. This too was solved in Linear Time Complexity itself, Sliding Window, but the viral look in the middle is not going well for me. There is a cleaner way to solve this. Even they would have understood. Yes, but this is the most standard method. In the interview with I Painter and K Painter, first of all you have to go for Brat Force and then this approach. Okay, after that, if he asks you for a more clean approach, then what I am going to tell you right now. If it is okay in the proposal then let's quickly submit it. Let's say you passed which is done in D test cases. Let's quickly go to the third approach which is the cleaner approach. I will call it cleaner sliding window. Okay, so look now we will move to our third approach. But let's go to Butter Sliding Window Approach. Okay, look at this. To understand this, I will tell you a small story and example, like because of mother, here we had only seen one. There would be a zero written in the middle, the rest would be one. So see why this window is valid, first understand why this window is valid, why this Sabri window is violet because it has all the ones in it and only one zero and it is mentioned in the question that we can delete one. One zero is okay, we have to delete one element, so obviously I will delete zero here, so this is my valid, everything is okay, till now it is clear, but as soon as k goes ahead, okay and k If zero is seen then it is no longer valid. All the fillings between I and J are no longer valid. Okay, look, sorry. First of all, don't do this. Understand the story. Write the code yourself, Dog. Now K got one more zero. Okay, two. Zero is already done, friend, we can only delete one. Okay, so I know what will the AI ​​say that brother, it is the last time. Zero, AI ​​say that brother, it is the last time. Zero, AI ​​say that brother, it is the last time. Zero, where did we see the last time? If we saw the zero here, then the GI will say that brother, it is the last time. I had not seen him since zero, I just talked to you are right here, you are here, whatever was the index of zero last time, whatever was there, mother takes extra, so I don't know what I told you that you are X + 1 But the one who was here has come here, + 1 But the one who was here has come here, + 1 But the one who was here has come here, now see why, what was the reason because we had seen the last time zero here, now we have seen another zero, brother, let it shift, wherever the last time zero will be, there is just one thing so that now In the window that I got, there is only one zero which is currently looking at. Okay, now it will go ahead in the future. Okay and I will have to update the last zero index. What is the last zero days now? You are here, this is the story. Here we have to keep track of where we saw the last time zero. Right, where did we see the last time zero? Right now, both are indicators, so we might not have even seen the last time zero, so here I will give -1 for now. Okay, this is give -1 for now. Okay, this is give -1 for now. Okay, this is clear till now in which I will store the maximum, this will also be clear to you, let's start now, okay look, it has become zero, the length of the result is now 0, so we will not update anything, they are good, okay, I am still here. I have got only one so again I will update the result What is the value of K minus IJ so I have updated my result ok why am I repeating again K from and I is here K is here right here There is one, this is also one, so I found one Sabri in which all the elements are only 1, so if we delete it, then what will be the answer, for now my answer is one, it is fine for this window, last time we saw zero wherever. You were just talking about one thing, which means, what will I say to the last zero index plus one, which is you, what will happen to this, where will A go to zero, okay, so what did I do, I sent A to zero, okay? Now where have we seen the last zero, I said that we will update it, but now we have seen the last zero, so I will update it, what are you, it is clear till now, okay, now let's move ahead, it will be very clear. See ji, now I have come here again, I saw zero, am I okay, so ji, what will I do then, ok yes, when I was here, we had not updated the result, see what will happen, 110, this is my window, delete an element in it, allow me to delete it. If you delete it then what will be the length? You have updated the result with your own. Okay, the result will be updated every time. Brother, whoever you are, last time wherever we saw zero, there is one thing about it because now we have to see it in our window. I need only one zero, okay, so what was the last time zero index, you were there, add plus one to it, give it a date of 3, so I also now A will go here, okay IB will go here, and last time now where did we see zero. Will update if I saw that the index became three last time, then this time we will do the same that I have signed, the size of the window comes out to be zero, but our answer is you, so thoughts are fine, we will move ahead, it is fine here. Now we have shown forests, so there is no need to do anything, there may be floods in the future, if mines come out, then what will we do? If there are two, then no good answer has been found, if there are floods in the future, then I simply put the sign, what should I do? Will go 6-3 Pay attention to this window, there is what should I do? Will go 6-3 Pay attention to this window, there is what should I do? Will go 6-3 Pay attention to this window, there is only one zero in this window, we can delete it, okay and for us A will go 11, neither is the answer, three is I have updated it from CAT, from three till here it is clear. Now I have come here, look again, it is very important, do it here brother, last time we had just checked it, so the index went to 4, I got three plus one four, look, it must have been cleared well, it is okay here. So we have done this and now where was the last time we saw this and the next number is seven, so I have updated the index number 7, we have last seen 0. Okay, now let's update again, what is the value of this sign I have made? I will be with you, there will be three, the answer is already three, so no big answer has been found which has come here, now look, I have done eight mines, I have updated it, what is this window, pay attention, this window is here, right, look at all the keys. All are one and deleting one element is allowed, so I will delete it, after doing one, two, three, it got length, hence it got updated after answering, ok next big out, everything is finished, it has stalled after doing our answer, how much clean solution is needed. Right, that's why I found this solution very correct and it is not anti-that much, I have and it is not anti-that much, I have and it is not anti-that much, I have tried to simplify it by telling the story, but the most intuitive solution is the same approach that I told you, but this culprit was quite good, it was very simple. And this is a sweet approach, its code will also be very simple, you must have understood it, let us code quickly and complete this question today, so now let's solve our third process i.e. butter now let's solve our third process i.e. butter now let's solve our third process i.e. butter sliding window process, okay, quite good. We have to keep track of where we saw Project Time Zero. It has just started, so we must have seen it in Mines One. Okay, the intermediate result is equal to zero. We will keep solving the maximum in the result and so on as long as it continues till NABARD size reaches that level. No less, okay, as soon as I saw zero in Namsab ji, what did I say to Aayi, whatever you are, that is the last zero index, one further flood from where we had seen, which is okay, the region, I have told you and now the last zero days update. We will have to do this because now we have seen the last zero in K, it is okay till now it is clear, now just like every time, the result is equal to the maximum of result.
Longest Subarray of 1's After Deleting One Element
frog-position-after-t-seconds
Given a binary array `nums`, you should delete one element from it. Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray. **Example 1:** **Input:** nums = \[1,1,0,1\] **Output:** 3 **Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's. **Example 2:** **Input:** nums = \[0,1,1,1,0,1,1,0,1\] **Output:** 5 **Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,1\] **Output:** 2 **Explanation:** You must delete one element. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices.
Tree,Depth-First Search,Breadth-First Search,Graph
Hard
null
1,385
okay we're going to be doing late code 1385 find the distance value between two arrays so given two integer arrays array one and array two and the integer d right return the distance value between the two arrays the distance value is defined as the number of elements in array 1 such that there is not any element in array two where array the absolute value of array one minus array two is less than or equal to d so here we have array one with four five eight right then for each element in array one we check we subtract through here the absolute value of 4 minus 10 4 minus 9 4 minus 1 4 minus 8 right and it's what we're doing here right you can clearly see that for 4 is that this is what they're describing as a distance value it qualifies right because the absolute values here are all greater than d and d is two right five qualifies as a distance value because as you can see they're all greater than two eight does not qualify as a distance value because 2 is equal to 2 which is id 1 is equal to and 7 and 0. so you really need to understand what the question is asking and this took me a while like i read for like five minutes then i understood what they're asking but so uh a mistake i made was actually to return uh the non-distance values i had a uh the non-distance values i had a uh the non-distance values i had a counter which counts the non-distance counter which counts the non-distance counter which counts the non-distance values and that's what i returned but you're supposed to find four five and eight not eight so let's do the brute force is we're going to for each element here we're going to iterate through here so this is two loops right so brute force is obviously going to be quadratic it's going to be o of length of array once times length of array two right so for i in range length of array 1 for j in range length of array 2. we calculate and check for unknown distance value so if absolutely e to the absolute if absolute of array 1 at i minus array 2 at j right if this value is less than or equal to d then i'm going to have a counter here then we increment our counter for let me call it non-distance values let me call it non-distance values let me call it non-distance values non-distance values so that means that this value of i is a non-distance value right because its non-distance value right because its non-distance value right because its value is less the absolute value of this formula is less than or equal to d so non-distance non-distance non-distance non-distance values non-distance values non-distance values will be plus equals one and then we break right we don't need to continue going through the rest of them right so for example if we add eight and we calculate this already we know that eight is not a distance value so we don't have to continue with this so that's why we break here so we break and then here we return the length of array one minus the non-distance values let's see voila it works right so how do we improve this we can improve this but instead of doing a for loop we go through array 1 and then with binary search array 2 right but array 2 is not sorted right so all we have to do is sort array 2 first then iterate through array one and for each value instead of doing instead of iterating through all this we do our binary search and this will evaluate to n log n time for the whole algorithm as long as there's always uh as long as there is a binary as long as there exists a non-distance value non-distance value non-distance value right so let's do this so the more optimal approach it's not so optimal but more optimal approach we sort array two so array to the sort this is done in place and it's a quick sort then we iterate through array one and binary search array two for non-distance array two for non-distance array two for non-distance values so we're going to create our variable for non-distance values which is equal to zero initialize it to zero then four num in array one right we're getting instead of like using an index we're just grabbing them individually so now we binary search for unknown distance values in array two so i is equal to zero j is equal to array two i mean length of array 2 minus 1. okay then while i is less than or equal to j we get our mid submit will equal to i minus j minus i divided by two then we check right we check if absolute value of array of num right minus array 2 at mid is less than or equal to d then we increment our non-distance then we increment our non-distance then we increment our non-distance values plus equals 1. and in fact at this point we can even break right l if uh array two at mid is less than uh our distance if yeah if array2 is less than our distance value then i is equal to mid plus one else j is equal to mid minus one right so we're just binary searching for each value and then we simply return length of array 1 minus non distance values right oh okay so that means i made a mistake somewhere we could think have happened let me see oh it was supposed to be my bad i wrote d it was supposed to be numb right supposed to be this now because this is what we're looking for so sorry about that okay where else did i make a mistake if array at mid is less than num then i is equal to i mean it looks fine where may i have made is less than or equal to d counter the length of array one minus counter my difference i see is here okay so i is equal to zero length of array less than or equal to less than it looks okay to me i don't see where i made a mistake i must have made a mistake somewhere but i can't see it made am i tired j minus 1 oh the mistake was here sorry this was supposed to be plus right yeah not minus sorry about that i'm a bit tired yeah so the mistake was here and also don't forget here it's less than which is what we're looking for so yeah sorry about that i'm a bit tired but i just binary search this and yes so that's the solution this will be n log n time okay bye
Find the Distance Value Between Two Arrays
number-of-ways-to-build-house-of-cards
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_. The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`. **Example 1:** **Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2 **Output:** 2 **Explanation:** For arr1\[0\]=4 we have: |4-10|=6 > d=2 |4-9|=5 > d=2 |4-1|=3 > d=2 |4-8|=4 > d=2 For arr1\[1\]=5 we have: |5-10|=5 > d=2 |5-9|=4 > d=2 |5-1|=4 > d=2 |5-8|=3 > d=2 For arr1\[2\]=8 we have: **|8-10|=2 <= d=2** **|8-9|=1 <= d=2** |8-1|=7 > d=2 **|8-8|=0 <= d=2** **Example 2:** **Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3 **Output:** 2 **Example 3:** **Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6 **Output:** 1 **Constraints:** * `1 <= arr1.length, arr2.length <= 500` * `-1000 <= arr1[i], arr2[j] <= 1000` * `0 <= d <= 100`
If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles.
Math,Dynamic Programming
Medium
815
943
hello friends today there so find the shortest superstream given array a of strings find any smallest string that contains each string in a and the substring we must assume that no stringing a is substring of another string in a so let's see this true example we can see Alex loves Lea code this free stream do not have any overlap so the shortest super string is just the concatenation of these two strings and the permutations not matter that means lick who loves Alex is also correct how about example two we can see that there are mending of laps between ending to sub to string such as CAT G and the ATG chec we can see that h EG you know overlap so we can merge these two string in the zones of force and finally we can get this result so let's first see about this problem how do you find the super string of two strings this is the case one when the two string do not have any overlap so the super strain just the concatenation of these two string the case two we can see that only if the last substring equal to the first a substring of string s we can merge them we can used the common place so the superstring were just the bcat g and the chec and you may find out that actually this is the esta substring 0 - 4 - 3 4 this is the esta substring 0 - 4 - 3 4 this is the esta substring 0 - 4 - 3 4 is the length of string 1 and the 3 is the length of the overlapped astray and actually the st. Paris is just the string to and this is another situation when the first part of the string one is equal to the last part of string true you missing a it's just this truth dream change their place switch you may think that like that so the shortest super string will be g cg a and a GT right the stem is first Paris as to das true substring 0 and 4-3 the salient substring 0 and 4-3 the salient substring 0 and 4-3 the salient Harley is the string 1 okay how about her we will there are more than two strings like if I referred there are five string and we will choose two string to merge them then we get the s6 and then we choose two string to merge then we left mystery and the soul and so forth and at the last so we only have one string it will be the result but how do we choose which two string to merge actually we if you think that we will combine all the string and try to compare the you know the overlapped part if the overlapped part is longest so we know if we merge these two string we can save more characters in the final string right like if one combination is cat in a THD they only have the teeth them so we stab one character the way is cat and so crazy we know actually the same so we can save true character so we may choose this true string to merge so the each level we will try to compare all the combination and you know save the longest overlap part and we merge this truth tree and add this new merger string to the laser and remove these two original string from the list and finally when the lists only have one string it will be the result so wrap up we need a method called merge we merge the string as one in the string s2 and this is the one situation this is another situation and actually it can be concluded through this one of these two situation what we call you know from the end of the s-1 in the front the end of the s-1 in the front the end of the s-1 in the front the beginning of the as true one is called from the beginning of s1 and the end of the string - okay the string - okay the string - okay then we return a merge the string right and we will add the merger string to the list and remove the original shoe string and when the lists only have one string it is the result so we are given a string array so first we need change the two string list and we compare older Chu string combination and try to find the truth during which they're overlapped part is the longest and we added this merger string to the list so if we ask them the elgran you can stop in the right at your own code and finally compare your holder with mine okay so now let's write the code we first need at least alright we call this and they'll actually reach ng2 from the array so there will be a race at least eight and the less right to the merge part we return stream and emerge this is dream I swamp dream that's true and the way you first together lens one which is s $1 and the last two is s 2 which is s $1 and the last two is s 2 which is s $1 and the last two is s 2 dollars and 1k see that we start from the end of the s1 and from the beginning of s to R I so interest which is the length of the overlapped apart started is one and you know actually there are two cases of the substring one is the substrate which is the begin index T of the end another is some string we give it two parameters which the beginning and end index so if we do not you know indicators or and index it will just go to the end so the first if we go start from the end of the s1 the part we need to compare actually is you know is like a PCT we needed to compare CD right this is the overlapped part and this is s1 so we needed to make sure that's one minus lens it's great all you can 0 right this is lens one we - its lens right this is lens one we - its lens right this is lens one we - its lens it'll show up equally Houghton's 0 and the 10th should also be less or equal to LS 2 right otherwise it is a minimus and we every time we increment this lens right so when there is one does upstream then the beginning index is length one - the beginning index is length one - the beginning index is length one - length this is the lens city is lens for example the star index is lens one - example the star index is lens one - example the star index is lens one - this lens and if it equals to let show substring and the part we needed to compare actually is like cdef we start from zero and the end index is length so if it's the same we need to save this lens we call it overlap to walk to the lens so at first we needed two variable one is over lefty one equal to zero overlapped I choose you okay another case just switch this true this time we start from the beginning of the string one and does the end of the string true so there will be a skewed or substring there's two - lens impose true substring there's two - lens impose true substring there's two - lens impose true s1 substring there will be zero in the lens right if they are same then overlap entry module ends so funny will be that you compare the length of these two parts if the overlap is one is greater or equal to over lap it - then we need to return if over lap it - then we need to return if over lap it - then we need to return if it's greater like if it's greater we needed to return this part as to the substring 0 and H true talents - of laps substring 0 and H true talents - of laps substring 0 and H true talents - of laps at length plus as 1 so there will be we return as true the substring start from 0 and then through - / - we need to 0 and then through - / - we need to 0 and then through - / - we need to return F is less so we need to return X 1 sub 3 there will be 0 s 1 - let's check it whether he's right the overlapped one actually the last part of the string one so if it is greater ah I think this should be s 1 substring + I think this should be s 1 substring + I think this should be s 1 substring + hence 1 minus overlapped 1 + hence 1 minus overlapped 1 + hence 1 minus overlapped 1 + because actually if this overlapped 1 is great they're overlapped true that means we choose this part right so actually this is s 1 da substring + 0 x 1 this is s 1 da substring + 0 x 1 this is s 1 da substring + 0 x 1 dalliance - overlap lens + s true okay dalliance - overlap lens + s true okay dalliance - overlap lens + s true okay so this part of the be very careful we cannot make a mistake this lens true - of laptop + s 1 ok so this lens true - of laptop + s 1 ok so this lens true - of laptop + s 1 ok so currently you should be right okay then why sure if we get the size of the list and if only one we just a break we are this wire loop and we return this turn yet zero it's the only in string it's a final answer otherwise we needed to compare every combination I less than n minus 1 plus J 0 j s 1 will be Lister Gator I ask you will be east of capture J right then we needed to get the merge as well as you and we can get it saved lens there will be the original lengths plus s 2 dollars miners merge two dollars so if the same length is the is greater than the previous sector lens so we need like kind of global max the lens firstly you can chew next one because it can be 0 if save the great at the end of excellence and will update this excellence you watch with our saved you also needed to save this to index I and J because we needed to remove it afterwards and we also needed to save the merge string so neither add the three variable twice the index 1 u 0 neither much tree at first is empty string right okay so this part the index 1 is equal to I industry hojae and word sorry cannot call its merge okay so this part new screen will update that you emerged so after we get the most saved true string we will remove them from the list so least a string 1 these two will remove stranger annalisa will add this yeah I think we have finish 8 okay sorry goodbye okay let's quickly check it hmm overlapped yes okay thank you for watching see you next time
Find the Shortest Superstring
sum-of-subarray-minimums
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Array,Dynamic Programming,Stack,Monotonic Stack
Medium
2227
235
hello everyone today we are going to solve lowest common ancestor of a binary search tree it's a medium problem so it's a problem related to Binary Source tree so we need to utilize the property of the binary search tree it means all the nodes in the left subtree of a node will be smaller than the value of the node and all the nodes in the right subtree will have values greater than the node value so for more interesting coding problems please subscribe to this channel now let's talk about today's problem so given a binary search tree find the lowest common in Sister node of two given nodes in the BST okay so we are given a binary search tree and we are given two nodes and we need to find the lowest common ancestor of these two nodes so let's see the definition of lowest common in sister so according to the definition of LCA that is our lowest common insistor on Wikipedia the lowest common in system is defined between two nodes p and Q as the lowest node in the T that has both p and Q as descendants will we allow a node to be a descendant of itself so a node can be descendant of itself also so this means if this is a 6 and we need to find the LCA of six so we'll say it's 6 because the node is a descendant of itself also so the simplest way to solve this problem will be like we are going to search for the first key that is p so we are firstly going to find this P key in our tree and going to store the path from the root to that key okay so p is 2 so we are going to firstly find the two in this tree and going to store the root 2 that node path so all our traversal start from the root so firstly we are going to visit this 6 that's a BST so left will be smaller than the root and right will be greater than the root so we are going to compare this key value with this root value so this is 2 so 2 is smaller than 6 so we are going to go for the left side so 6 left is 2 so it is equal to P so we are going to return because we found our key in the tree and the path is 6 2 okay so we'll store this path now again we are going to find this Q so Q is 8 so we start with the root is 6 so we store this path and compare this key value with our root so 8 is greater than 6 so we are going to go for right so next right is 8 so it's equal to the key value so we are going to return and this is our path and now we are going to compare these two paths so whenever the nodes are similar we are going to skip that node and keep that script node in a variable say result okay node will be our lowest common in system so we are going to match in this way so let's suppose we are given this tree and our keys are 0 and 5 and we need to find the LC of these two nodes so when we are on a node how we are going to decide we need to go for the left or we are going to go for the right so firstly we are going to assign P the smallest values from these two nodes okay so P will be our main thing and for the queue we are going to assign the maximum of p and Q so Q will be the max so when we are on a node we are going to compare from these two values and we decide whether we need to go for the right direction or left Direction when we are on some node we are going to compare with the smallest value if this value is smaller than the smallest value if our let's say this is our current thing so if our current dot well is a smaller than our p it means that its left child is not going to contain p and Q because its left child is going to contain the values smaller than this current value and our p and Q both will be greater than this current value so there is no possibility that our p and Q is going to lie in this left subtree so we are not going to explore this left subtree we are going to explore this right subtree because they are going to lie in the right subtree of this node because both values are greater than this current value so this is our first case so the second case could be our current value our root value is greater than Q so there is no way that our p and Q is going to lie in this right subtree because right subtree is going to contain all the values greater than our current thought well and our p and Q is smaller than this current value so they will be like lying in the left subtree so now we are going to take in consideration both the nodes not a single node while searching and we are going to search these two conditions if our current root value is smaller than our the minimum thing that is p then we need to go for the right direction otherwise if our current value is greater than the maximum thing we need to go for the left Direction and if none of these two cases are true it means that our current value is either equal to P or Q or our current value is in between p and Q so it is in between p and Q so that node will be our LCA because P will be in its left sub tree and Q will be in its right subtree so there is no way that both the p and Q will be going to be in one subtree they are going to be in two different subtree so whatever this current node is there which is in the between p and Q range that will be our LCA so these two cases can happen other than these two initial case so if these two cases are happening it means that we are going to return that root node in this way we are going to modify our search strategy so what will be the time and space complexity so time and space complexity will be similar to the previous approach we are going to take on time complexity because it could be the case that our tree is like skewed tree and our p and Q are just like bottom two nodes so in that case we need to go to tilde bottom minus 1 so there is no benefit so it's like o in itself and the space complexity will be Owen we are going to solve it recursively and recursion is going to take o in space on our stack space but other than this we are not going to take any extra memory and the space for the comparison thing or for the creation of our root to node path so these all spaces and comparison could be saved so yeah that's all for this problem so I don't feel it's a medium it's the easy problem itself so let's code this problem so firstly here we are going to assign P the minimum of p and Q the maximum of p and Q so let's do it now we are going to modify our search function for a key in a binary search tree so let's write our code for a searching a key in a binary search tree then we are going to modify it so the parameter to this function will be root so if our root value is smaller than our minimum value that is p-value minimum value that is p-value minimum value that is p-value so it means that our p and Q is going to lie in the right subtree second condition will be if our root value is greater than the Q value so it is greater than the maximum value so it means that our p and Q is going to lie in the right subtree of this node otherwise if none of these two cases are happen it means either our root value is equal to P or Q value or root value is in between the p and Q value range so this will be our LCA so we need to return this value so this completes our code it's just a three to four line of code so let's run our function let's submit our code yeah so it's called submitted it's efficient and space complexity is also good so yeah that's it for today's problem if you found this useful please subscribe to this Channel and like this video thank you for listening see you with a new problem
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8 **Output:** 6 **Explanation:** The LCA of nodes 2 and 8 is 6. **Example 2:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4 **Output:** 2 **Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[2,1\], p = 2, q = 1 **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the BST.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
236,1190,1780,1790,1816
1,289
hello so today you are doing continuing on this contest beauty contest 15 the last problem which is this hard problem 1289 minimum falling path some - so the 1289 minimum falling path some - so the 1289 minimum falling path some - so the problem says given a square grid of integers a falling path with non zero shift is a choice of exactly one element from each row of array such that no two elements chosen in adjacent rows are in the same columns and what we want is at the end to return the minimum sum of falling path with nonzero shift what essentially this means is that we're going to pick any number from the first row then pick another number from the second row that is not in the same column and keep doing this for each adjacent row and the goal is to do this in a way that we get the minimum sum of a path that has this criteria here and if we look at the example here we can take one and then take five and take nine you can see these the all of them the adjacent rows the ones that will pick it from adjacent rows are not in the same column and so the smallest one among all of these is this one that's where we get the minimum sum which is 13 so we return that the ranges is that it's a square grid and the rows and columns can be at most 200 each so how can we solve this problem so one thing you can think of actually when were the intuition behind the solution for this problem is that well if you think about the most straightforward way to solve it is well let's just find the minimum in the first row and then add to the minimum of the second row and then add it to the minimum of the third row and then add it to the minimum of the fourth row and then keep going just taking the minimum right but the problem with that is what if the mean in multiple rows is a what if the men like in this role is the same in this lawless the min and this row is the same on the same column that's the only case where we have a problem right and so if the mins are in the same column well what is the solution let's just pick the smallest one in this row the second smallest one right and then that way we will have satisfied the criteria and have the minimum sum right and so that means that our strategy would be get the minimum add them in from the previous row to the min of the control right if they are not in the same column right and if they are in the same column then that means just add the second smalls from the previous row to the min in this in the control right and do this keep doing this of in the adjacent for each adjacent rows right and that's pretty much the solution that's pretty much the main idea behind this solution right so let's just cut it up so first I'm just going to keep track of some variables know the length of the row which is here since this is a grid I don't like it to be named array so I'm just going to name it M so here lengths of columns is m0 and then we wanna for each row right we are going to start from the first row because for the from the second row because for the first row which is the one at index zero we can just take them in because there is no previous role to check against right and so here we need to for the role at position one we need to take the two smallest from the previous row which is all at position zero and so we need to get the two smallest from the previous row so how do we get it so find the two main values in the previous row two smallest values from the previous row that's what we are going to do here and so to do that first let's get the first the smallest one from the previous row so let's call it mean one Alice get gets get its index right so let's call it j1 and to get the index there we just take the previous row and find the index for that smallest value right then we want to get the second smallest element so that's just the min for the previous row except by excluding them in one right except we need to exclude j1 here we need to exclude the element at position j1 so to do that I'm just going to say 4jx in I'm going to enumerate the row but I'm going to consider only take the minimum only for all the elements except the smallest one because I want the second smallest so if G is different of course then the index of the smallest one right so now I have the two smallest values between 1 and mint too so now what I want to do is just go through the current row which is just the G's in the range of color and I want to do what I said here if the previous row smallest of the previous row is not in the same column then I just add that right and if it is then I take the second smallest so to do that I just add on to the current value and since so this way I will keep accumulating in each row and so that way for in this last row I would have the accumulation of this sum and I can just take the smallest of these right and so here I would say plus min - so well here I would say plus min - so well here I would say plus min - so well there is one case is if min one if the element in the previous rows column so the same column of the previous row is equal to min one what that means the smallest element in previous row is in the same column right so that means I can't use it right so that means I need to add the other smallest element otherwise I can add the this most element because they are not in the same row right and you can see here I'm adding that means that I will keep adding until in the final row I would have the smallest one that I obtained through all four all columns and I can just take the minimum of that right and so here at the end I can just take the minimum of the last row and so to do that I can just say the minimum of the last row so this will give me the minimum sum because for each column I tried in a greedy way to obtain the small sum of it and so now my mij will contain the sum the minimum sum possible of all the rows before it such that we pick that element at that position right so yeah so that's pretty much it I hope this is a clear but the main idea is this thing here is if the two minimums of two adjacent rows are on the same columns column we can't pick both right because there is the constraint that we can take from the same column and so we take the second best choice which is the second smallest but we don't know maybe there was another one another case where we would have taken a different column and find a better way and so we are going to populate all of them and then at the end take the minimum of the last row and that's pretty much it for this solution okay so I'll submit okay so that passes a slightly different way to do this instead of this calculation that we did here for the for that to smallest element is Python has hip Q right a heap can get you the end the n smallest element and so it can get us the to smallest element because if we import he pure like this it has this function called M smallest well you could give it m and an iterable and it will find you the n MOS most elements in the iterable so here if we give it to it will find for us the two smallest element and so here to obtain min one and min to instead of doing this manually we could just say mean one and min two will be equal that using hip queue we just get the M smallest two elements of the previous row that's what we were calculating here so minus one and we can use that instead and so we will need to import hip kill here and this will do the exact same thing okay so that passes again yeah so that's it actually for this there is of course a way to solve this problem using top-down dynamic programming it passes top-down dynamic programming it passes top-down dynamic programming it passes in Java but doesn't in Python so I didn't go over it here but that one is pretty straightforward you could just you just recurse and you have two choices at each moment where for the previous row you try sorry at each moment you can you try all the values in the next row except the ones on the same column and you pick the minimum yeah but it doesn't it get gives time latex exceeded in Python so I'm not going to go over it but it's just know that it's possible yeah so that's a for this problem please like and subscribe and thanks for watching and see you next time bye
Minimum Falling Path Sum II
day-of-the-week
Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_. A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column. **Example 1:** **Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** 13 **Explanation:** The possible falling paths are: \[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\], \[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\], \[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\] The falling path with the smallest sum is \[1,5,7\], so the answer is 13. **Example 2:** **Input:** grid = \[\[7\]\] **Output:** 7 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 200` * `-99 <= grid[i][j] <= 99`
Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year.
Math
Easy
null
1,482
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go so Larry cute 3 minimum number of days to make em Paquette's and this one because um so I'd like to do them in order because I don't know but so that's what I was doing because I because the palms weren't loading in the beginning so I wasn't sure which went out which plum I was looking at but yeah now that I said earlier now there was just a lot of reading and that's pretty much what I was doing a lot of reading I still I didn't understand what this poem was doing I probably have some bad habits about reading I go to the example to example didn't really teach me another I go back to the kalam statement I read it again and I'm under another example and so forth so I did this for about a minute which if you're submitting in 3 minutes or 4 minutes that adds up yeah but as soon as I understand what the problem is actually asking I go to the binary search pretty quickly so the idea and of course if you're watching I do go explain these problems at the end so definitely go to that there'll be a link below if you like but that's for it or whatever you like and go straight to the explanation but this part in the commentary part I do try to explain my thought process as is happening which sometimes I don't have to answer right away know most of the time even well yeah but now I'm just trying to see ok boom day I'm still reading on this problem unlike what's boom day and what all these things what are they important and now I'm like ok I think I have two idea that's I think I briefly look at constraints which it reasonably ok for binary search and that's the only thing that I checked really yeah and that's pretty much it so the idea I know you know the explanations will be at the end as well but so what I'm well here is that notice that for a given day so let's say you're testing a day X how do you get the most amount of flowers from it or poke AIDS from it right well you just do greedy from left to right and construct patches of K consecutive ones as possible and if you do that and you look at how many flowers you make well that graph of days versus numberphile or a number of pockets that you can make its binary searchable and you want to find the first instance in which you can make at least four brocades and that's kind of the problem that we're solving and again in the later explanation I go into it a little bit with some rationalization let me know what you think about this problem this is this was a little bit tricky I died but still pretty cool oh yeah now I'm just thinking about the edge cases of like well not edge cases but like but binary search something that and I have a lot of really was on binary search is that I get off by one errors a lot so I'm really thankful okay what does it mean for you to point him the way that's why I'm a little bit slow but that's okay because when I'm fast I'm warm and I would it be snow and correct then just be wrong wait so yeah and this is just a running count the greedy part of this binary search yeah and as soon as we encountered a where we can't we just said to one is you Zuma and if one is greater than k then that means that we have we made a okay and I just like spaces and that's pretty much it Oh actually there's one more which is that if it is not possible I did not handle this case yeah it was like and the only thing I caught was that hard there's two engines and witches is a billion so I was like go it's not possible so I knew that another way of representing is not possible is if the end of the range is not good enough and for this problem so I did just if statement for that reason and then that is basically what I did I was going to just check if your answer is bigger than the max number of days then return negative one but it could be the maximum of day so I so that's what I fix and then I submit afterwards my binary search I'm never super confident to be honest Chris there's always potential for off by one so when I could submit I was just like you think q2 a minimum number of days to make em Poquette that's what this one is just binary search so that which is again based off another thing which is that it is greedy and it is greedy by basically give them a certain time you just want to take the earliest running sequence of and make bouquets as much as you can right so let's say you have K equals 3 in this case so let's say you have tell you goes to a like you have this one then and it stays 7 you want to you always want to make it as soon as if possible because why not is which is the basis for this greedy and in this case we cannot make it on day 7 because the second bunch of it we made one but the second one while it goes for 12 so that now we as soon as we see 12 minute meaning that there's a gap and you know you might as well treat as this then we have to start over and we just basically moved out along and then creating but gets as much as possible and then the question is well what is the first day that you can do this and the first day that it happens is that is you could do a binary search of this greedy meaning ok you test 12 route with 12 get well in this case is 2 ok they don't really give you good numbers to put to show you let's say you have this away right and you're doing was it K is equal to 2 and you want to make four of them so yeah so in this case you're just trying to you know you try 5 and then 5 lets 5 you cannot make for book heads yeah and then you try a bigger number and so forth such that because it allows you to do greedy because well the greedy part is another part but the binary search is pick because the later you get the more you can always like if you add a day to say you know on a given day you cannot do it and in a given day you can do it the day after that you can always do it because it's a is this sort of a subset of or a superset of before where you can make more pockets you can only make more pockets as you go on and from that properly you're trying to find that line where okay you know I was you know on the second day I did see what bouquet on the 53 bouquet its and you try to find that line where that meets this meets for exactly and that's basically what I do here it's binary search but it's pseudo the range is on the range of the room day which the number of days were just 10 to the 9th which is you know binary search I've done is fine don't you think that it's a little tricky is making sure that yeah well if I want which is binary search in general but also making sure that you handle the negative one case which I took some time to yeah so the complexity well we don't use any extra space really other than variables or one extra space it's log max of the range of bloom day which is ten to the ninth so it's a log of 10 to the nine which you know it's like 4000 it's like dirty or something like that but yeah so it's all depending how you want to say it because it does not oh it's that times and sigh so it's n times the log of the max of the range because for each of these binary search we have like you could say we have all of log of range of these let's say a large log all of these operations and for each operation we call good which this is of n right so because we have all of log n of these elevations each of these two and off log or so I don't know my other side so that's times n which is equal to of n log or complexity so yeah so that's kind of the complex of this is binary search it comes up all the time in programming both in dynamic sigh in competitive programming and interview so definite plasti said I think dynamic program because it maybe it's just something that's on my mind but yeah that's all I have for this problem that's cute
Minimum Number of Days to Make m Bouquets
how-many-numbers-are-smaller-than-the-current-number
You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet. Return _the minimum number of days you need to wait to be able to make_ `m` _bouquets from the garden_. If it is impossible to make m bouquets return `-1`. **Example 1:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 1 **Output:** 3 **Explanation:** Let us see what happened in the first three days. x means flower bloomed and \_ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: \[x, \_, \_, \_, \_\] // we can only make one bouquet. After day 2: \[x, \_, \_, \_, x\] // we can only make two bouquets. After day 3: \[x, \_, x, \_, x\] // we can make 3 bouquets. The answer is 3. **Example 2:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 2 **Output:** -1 **Explanation:** We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. **Example 3:** **Input:** bloomDay = \[7,7,7,7,12,7,7\], m = 2, k = 3 **Output:** 12 **Explanation:** We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: \[x, x, x, x, \_, x, x\] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: \[x, x, x, x, x, x, x\] It is obvious that we can make two bouquets in different ways. **Constraints:** * `bloomDay.length == n` * `1 <= n <= 105` * `1 <= bloomDay[i] <= 109` * `1 <= m <= 106` * `1 <= k <= n`
Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.
Array,Hash Table,Sorting,Counting
Easy
315
382
Hello Everyone Welcome to Date 7th January Liquid Chalu Ji Online Ho And Then Contents Time Without Much Difficulty Boxer Protest Question Today's Questions Link List Radhe In This Question Were Given In Earliest And Need To Define Adhi Not Being Able To Avoid Subscribe Subscribe subscribe one two three do subscribe and subscribe quite well received by the audience for a third tips created with better quality subscribe cast into doing all elements subscribe Video then subscribe to the Page if you liked The Video then subscribe to subscribe Quality of Doom Album Idon't With quality which were born in electronic channel subscribe and subscribe to subscribe and subscribe the subscribe to me link referendum note list to 382 intermediate level questions turn light to is totally feel the same will launch new technique subscribe and subscribe to subscribe our YouTube Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to and video one by two one but you can see in the twelve Video Subscribe 2131 * * * * * 2131 * * * * * 2131 * * * * * * * * Subscribe 1234 Subscribe 2015 12345 One Two Subscribe in right now it's implementation of draw something technique interviews to develop simple money subscribe not with synonyms of different subscribe paste windows number setting bomb against run minus one with quality Thursday subscribe The Channel Please subscribe and subscribe this Video subscribe to problem today one president pointed Thursday subscribe now to receive and subscribe to who is the probability for finding out 12130 should not be absorbed into the 30.22 its 30.22 its 30.22 its toxoid subscribe to the Page if you liked The Video then subscribe to the co select state lets check president of 251 subscribe this Video plz subscribe Channel liquid liner withdrawal from getting subscribe electronic questions were expected to give you do subscribe must subscribe loot lo the hindus were identified development of and liquid Subscribe to the subscribe button and that android no veer vote for him to return with prospective why not try to avoid you the selected tonic raub ghalib mir 143 possibilities 02 that what we will do blesses the native with considerable sacrifice subscribe to this to-do list to-do list to-do list Subscribe to the channel The Lord Has Been Updated To Three For The K Swab Ronit Property To Subscribe Do n't forget to subscribe my channel and subscribe in to-do to-do to-do list subscribe to the Page if you liked The Video then subscribe to the Page if some time For the probability of getting your answer turns out to be given by Sid Software doing and considering a previously computer labs for the subscribed * * * * * ki * 45 ki prior to IT and give some going on in this link for English language and minus one Upon in the mid-day the language and minus one Upon in the mid-day the language and minus one Upon in the mid-day the water left in the is one man is superstition what they are doing recording sessions will follow you want to depart at that Harold into real liquid liner Dhirwale-Dhirwale subscribe and subscribe the Channel Please subscribe and subscribe the For that accepted m correct vpn products editing notification time subscribe video subscribe button
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
1,725
B Call So what do we have to do so what will happen to us National Rectangle Square Triangle And I see we will pass the result Okay we will check like the method of finding the maximum Max If our system is done, then this is ours. Again current, we are people again. Rectangle, minimum rectangle, what should we do If you are done, then there will be someone, when our N becomes zero again. Okay, meaning If it is a simple message angle ] Rectangle And our in that will do our phone And this will do Now as much as we got this max Now we will compare one more last time, this is our current minimum, this is not if the current marks were equal What will we do now this will happen
Number Of Rectangles That Can Form The Largest Square
number-of-sets-of-k-non-overlapping-line-segments
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Math,Dynamic Programming
Medium
null
1,044
That Today Will See Editing Matching Problem Pattern Finding Problem Uninstall Longest Duplicate Sub Screen Award Is Means The Giver Bring to Front Subscribe Multiple Times at Least to Do It is the Longest Subscribe if you liked The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Also Like Sharing And Vrit Solution For District In Every Possible That All The Character Say District For Example A B C D E M Not Be Repeated Subscribe Must Problem Solve The Problems And Solutions And Subscribe Button More Time Limit Exceeded Subscribe Interview Subscribe Lutab Skin Ko Like and Subscribe And Pattern Matching But Still The Arrived At For Different Prime Numbers And Not Passing Through A Very Large Numbers At All E Channels Don't Subscribe And Subscribe No. 101 Time Limit Exceeded Egg Subscribe And Subscribe Withdraw From All Subscribe 510 Festival Complete One Should Be Enriched With Egg Ne Thursday In Ne Dhundhale-Dhundhale and subscribe With Egg Ne Thursday In Ne Dhundhale-Dhundhale and subscribe With Egg Ne Thursday In Ne Dhundhale-Dhundhale and subscribe the Channel Starting From 0 - 142 Subscribe From 0 - 142 Subscribe From 0 - 142 Subscribe Tomorrow Morning We Can Do we can build a drive stop this is my first president of but what are the different tractors pay an only regret character subscribe for 1514 in this super star bani start building this let's right year b that this that in village a b n a n ki And It's Right This Leaf And World In Green This Morning When Edit Distinct Today Strike Next Tablets Officer N A Suicide Note 's Daughter Nodal Want To Give Vote To It's N 's Daughter Nodal Want To Give Vote To It's N 's Daughter Nodal Want To Give Vote To It's N A That In That This Are Next Is Ine Ne Hua Hai MP3 Tomorrow Morning Money Vriddhi Feminine Amazing To Mark This And Affordable Suji Nehruvian Flight To Indore Dare I Am Writing 80 Green Color Vriddhi Including Member Vikram This Is Next Is A Push Vikram Ji Loot Now What We Need To Do We Need To Account Which Branch Have More Than One Lips Sudhir and a complete string itself will not even multiple subscribe this Video give Bill in this that is draw something like B.Ed sum that is draw something like B.Ed sum that is draw something like B.Ed sum subscribe to and huge body will be given only in the voice of but in this case is not the original Subscribe Prithvi Exhaustive words in the mid day meal is one world one day and anything with you that israel se word person white another word enemy suite for decision in difficult word that sweet-meats dupont is oil sweep that sweet-meats dupont is oil sweep that sweet-meats dupont is oil sweep elite we multiple listen what do you will you Can Take the Last Leaf Returns The Video then subscribe to the Last Food Should Keep Track of the Temple Will Return Dushman Hai 220 Approach Worked for Smaller Kissi But Again You Can See a Raghavan Length Addition - 110 You Can See a Raghavan Length Addition - 110 You Can See a Raghavan Length Addition - 110 - 21 - 3 - 4 - 506 504 3210 Vidron It'll - 21 - 3 - 4 - 506 504 3210 Vidron It'll - 21 - 3 - 4 - 506 504 3210 Vidron It'll Take Time To Know To Text Branch And You Will Lead You Not Exist Create One Branch To Try Node Animated Yr Again Continue Sui Time Last Time Total Time Taken To Install Subscribe Plus Two Class 10th Ki And Wild Insulting is business like account so let's meeting in software will commit directly comes in which exists in notices subscribe this Video Please subscribe and veer va peeth akad hai mein sundarkand vikram to next character us thrust government finance minister p ki android and knowledge-science Attend Show We Make At ki android and knowledge-science Attend Show We Make At ki android and knowledge-science Attend Show We Make At Least Not MB Sacrifice Us Zor Idli Sandwich Subscribe Loot 202 Subscribe 123 Ki Chal Yantri Starting From 30 To Three Layer Pendant Three Idiots Ne Sudhir Wali Patti Time Limit For B Id M Id To Key Table And Map The Institute Has Enjoyed Very smart and tough and also not map is used to visit near to keep track of weather subscribe thanks for watching 2.20 to subscribe thanks for watching 2.20 to subscribe thanks for watching 2.20 to annual subscription of possibilities of and 4G total 2621 - 1st prize winners of and 4G total 2621 - 1st prize winners of and 4G total 2621 - 1st prize winners list start from Big Boss Mein Will Not Something Starting From Come Switch Off Subscribe I 'm President In This Is It Or Isn't It Present 'm President In This Is It Or Isn't It Present 'm President In This Is It Or Isn't It Present World Tips Length Tomorrow Swimming Style Best 20 Switzerland This Later I Love You Updated To Three That Swadesh Me Vitamin A Great For All Sufferings And This Will Begin After Sunidhi Chauhan on Inch More But Will Subscribe Now to Receive New Updates Subscribe Interview Improve Interview Press the Subscribe Button Subscribe Now to Receive Tomorrow Morning A Friends We All Scotland 320 Weird Starting Distinctions Is Decided Someone Like You Sat 's 100 Richest Started 72 Neetu 's 100 Richest Started 72 Neetu 's 100 Richest Started 72 Neetu Compare Subscribe Starting from someone who already Subscribe Instituted of will start from I flu from this superhit starting position The thing will start from I plus and will this window will side sui 10 Tourists and a governess at this point of time which comes into Welcome to subscribe our Channel subscribe time limit exceeded final year so what is the name of the living with now school what is the meaning of you want to find the most pattern in given string what is the simple step which can take your parents that this man let's start with Correct Answer Only what will destroy all eggs and will look like subscribe and egg and begin it's not fair Next will move a gain a again this point and the second did not match will move egg and you will receive a normal view of doing something is the Receiver Region and Calculation So You've Already Been Written in Early Next Year Tomorrow Morning New Swift Hair Ki Unit-2 C Are You Can Go Through Camp Ki Unit-2 C Are You Can Go Through Camp Ki Unit-2 C Are You Can Go Through Camp Illets Limit for Lips Got Through Running Work Sweater Institute of Middoing Subscribe to Subscribe According to Our Director match this year character match sexual final match and subscribe almost we calculate the help of this pattern subscribe and subscribe the how to remove time is length and pattern engine and updated on today sukuldaihan saunf first name characters on that all traffic jam time a Plus B Plus C Face Message And Not For Now Let's Jobs Created A Very Good Ghr Functions For The Tunic Liquid Subscribe Now To Different subscribe and subscribe the Channel Please subscribe our Tomorrow Will Help In This Will Take Some Time To Calculate This Point Name Length Day Video Not It Is The Place Where Present That Idiot Match Vishisht Hairs Page Number 90 Hai Fennel Subscribe To E Want Ravindra Reddy Calculates Using The Character Switch C-1 And C-2 C-4 Zoom The Character Switch C-1 And C-2 C-4 Zoom The Character Switch C-1 And C-2 C-4 Zoom With Four Characters Switzerland One Time Number धोया Number धोया Number धोया जो हैर यह एफोल्ड Tractors D Why जो हैर यह एफोल्ड Tractors D Why जो हैर यह एफोल्ड Tractors D Why Plus Seat Times Square Plus Seat Times Dip Plus Seat 420 Sudhir Waiting For U Ki Nau You Need To Calculate The Best For This Way Newspaper Pattern Unlocked Pattern Will Appear Again After and subscribe this Hair Calculated Next Thursday Subscribe To That Sudheesh Calculation Will Be No More Water In Order To Meet With Constant Time It Seems They Are Creating Adding Some Value Subscribe Remove 1835 E Tomorrow Morning 12th New Hai Sweet Will Be C 2D Cube Plus Seervai A Plus Seat Five Now Suhag Can You Reach From This A Flat Sea How They Can Reach Problem Is The First Wave Subtracted Sewn Did You And You Will Go Away Because They Know Way Left With This Now With Multiple Of Birds That Will Help You Will See You Tube School Subscribe Depression And Finally Subscribe to one formula in operations one edison one conservation one multiplication and division respectively the length of the pattern subscribe multiply by newly married to all the time subscribe hai and one pass billion plus m.a. and one pass billion plus m.a. and one pass billion plus m.a. Loot Hain To Is Abhinay Ideal Function Time When Different Subscribe Comparing To Integer Values ​​subscribe Different Subscribe Comparing To Integer Values ​​subscribe Different Subscribe Comparing To Integer Values ​​subscribe The Channel Please subscribe and subscribe That And It's A Dare Different Patterns Winters Different Forms With Everything Seemed So Will Keep And Whose Starting Index For Hair That Late Lalit Jo Sudhre Is serial match this jersey this match 12th not different subscribe Video from this App ko Chaudharyan program note directly 200 first directly this code wich got time limit excelled software widron its simple general festival ch main ine argaranand setting mobile volume insulting all respects and keeping track of Account Services Testing Increment Account And Complain Against May Call Recording Cord This Pimps But Not Work No Subscribe To And Then General If Sunday Witch Is Quite A And That If They Can Take Different Valleys Of Death Will Work But General Fuel Due To The Number of Characters with Only English Letters Video 600 U All Subscribe Times in a Year A Great Power Factor and Completed All the Power Point 6 and Final Test Prime Numbers for General Key Size of Festivals Prime Numbers Subscribe - Model Number subscribe - Model Number subscribe - Model Number subscribe and subscirbe mode off karen ki and what is the value from YouTube channel story dear kal subah text prime sense of humor 148 function and note suyash laddu is generate values ​​with multiple of one another like values ​​with multiple of one another like values ​​with multiple of one another like x subscribe now to receive New Updates Subscribe Location Problem Subscribe Benefits Maulvi 2012 Duty subscribe and subscribe 220 Leader Will Win More Chances of Colleges Pet Seervi And You Have 0 Subscribe Channel Number 230 Mid Day Ko Share Bhi Happy Calculate The Power Of Date With Six Days Half Loot Lo Hai So you can transfer and Netherlands what they are doing where giving bribe in carpet length the time giving one thing you can also give one length tried to find all the subscribe and subscribe the length is and sudesh widow and don't write for all transfers from one To minus one but doing research on this soil the length of Pandu liked The Video then subscribe to the Page if you liked The Video then that Sunni to travel from this show is that exam Akram Times that Sudheesh to waring two times in obviously a here * Times &amp; Jobs Opening Times a here * Times &amp; Jobs Opening Times a here * Times &amp; Jobs Opening Times It's Only From This Is Repeated-Repeated Subscribe Button Adh Ki Saumya Start With Third Length Irfan Did You Know That At Least Three And Ander Duplicated Sweet Will See A Significant Improvement Solution dont Do Anything and subscribe to subscribe our 500 idk it's a distant you didn't find swift lipstick pimple says pe 2009 the supreme godhead duplicate string of saffron in odisha small waves us flat co can't find duplicates subscribe 504 subscribe this Video like Share and subscribe the Video then subscribe to I am Anil aka And 75 se zip liquid soap bhi lage entry em our and here it is 62 F but dushyant singh anil alarm procedure in you know that you have borrowed neck length unit andar sudhir walking tours and a that suavti driving car again ko olive 30 days No Point In Finding Otherwise Reduce Map Sudhir And Subscribe To Ka Saubhagya Calculator Apps Of This Is The First Limit Characters Surya Pattern Will Be Flu 100MB Calculate The Use Of This First Rank Subscribe Share From Year To Year Hai Ke Din University In The Map But With Her School Days Substring Started 10 Length Subscribe Sunni Hai Jo Mixed You Calculate All The Evening Values ​​Are Mixed You Calculate All The Evening Values ​​Are Mixed You Calculate All The Evening Values ​​Are 90 Have Plate The Face Co Difficult And Characters Will Not Make Idli Sandwich Subscribe To Order Business First Candidate Item From Year To Year But Even Fluid Switzerland Addison Adhoi Roop Running From This Channel Subscribe Multiply Subscribe To Yesterday Morning Subtracted Current Was The Great In Time Minus One Times APR - Length Time Minus One Times APR - Length Time Minus One Times APR - Length Video Channel Subscribe Our Video Main Office Prime The Sims And This Current Was Between 0 And Time - 150 Practice Vikram Negative Time - 150 Practice Vikram Negative Time - 150 Practice Vikram Negative Limit Can Be Logical Data Model Nucleic Acid subscribe and subscribe the Channel And subscribe The Amazing and hear that this will do something match needles subscribe our Channel Starting from India and subscribe Karna Absolut Tweet Ki Speed ​​Did Not Find Any Secretary Rajeev No Ki Speed ​​Did Not Find Any Secretary Rajeev No Ki Speed ​​Did Not Find Any Secretary Rajeev No Dip Liquidator Lamp in a gift from max value the fifth form a delicate and its length is the stuffing of this issue result B.Ed result stuffing of this issue result B.Ed result stuffing of this issue result B.Ed result fan advocate of government middle and subscribe for live video and half minute once again it has happened that antrix round 2492 can be found just 50 from this % % % 220 Due Time Set Voice Hindu Shrins And Withdraw When Bigg Boss Withdraw After A The Candidate Similar In Japan Pathal
Longest Duplicate Substring
find-common-characters
Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`. **Example 1:** **Input:** s = "banana" **Output:** "ana" **Example 2:** **Input:** s = "abcd" **Output:** "" **Constraints:** * `2 <= s.length <= 3 * 104` * `s` consists of lowercase English letters.
null
Array,Hash Table,String
Easy
350
142
hello everyone welcome to codex camp in today's video we are going to see linked list cycle two so the input given here is the head of linked list and we have to return the point where the linked list cycle starts so now we have already seen the problem linked list cycle one which is very similar to this problem which just ask us to return true if there is a cycle if not we have to return false we are going to approach this problem as well with a very similar approach but just that instead of finding whether there exist a cycle or not we are going to add one more step to find the entry point of the cycle so let's see how we're going to approach this so here is a given example in the problem statement and in this problem we have to find two things the first thing is whether the linked list is having cycle or not if there is a cycle what is the entry point so most of you would have been familiar with how to solve the first part of the problem if you have solved linked list cycle one if not that is okay so here we are going to use two pointers fast and slow that is going to move in different speeds and if they meet at the same point then we are going to have a cycle so the logic behind this solution is purely from cycle detection theorem or floyd's hair and tortoise algorithm that says if two pointers that are moving in a different speech then they are going to point at same value if there is a cycle so using that logic we are going to have first two pointers fast and slow so let's say fast is going to be in green and slow is going to be in yellow and we are going to move them in different speeds so our fast is going to move with twice the speed of slow so if we are moving slow by one pointer or one node we are going to move fast by two nodes at a time so let's see for at first iteration our slow point is going to point at the value two and our first pointer is going to point at the value three so then at the next titration slow moves to three and fast moves to five in next titration slow is gonna move to four and fast is gonna move to seven and finally our slow is going to move one step ahead and point at the node five and since there is a cycle after seven fast is not going to move towards null instead it is gonna take two steps ahead in the cycle so now by two taking two steps it is gonna point at four and then to 5 where our slow pointer has already moved so here is the point where slow and fast mates and since they are meeting at a point there exists a cycle so hence proved by the cycle detection theorem that there exists a cycle and fast and slow pointer has met and that solves the first half of the algorithm and there comes the next question so how do we find the entry point of this algorithm so yes the second part is quite a logical approach if you understand the distance and little mathematics you're gonna crack it so before going into the logic of the second approach let me explain the solution and then go to the logic so let's see we are going to have another slow pointer which is let's see let's have that as s2 because the slow pointer is going to move by one node at a time that's why it is s2 you can name it however you want to so we are going to move s1 or s and s2 simultaneously by one node at a time and wherever they first meet is the entry point of cycle so let's give it a try and then go into the logic so now for each iteration s2 and s is gonna move one node at a time so now s2 is at node two and s is at node six and then s2 is at node three and again yes moves by one pointer is at node seven so at the final iteration yes two moves to four and s also moves to four because it is in a cycle so this is the point we are actually looking for where the pointers yes and s2 meet and this is the point where a cycle starts and 4 is going to be our output so yes it is very clear that once we move slow and fast pointer at some point and we are going to initiate another pointer which is start from the head of a linked list and we are going to move both the pointer s2 and s1 equally until they meet at a point and when they meet at a point and that is the starting point of the cycle so how do we say that so what is the idea or logic behind this approach so this is nothing but a simple mathematical logic you can uh just solve it using mathematically and crack the logic behind it so first let's see let us consider the distance between head of the linked list to the starting point of where the cycle starts is going to be x1 and the length from the starting point of the cycle to where our s and f met is x two so here is where our uh star uh slow pointer and fast pointer met that found that there exist a cycle so let's see from the starting point of the cycle to that point is x2 and let's have the rest of the linked list from this the next to slow and fast point of met till again the entry point is x3 so why again the entry point because consider we are going to move our s from this point to where our cycle starts uh that is the distance we are going to cover or move our pointer yes going forward in the second part of the algorithm so from here till where we where our cycle starts is going to be x3 so understanding this would gonna help you solve this so now let's see how long is the fast pointer have traveled so if our first pointer started from the head of a linked list and stopped at where our slow and fast pointer is it must have traveled starting from the head went through the cycle one complete rotation and then came back to this position to meet yes hope you are understanding what i am saying it is going to start from head and then go to a complete cycle finishes the cycle off and then from 4 till 5 it travels again so the actual distance traveled by the fast pointer is x1 plus from 4 to 5 it is x2 again it is gonna move from x22 that is from this position till the starting of the pointer that is x3 and from again x3 or the starting of the cycle it is going to travel till where it met s so that distance is x2 so this is the distance fast pointer would have traveled to meet this low pointer for the first time so now what is the slow pointer have traveled so slow pointer would have traveled x1 plus x2 because it is slow it is gonna uh meet the fast pointer in its first iteration instead of taking the complete circle over it so it is going to travel x 1 plus x 2 so how do we make them equal so now f is equal to 2 x 2 sorry f is equal to 2 s why because since we have mode fast twice the time of slow fast must have traveled twice the distance slow have traveled at some point so using that logic we are going to put x 1 plus x 2 plus x 3 plus x 2 is equal to twice that of x 1 plus x 2 okay so solving this 2 x 2 plus x 1 plus x 3 is equal to 2 x 1 plus 2 x 2 just an algebraic formula we are going to just cancel out the x's so 2 x 2 and 2 x 2 cancels so now rest is x 1 x 3 is equal to 2 x 1 so here 1 x 1 cancels and here remains 1 x 1. so finally it is going to prove us x 1 is equal to x3 so hope i made some sense so which is nothing but what is the distance from the pointer s to the starting of the entry point of the cycle is equal to the distance traveled from head to the entry point of the cycle so this is the logic we finally get so what are we going to do we are going to traverse this path x1 by having a pointer s2 at the head and we are going to travel the path x3 by moving the pointer s from its point to the starting so we are going to eventually move them with equal speed so at some point they both meet so that is the point actually the entry point of the cycle so hope we made some sense with this formula and expressions so it's it is very simple and logical approach where we can solve it and finally we just got an idea we did not get a solution we got an idea that the distance from head to entry point is equal to the distance from the where the point is met to the entry point so we simply put two pointers to travel from these two pointers to meet at some point and that some point is our solution so hope i made some sense so before going to code this is going to work in big o of one space because we are not going to use any space and this is going to work in big o of n log n time so let's go to the code now yes as we said we are declaring two pointers low and fast and we are going to iterate fast by to twice that of how slow travels so here we are uh having a point that fast is not is equal to null and fast at next is not is equal to null because if there is no cycle which means our fast pointer will first reach to null so in that case uh we can written minus 1 because there is no cycle if not if it doesn't meet null at all then ah there is a cycle so which means uh we have to find uh a pointer that where fast and slow meets so now we have our fast and uh slow meets at some point if that meets then it is the point where we are going to declare another node in the head of the linked list so as i said once we declare slow 2 we are going to move slow and slow to equally by one node at a time and when they meet that is the solution we are going to return so yes now they both meet at some point that is the starting point of a linked list so we can written either slow or slow two they both are going to point at the same answer if not finally we are going to return null so yes this is it let's give it a try yes so let's submit yes we have completed today's problem and it runs in one millisecond thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
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
987
welcome to january's lego challenge today's problem is vertical order traversal of a binary tree given the root of a binary tree calculate the vertical order traversal for each node at position x y its left and right children will be at positions x minus 1 y minus 1 and x plus 1 y minus 1 respectively the vertical order traversal of a binary tree is a list of non-empty reports list of non-empty reports list of non-empty reports so nodes for each unique x y x coordinate from left to right each report is a list of all nodes at a given x coordinate so that's the vertical axis the report should be primarily sorted by the y coordinate from highest y coordinate to lowest so from top to bottom and if any two nodes have the same y-coordinate y-coordinate y-coordinate the node with the same smaller value should appear first so what that means is if it's at the same x-y coordinate if it's at the same x-y coordinate if it's at the same x-y coordinate then we want to add the one that's smaller first into our list if we had a binary tree here you could imagine overlaying this binary tree on an xy graph and this 315 is going to be on the one of the vertical axises same with the nine same with 20 and same with seven so we want to output a list of lists in order from top to bottom with 9 315 20 and 7. same thing here except you can see that 5 and 6 actually share the same x y coordinate so we take the smallest one here so that's going to be one five six in the middle right like that okay so my approach here i've seen this problem before what i'm going to do is create a lookup of some sort that's gonna have the vertical access as its key and a list of all the values in order from top to bottom and i'm going to traverse through our binary tree using a depth first search because that's what i'm most comfortable with you could do a breadth-first search but i'm just going breadth-first search but i'm just going breadth-first search but i'm just going to go with that for search here so what i'll do is create a lookup dictionary what i'll do is call it a default dict and make a list as the type and i'm going to write a helper function dfs what do we want to pass in we're going to pass in the node but we're going to also have to keep in keep track of the x y axis so x y we'll pass in those two as well the x-axis is gonna be the vertical axis the x-axis is gonna be the vertical axis the x-axis is gonna be the vertical axis and that's gonna be the key inside of our lookup and we'll pass into y and i'll show you why later but for now let's just do our typical depth or search if not node go ahead and our recursion otherwise we will add to our lookup at the x value the no dot value after that we will traverse to the left first and we will actually subtract one from the x as well as the y and we'll do the same thing on the right except we will add to our x-axis except we will add to our x-axis except we will add to our x-axis and we'll still subtract from our y-axis and we'll still subtract from our y-axis and we'll still subtract from our y-axis like this once this is finished we will have to run it with a root as well as zero being the very first x-y coordinate and we can the very first x-y coordinate and we can the very first x-y coordinate and we can take a look at our lookup and just show you what i mean so here's what it looks like and you can see the answer is in it's not sorted because it's a dictionary but we sorted it and start with negative one we'll have nine then three fifteen then twenty then seven so it looks like this is done all we need to do is sort our dictionary uh but that's not quite the case and the reason for that is we're doing it that first search imagine that we had a binary tree that looked something like uh something like this and kind of ended i don't know what went all the way just went like all the way forth right here but say that we had some other tree that also went this way uh but then started turning the other way underneath like just stepped on going forward all the way down here i don't know if i'm making sense um hopefully you can kind of visualize this binary tree like if we did a different search we would go down this step first right and we'd be adding these numbers but unfortunately these actually come first with here i'm not actually keeping track of that at all so the answer would actually end up being wrong because these would be appended first so i need to take care of that like you could just sort it at the end um passing in the y axis but what i'm going to do instead is instead of appending it to our lookup our list we'll do a heat push we'll make this into a heap it's still going to be a list but we just need to keep pushing to it but what i have to do is pass in a tuple with the y value as well as the no dot value and later on when we pop it off of our heap this will be in order of the vertical order so that's going to allow us to just take care of that at that point one thing to note is i actually need to make this a negative because since we're subtracting here uh we don't want to add from the bottom to the top we want that from top to the bottom so we just make that a negative okay so now we want to do that for search now we have our lookup so let's go through our lookup and to do that really i can just say just sort our dictionary and say for key dot value in sorted what do we want to do well okay the k is going to be the vertical axis right and the v is going to be that heap so what i'll do is create a temporary initialize list as our output we're going to create a temporary list and while we have our heap let's pop off whatever is off our heap call that a candid we'll do a heap pop and this is going to contain what the y value as well as the known value right so all we need to do is actually add the node value which is the second item inside of our candidate and we can just ignore that first item because whatever gets popped off that should be in order now if it has the same value here well we're okay because it's going to pop off the second one that's the least and that's going to come out first so once we appended everything add to our output the temp list and finally return our output um okay so what i do wrong here sorted all right parentheses okay so that looks like it's working let's go and submit this and there we go accepted now time complexity it's a little complicated um we know that the depth of search is going to be an o of n and because we do a sort at the sort here um that's gonna i suppose be the length of however or the width of this binary tree so that could be i don't know it's called w log w maybe and we also have this heap insert that makes it also a log so i think just gut feeling this ends up being a n log n um time complex complexity as well as using oven space for r for our lookup all right so that's it hope that helps um i know there's all sorts of different ways to do this i did it differently before so hopefully we can continue to creatively think of new ideas and ways to do it alright thanks for watching my channel and remember do not trust me i know nothing
Vertical Order Traversal of a Binary Tree
reveal-cards-in-increasing-order
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Array,Queue,Sorting,Simulation
Medium
null
1,678
hey guys welcome back to my youtube channel how are you all doing so today in this video we will try to solve lead code problem 1678 which is to do goal passer interpretation so what we have to do is basically you have been given a string here which is a input uh the input string it's a string which is g and then uh the curly brackets and again brackets and inside a string in it al so the whole thing is you have been given this input and you need to get the output goal so every time you have to get the output goal it could be with multiple o's and a so how it works is if it's a g if input has a g like just take this single string then you get the output g if it's a bracket the bracket without nothing in it like empty bracket then this means o then you should return o and if this bracket has any string in it which will always be a l then you should return a l with it so which means g o a l so in this instance if you see this is g this is empty string so which means oh so g o and this means a l so this whole thing means a l right that's the whole point if like this is literally this thing you have to translate so every time any of these things are in the input you have to return this thing and you have to add all of them together and just written it as output that's the whole thing so i'll just write it so basically if it's g you want it to be g so literally we're going to solve this problem using if and else statement because it's uh easy so if it's a g you written g and if it's not g but if it's this thing right i'll show you how to solve if it's this thing then what you want to do if it's this thing then what you want is then you want to check that what is the next element after this so next element after this you want to check what is it then if it's this thing then what you want then you want to output o and other thing you could check that if it's this thing right like just the first bracket is there and next thing you see that next thing you see if it's not this thing right and if it's this l then what you want to output l easy as that's the whole question so for this example goal let's we'll keep that in mind and we'll try to solve it so how would you do it for this one it would be g and then o for this one and this is a l so a l easy so let's try to solve it if you want you can try it now but it would be just using a file statement and let's do it so as usual i'll so what we'll do i want to store the output in the array so i'll create an array which will be named as output and i will create a i'm using very well here and create a new variable called new command code new command so what is this command is the input which is this goal so i don't want it directly so to go through this whole string i want to loop through it i want to use a for loop right and you cannot use a for loop on a string directly you want to split it because i want to get hold of all this element if it's g i want this g if it's this empty string i want this for that i'll have to separate all of them for that i'll use a split method of array built in javascript method so what i'll do i'll say okay variable new command equals to i'll say command and then i'll say okay now what i want to do i want to split it right so i'm saying split use the split and i want to split it by each character so after this what i'll get here this new command right now here it's like you can think something like this g this right and like this it's literally like this thing and then the other thing is like this like everything is divided into you see these things are divided like this as well and same goes like this it's more and for this like same like this and probably this o is here and then a is here and then l is here you get it what i am trying so basically everything is divided you got it and so that's what going on that's what's going on right so right now we have got hold of all the uh characters and now what i want to run a for loop so i'll say for variable i equals 0 i should be less than new command c new comma new command dot length and i want to run it every time by creating increasing it by one that's it so now we're just gonna use the file statement so what as i said you in the beginning what we're gonna test all the cases so i'll say if new command at i right and what we will try to do we'll use it using the three equals so when you want to when we use three equals you are checking directly with the exact identity so here i'm checking if new command at i so i'm checking if this g if it equals to basically in the beginning i'm saying if it's equals to this empty bracket so basically i'm going through this whole thing what was here in this goal i'm saying if it equal to this empty bracket right then i want to put if condition and then i'll say if it's equal to this then i want to check one more thing i want to say if new command and now i want to say i plus 1 because i want to check what's after this right i want to check that so under if i plus 1 if this thing if it's equals to this thing like if it's opening and then if it's closing like i already got to know that if it's opening and if it's closing then it means it's this and this then what do we want it to be we want it equal to be o then what i'll do i'll say output ut output dot push and then what i'll say okay output dot push i want to push o which will be gold o right but if it's not this like if it's this but the next i plus one is not this then what i'll say i'll put here else if condition right i'll put an else if condition that if new command at i plus 1 right because you are checking the after element if new command at i plus 1 equals a or if new command at i plus 1 equals l so it could be any of this thing if any of these things are there then what i want is i want to output dot push i want to put into that output array i want to push into that output array what do i want to push a and that's what we said see if it's a or l then see we want this thing right a l why we did this because if this is there it will push a l and if this is there it should also push air and we're just taking for i plus one time and there is a problem with this so what the problem is that if it's a then it would push a l right because it's o or get we are using but then you will say if when it goes to a l again it will again push l and we don't want that right that's why what we'll do we'll say whenever any of this thing is there you do i plus so you get out of this loop and so what happen we check two cases if it's al we will get the value if it's the brackets we will get the value now what's left so see this else condition else if it's ending here and this is the main if condition which is ending here and what we'll do is here that after this else condition and so once we have checked that if it's this one if it's this then what i'll do after this i will put again else if condition now why we are putting this elsif condition because now we want to check that if it's not this which means what is it only one thing left g so else if you can directly put a condition but i'll put an just to make it clear i will write the whole thing you can directly write else and you can write so i'll say if new command at i if it's equals to g the goal g right then what do i want to push output dot push on to push g for goal and after the whole for loop is completed what we'll do we want we don't have to do anything just output dot push that's it and output dot push what new command that's it and if you push it now you will get all of this but with the comma but we you don't want the comma in it so what you'll do you'll say return output oh sorry output.push now you will say output.push now you will say output.push now you will say return output dot join you want to join it right so you will join all of this and you don't want it with a comma so you will put a comma here so what will it will join all of them with all the commas so it will remove all the spaces between it and then you just want to return it and if you run the code now then it should work see you got the good answer and now if i try to submit it then you should get a good solution as well yeah you got a good solution so that's all for today's video if you came to my video it means you like how i try to change so make sure you subscribe my channel like my video and share it to your friends who wants to start learning lead code because this is literally one of the easiest way you will find to solve problems on lead code thank you
Goal Parser Interpretation
number-of-ways-to-split-a-string
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Math,String
Medium
548
84
hello welcome back today I will solve liquid 84 the largest rectangle in histogram we're given an integer array height and this represents the height of each bar for the histogram the width of each bar is 1 where it has to find the area of the largest rectangle in the histogram here is another representation of the heights array so you can see the value here represents the height of each bar with a one so one of these rectangles that we have to find for example here it would be a one rectangle within the histogram here will be another rectangle within the histogram here's a third example of a rectangle within the histogram the one that is the largest one for this particular histogram is this one and has an area of 10 units let's talk about the height of this rectangle first what are the possible Heights of this rectangle well the height could be any of the value in the Heights array so it can have a height of 2 1 5 6 2 and 3. the values in the array Define the subset of heights that's possible for all the rectangle if we are looking for the largest rectangle we can in principle iterate through the height array mors what's the biggest rectangle one can make from this height and then we can go to the next one and say what's the largest rectangle we can make from this height and also this height and so on now that we talk about the heights let's talk about the width of these rectangles that we can make take this rectangle of example this has a height of five what are the boundaries of this rectangle for this height the width is defined by the two indexes on the left and on the right look at where the boundaries are for this rectangle what is the bars that it can include as you can see if you have the height of 5 the rectangle that you can make from that height would include all the bars that of the same height or higher on the left and on the right the boundaries are defined by the bar that has a lower height or the boundary of the array so the example here on the left hand side you can have a one which defines the left hand limit because one is smaller than 5 and on the right hand side you have the value of 2 here which also because of 2 is less than 5 it defines is the limit on the right hand side since the width of the rectangles are defined by a pair of indices we can imagine that we can go through all possible pairs of indices and we can find the minimum height between those pairs of indices and we can figure out the rectangle one can make within the boundary of those pairs of indices now that is not a bad solution to go through all possible pairs of indices thus are all of N squared solution given this series the other solution for this problem is that we will find the nearest smaller number on the left and a smaller number on the right for each bar then we can determine the boundary for the width of each rectangle for each bar in the histogram now let's go through the process of establishing the limits of each rectangle on the left hand side and also on the right hand side we start with the index of the array now let's just add two more index on this on the left hand side left of zero we put minus one and on the right hand side on the right of the last element we just put another index here as the length of the array next we determine the index of the smaller value on the left for each item in the array for example the first value here is 2 there's nothing left of two so we put -1 there's nothing left of two so we put -1 there's nothing left of two so we put -1 that's where the minus 1 is coming from the second module is one and then there's nothing smaller than one on the left hand side so again we put -1 the left hand side so again we put -1 the left hand side so again we put -1 the third value is five and we see that the nearest model value on the left is one which is index one in this manner we'll go through each item in the array and we will populate these values here next we will also determine the index of the smaller value on the right hand side the first item is two and the nearest model value on the right hand size one so that is index one the second module is one and we don't see any smaller value on the right hand side so we will take 6 from here the third value is five the nearest smaller value on the right hand side is this value which has an index of four so the four goes in here we can go through this process the value that as shown here once we have both sets of values then we can calculate the width for each bar and the formula here is that left equals to the value on the right minus the value on the left minus one for example this rectangle so this rectangle has a height of 2 we take 6 e minus one here and B minus 1 again we got four so the width is 4. and let's take a look at another example for example the height of 5 we have on the left hand side we have a four and then we do a minus one and then minus one again four minus two is two so the width is two now that we know how to establish the width for each bar and we also know the height it's easy to calculate the largest area we can make from each of these individual bars the values here we're gonna hold that in Array called left and the values here we can hold those values in a ray call right so the pseudo call for this function would be we just initiated both the left value and the right value we write two functions where we're going to establish the index of the smaller value on the left and the index of the smaller value on the right and then we will iterate the array and then you're going to use the height times the width we'll get the area and at the end we will turn the maximum of the area that we have found now let's talk about these functions find smaller left and find smaller rate we're going to use a monotonic stack for these functions if you don't know what a monotonic stack is I strongly encourage you to pause the video and watch the first video of this series the link to that video is in the description below there I discuss in detail how everything works and explain every lines of call also we have established a template where we can use for this kind of function is to find the nearest smaller elements on the left we use this template from Video One and in this template we will populate the left array we're building a stat when we're iterating from left to right because we are looking for the smaller value we are making a step that's increasing and then we're gonna assign left sub I if the stack is empty then that means there's no smaller value on the left sub I is going to be -1 the left sub I is going to be -1 the left sub I is going to be -1 so remember the index we talked about earlier we use -1 on the left hand side we use -1 on the left hand side we use -1 on the left hand side otherwise we just take the item on the top of the stack and use the index the stock is going to be holding a tuple which includes the index and also High sub I to find the nearest smaller elements on the right we will use this template where we're going to populate the right array here we are entering the heights array in the reverse order we are looking for the smaller element so the stat will be strictly increasing if this stack is empty we will populate rise of i as the height dot length remember on the right hand side if we don't see a smaller element we'll take the boundary of the array and we will assign the value 6. and if we do have a smaller element then we will just take the item on the top of the stack and take the index of there will push under the stack a tuple which includes the index and height sub I now that we have discussed the pseudo call let's look at the real call this c-sharp implementation is available this c-sharp implementation is available this c-sharp implementation is available in the GitHub links below we have the left and the right array and then we will have this function of find smaller left and finds mono right where we will take in the height array and then we will have the for Loop we iterate all the different bars in the histogram and we'll determine the area and we take the maximum area that we have seen and return this as the maximum rectangle that we can generate now let's look at the find smaller left and find smaller right function these are just sort of very similar to the pseudocode that I talked about earlier both will populate the stat and the stat will take in a tuple which includes the index and also the value and the value here will be the height of each bar in the histogram before we test the call let's talk about the runtime complexity as we are using a monotonic stack each element will place in the stack exactly once and they will remove at most ones so the one time for everything here is O of n okay now let's test the call and it looks good if you'd watch the video solution for this problem on recall you will see that there is a more elegant solution for this problem but the point here is not about finding elegant solution for any particular problem it is about having set up building blocks at a disposal so that we can solve problems that we have not seen before hope you like this set of videos on monotonic stack if there's anything that you want me to discuss please leave a comment below see you next time
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
1,026
hey everybody this is Larry this is day 11 of the Leo day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's prom uh and I'm doing a thing that I did last year but I kind of well I went traveling so I stopped doing uh I am going to do a random premium problem that I haven't done before um if the problem that I've done or doing now if the daily problem is a problem I've done before I'm going to do one that I haven't done yet trying to get my premium money's worth you know anyway today's PR is 1026 maximum differences between node and ancestor so yeah hit the Subscribe button if you want to do an extra problem with Larry also come to the Discord and just chill I suppose uh today's problem is yeah given a root find a maximum v such that there exist different nodes A and B where V is equal to a okay and oh n a is an ancestor B I guess that's the big thing uh okay oh you're try trying to find a maximum value so you're not even um okay so it's not even looking for a given we okay uh I mean I think this is a very reasonable problem for um I think if you know this is a contest now or even indw level this is probably something that's slightly below the indw level so I would definitely recommend you um to really be able to not only do this but do this way quickly to be honest um you know to give yourself the best chance I think this is a very reasonable problem and this one you have to maximize uh the absolute value and really um when you see Max or when you see absolute value and you try to maximize it well then they really only um so the way that I would think about it is breaking down the cases and that is that uh where a the previous the ancestor is going to be the Max and ancestors the Min those are the two things that I would consider and with that in mind we will start right because basically the idea is that you're trying to maximize either let's say a is the ancestor I guess that's the definition you're trying to maximize either this or maximize this right that's what that's how we break down the absolute value um into the two components and that's pretty much the idea right and of course here um we store this as this is the max if we try to maximize this part then this has to be the biggest if we're trying to maximize this part this has to be the smallest so that's how and even negative right I don't know if that negative is an input I guess negative is not an input but these are the things that I would think about and it generalizes with negative anyway so that's why it doesn't really matter as much maybe actually is that true yeah should be true so yeah so basically now um yeah here maybe I would hm yeah so that now they lot of ways you can write it but let's say best is equal to in uh oh zero not Infinity that's what I was trying to figure out so we should have an Infinity well this is it's just my Infinity I don't know it's not really a big thing uh but yeah but here then we can do uh a Traverso so we Traverse node we want to maybe have the max the Min um on the previous thing right and if node is none we can return otherwise you know we could do a pre-order doesn't really we could do a pre-order doesn't really we could do a pre-order doesn't really matter which order as long as you look at every node and then yeah non local best is equal to so you want to so max so okay so let's define this real quick node is just the current node okay Max is the maximum max value of the ancestors and Min is or MN is min value of their ancestors just to be clear just want you know so then now we can Max either um MX minus the current no. value or you know no that value minus the minimum value and that's pretty much the idea and then now you could transverse trans Traverse transverse oh my English is hard uh and then we pass it down right I guess we use this actually so and also that's not a function but okay fine uh so yeah so then now you could do and there you go and then of course you also want to do the other side as well not that way and that's pretty much it uh you want to go bring it to the root you want to do negative infinity and then we just return best hopefully this is right because otherwise it's just embarrassing it's not that embarrassing people make mistakes all the time uh but yeah 1381 day streak um we've been doing three problems all uh all couple of days I guess it's not that long but uh but yeah that's why I go little complexly when you look at each node on it's always going to be linear time linear space um l space bring the height of the tree you implement stuff on the stack um yeah that's pretty much all I have I mean pretty straight forward pretty reasonable I soled this oh that was I keep on thinking it's 2023 I was like oh look I solved it like not that long ago oh man this is way more complicated I don't know uh but yeah I guess in the past I've done it more complicated well maybe not I think uh I me just oh and this is just recursion instead okay fine uh but yeah that's all I have for this one let me know what you think uh I'm going to do an extra one afterwards so if you want to you know hit the Subscribe button let's do that uh it's Wednesday is hump day hope everyone has a great rest of the week I'll see you later and take care uh wait stay good stay healthy to your mental health I'll see you later and take care bye-bye
Maximum Difference Between Node and Ancestor
string-without-aaa-or-bbb
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\] **Output:** 7 **Explanation:** We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. **Example 2:** **Input:** root = \[1,null,2,null,0,3\] **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[2, 5000]`. * `0 <= Node.val <= 105`
null
String,Greedy
Medium
null
231
alright so this lead code question is called power of two it says given an integer write a function to determine if it is a power of two example one is the number one a powerup - yes it is because number one a powerup - yes it is because number one a powerup - yes it is because two to the zeroth power is one example two is sixteen a power of two yes it is example three is two hundred and eighteen a power of two no it's not so we returned false all right what this question wants to know is whether the N being passed in is a power of two the key to solving this is to figure out the powers of two that are less than n and when you come to a power of two that is no longer less than n you just compare it to N and if it's the same thing then yes it's a power of two if it's greater than it's not a power of two I'll show you what I mean so you start with two to the power of zero that's one is that less than ten yes it is so you keep moving on what's 2 to the power of 1/2 is that less than 10 yes so power of 1/2 is that less than 10 yes so power of 1/2 is that less than 10 yes so you move on what's 2 to the power of 2 4 is that less than 10 yes so you move on what's 2 to the power of 3 8 is that less than 10 so you move on what's 2 to the power of 4 that's 16 is that less than 10 no so you stop now what you do is you take that power of 2 so 16 and you see does it equal and if it does then yes it's a power of 2 if it doesn't then no all right let's get to the code what lead code has given us as a function called is power of 2 that accepts a parameter N and it's just the number we're trying to figure out whether or not it's a power of 2 all right so the first thing we could do is we can eliminate any number that's less than one because remember the first power of any number is one so we'll say if and it's less than one we will return false because it's definitely not a multiple of two now we'll create our variable that will hold all of our powers of two we'll call it power of two and will instantiate it to the number one because the number one is the first power of two next we'll create our while loop that will increase our powers of two and compare it to our n so we'll say while power of two is less than n what are we going to do we're going to increase it to the next power of two so power of two equals the power of tour on times two so the next power of two so like I showed you before what this is gonna look like is this the first power of two is one so then the while loop is gonna say is this less than n yes it is so now it's going to save the next power of two into this variable which is two is this less than n yes so it's gonna make it the next power of two is this less than n yes it is so it's gonna make it the next power of two it's this less than n yes it is so it's gonna check one more time it's gonna make power of two sixteen so we're at line twelve again is this less than n no it's not so now we can check to see if this number is a power of two so what we're gonna do is we're gonna return whether this number in this case it's 16 equals n all right let's quickly do it one more time except for n being eight erase these okay so at line 10 it says let power of two equal one which it is while loop is this less than n yes so make it the next power of two is this less than n yes it is so make it the next power of two now is this less than n no so now we're going to check whether it equals n so we're at line 16 does this equal n yes it does so let's run the code it looks good let's submit it all right so our solution was faster than about 48 percent of other JavaScript submissions as usual the code and written explanation are linked down below if you liked the video give it a like and subscribe to the channel see you next time
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
285
all right we're going to do inorder successor and a bst so they give us the root of the tree and they give us some node p and we just want to find the successor of p which is just the smallest value which is greater than p um so we'll do this two ways the first one we're gonna the first way we're gonna do it recursively then we'll do it iteratively so recursively uh what's our base case so if the root is null then just return null and if the value of the root is less than or equal to p's value well if this is smaller than p because less than or equal or it's smaller or equal to p and we're trying to find a value that is greater than p we want to find the smallest value that is greater than p well we need to recurse towards the right side right because in a binary search tree the smaller values are towards the left and the bigger values towards the right so we're going to go further to the right side let me copy paste that and we're going to just recurse towards the right side and this p here is never going to change we're going to keep passing in p don't think that's going to change whether we're going towards the right or towards the left okay now if we've gotten this far oh actually this should be returning so we're going to return whatever's whatever we find on the right side that is greater than p but anyway so after we get past this if uh if we get past this condition and we're down here and that means that root value is actually greater than p now that means that root is the potential successor of p we don't know for sure yet because there could be some value that is smaller than this roots value but it's still greater than p so here's what we're going to do we're going to recurse towards the left side so tree node left equals let's just copy paste this we're going to change this to left so now we recurse towards the left side and now we're going to return if left is null actually let's do this if left isn't null return left otherwise return the root and why does this work so if we were cursed towards the left and we find a value that is less or that is greater than p then this value must be less than the roots value therefore we have to return left i'm going to say that one more time so if we found something so when we were cursed towards the left side if we found a node that is greater than p because we went left that means that this value this root dot left it must be less than root stock root dot val so that's why we're going to return left here if we found anything and if we didn't find anything well then root must be the successor because root was if we got this far remember if we got this far this means that root.val is greater than p that root.val is greater than p that root.val is greater than p all right so let's do the iterative solution now let's just comment this out copy copying the signature and all right so for the iterative solution our algorithm is basically the same thing we're just going to iterate down our tree and we're going to step towards the right we're going to step towards the left depending on whether the value that we're currently at is greater is less than or equal to p or greater than p and we're just going to keep track of the minimum value that we find along the way that is greater than p so uh let's create a temporary or a variable to iterate down our tree so let's call it current occur and set it to root and we're going to keep track of the minimum value that we find that is greater than p so i'll just have this null for now because we haven't found anything yet and while current is not equal to null we're going to say if current dot value is less than or equal to p's value so if this value is less than p or less than or equal to p that means we need to step towards our right because we're looking for values that are greater than p so we're not current all right current equals current all right okay and if we find a value so this means so for if we hit this lcm that means current dot value is actually greater than p's value which is good that's what we're looking for we're going to go ahead and set min equal to current because this node is greater than p right okay and we're going to say current equals curve dot left because if this value is greater than p we're we now need to look for smaller values or values that are smaller than this current but that are still greater than this p so we want to step to our left and if we so let's say we set so curve equals per dot left we're going to step to our left and when we go through this iteration again if we hit this again that means that because we step to our left that this new curve must be smaller than the last min that we encountered so we're going to go ahead and set min equal to that current and again we're going to try stepping to our left again um and again this whenever we hit whenever we go inside here this also means that current.value is greater than p's value current.value is greater than p's value current.value is greater than p's value um which is good because we're looking for values that are greater than p um but anyway like hopefully you can see this that every because we're stepping to our left because it's a binary tree that means we're going towards smaller values and every time we go in here that means we've encountered a smaller value that is still greater than p because if it was less than or equal to p we would have gone in here all right and then all we have to do is return them in at the end because this represents the smallest value we encountered that is greater than p let's just run this and submit cool so that's the iterative solution um so this would be o of one space compared to the recursive way which would be o of h space where h is the height of the tree uh time complexity for both of them would be log of i want to say log n but um if this binary search tree is actually like a linked list then it could be i guess worst case could be o of n so it could be i guess the worst case is o of the height yeah so in the worst case for both of these and for the time complexity um yeah it would be o of the height of the tree okay um so that's pretty much everything for this question uh if you have any questions you can leave a comment and you can like subscribe whatever all right bye
Inorder Successor in BST
inorder-successor-in-bst
Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`. The successor of a node `p` is the node with the smallest key greater than `p.val`. **Example 1:** **Input:** root = \[2,1,3\], p = 1 **Output:** 2 **Explanation:** 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], p = 6 **Output:** null **Explanation:** There is no in-order successor of the current node, so the answer is `null`. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` * All Nodes will have unique values.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,173,509
545
hey what's up guys this is Chung here again I'm still doing this please called tree problems so today let's talk about the this number 545 boundary of binary tree okay let's see what does this problem want us to do here so you're given a binary tree right and then you're going to return a value of the average boundaries in the anti-clockwise direction right anti-clockwise direction right anti-clockwise direction right anti-clockwise direction what does this anti-clockwise direction what does this anti-clockwise direction what does this mean left boundary is defined as the path from root to the left most node right boundary is same thing define of the path of the rightmost node right the left most node is defined as a leaf node if you could reach when you always first refer to the left subtree if it is if not travel to the right subtree repeating to reach or leaf node the right sub node is also defined by the same way with the left and right exchanged okay so what does this mean let's take a look at this one here at this tree here so we have a 1 okay so we have 1 2 3 4 5 seven eight six nine ten right so what is the left boundary of this tree as you can see here from one two actually it's a except for the root right the left boundary will be two and four right like what we discard like of the definition for the left boundaries we keep going to the left and heal until that indeed this element the last element on the left side doesn't have either a left or right so what does it mean so did for example this one for is to phrase the root right because the four doesn't have any left or right if this one has another if the four has another like eleven let's see there's a to the eleven here as it's a right subtree then the left boundary will be two four and eleven right because that's what we were doing here as long as this last node has either a left or right side if it has a lap side always call to lap if it doesn't have lap side we call so we call the right until there's no child tree of this one and same thing for the right side for the right boundaries here three we have three here we have six right we have six and then we have ten right so ten will be the rightmost node here and that's the left and right boundaries and then we also need to find that the leaves right so it says we're from the left and then plastered the leaves here plus the leaves that so this kind of leaves right the leaves and the right side basically it's gonna be anti-clockwise which means it's from anti-clockwise which means it's from anti-clockwise which means it's from root left for I just remove it for some reason sorry let me try it real quick here six so the question asked us to get the result from for the left leaves and the right boundary in the anti-clockwise so what does it mean so anti-clockwise so what does it mean so anti-clockwise so what does it mean so from one to four right and then that's the left boundaries and then go to the leaves seven eight nine right and then turn right turn them back to six three that's the result the question wants us to do so how can we think about this question right I mean we won ways we can all we can get which is followed we just follow the that's that description we get all the for the left boundary we are Traverse we get all the note for left boundary Traverse will be one to four right and then we get all other leaves will be four seven eight nine ten right and then we get all the right boundaries 10 6 3 1 but notice that so the left most node and the rightmost node they will be uh they're also part of the Leafs at right so in that case if we get those three sides we just combine them together we need to make a track we need to make sure this left most node and rightmost node doesn't get added twice that's one way right and another way is the to avoid checking duplicate is movie Traverse we Traverse for the leftmost tree right we stop here right we stop add to here we with basically which is we add two here and then but when we see four we don't add four because we know four will be the our last left the most tree left most node so we only add two same thing for the rightmost node right away we Adam from three six and when we see ten here we don't add it we just stop right here and then we'll be having two and ten here so in that case we don't have to worry about this like duplicating right we just stop at one level before then we'll have four seven eight nine ten is the leaf node and then that should work okay yeah so basically that's the basic logic here and let's try to implement this thing here so first so basically we're going to define three helper functions first one will be like DFS for the lab for the left boundaries right we can talk called leftmost right node and then we'll have another one DFS rightmost sorry now leaves move to a Leafs first second because that we won't do it anti-clockwise right and then it's do it anti-clockwise right and then it's do it anti-clockwise right and then it's gonna be another one yeah yep as right-most right-most right-most right same thing for the node okay so let's write the main structure here so assuming we have those two nodes right and then we're gonna have a we have sorry assuming we have those three helper functions and we'll have a like result to keep the final very right so okay of course the finer is out the first one will always be the root note right because we're always starting from the root so we add the root value to the result first then we do what we do a left side Traverse right we Traverse to the left side and here I preferred to a check here so basically if the root dot left if there's a left right if there's a lab I do the track here you can also do the track inside here but I in my case I preferred to the check beforehand so and then we do a DFS right left most right mmm root left right and then for the Leafs note which is fine we don't care about the Leafs no we just sorry for the Leafs now that we don't care about that's alright we just to pass the root note to basically TFS leaves right past the root to get all the Leafs node and then we do a quilt reverse on the right side basic TFS right most can be routes that right so in the end we simply return the result here yeah so that basically that's the main structure of our code so now it just comes down how can we implement this left side leftmost traverse here right so the main part is if node right if node has left right if node has a life one we always go to the left if there's note has a life that we go to the we always go to laugh because we want like the definition of the lab I love the most know that we all we always try to keep try go to the left first right note how the left and house and then we go right I'll see if basically house if not he wants to write if there's a right-side subtree we go to there's a right-side subtree we go to there's a right-side subtree we go to the right basically right remember no notice here we do a if else here because if there is a laugh one we don't need to go right to be cold we always try to call left as much as possible if there's no left sub-tree and possible if there's no left sub-tree and possible if there's no left sub-tree and then we go right so that's why we have evals here and so here right so remember well while we were traversing the left sub-tree a left most node will the left sub-tree a left most node will the left sub-tree a left most node will keep adding the results to the to our final result right no the value here and remember we want to stop we won't stop at to here because so we don't have we do not add for right so what do we do here we do a check here so if note that left if the note doesn't have left and basically if this node is a leaf node right and not note right we just basically we just stop here right see otherwise it will add this leaf node for example here we have one two and four here right so when once it we reach for here and we see four is a leaf node basically doesn't have a laughs all right and right subtree so which keep simply return you before adding it to the final result so in this case and so once this is done we have to and we have to right now so basically so that's pretty that's it for the left for leftmost helper so now we want to write this like leaves here okay so for the Leafs note we can they're like I think not more than one ways we can do the Traverse we can do either - we don't need to do a can do either - we don't need to do a can do either - we don't need to do a pre-order or in other traverse yeah pre-order or in other traverse yeah pre-order or in other traverse yeah because I think for the Leafs note we just need to traverse all the way down here we don't want to do a post order because remember we want to output the tree node from left to right as long as the secret trevor sequence from left to right it's fine so basically either pre-order in-order will basically either pre-order in-order will basically either pre-order in-order will give us that sequence if we want if we do a post others tell the Leafs node will start from right to left which we don't want right yeah okay so let's do a pre-order traversal right three other pre-order traversal right three other pre-order traversal right three other means we traverse left side further all the way to the left and then to the middle and then to the right to the route to them to the right okay so first not note right we just simply return right that's the basic here if and then we do go it with outside we do a DFS we do a recursion Traverse here note dot left right and then we do something here do something and then we traverse turn to the right side right do something so what are we doing here so we check if this node if this if the node doesn't have a laughs or if this node is a leaf node or not right if not no not like what we described what we check in the leftmost method here no doubt that right and not right never panicked right the pendous went to the rear we found this note to the Torah final result because we know that's one of our leaf node doctor okay right but remember here we need to do add another check here we need to make sure this node is another root node right let's assume basically assuming we have a that's it we only have one node here this is there's one there this tree only has one node here and we're passing the this root here and this one doesn't have left or right but we cannot treat this one as a node because the root is a root is not a leaf node right that's why we need to check the root node here so if note is not root right and it's a leaf node then we time is this one here same thing for the rightmost thing so you can just copy most of the code from the left most one first we stopped right we stopped it and then here if nodes but remember here we have to check right side first because we're going to the right first right all the way to the right and the rightmost right and then no right if there's not a right subtree will and will go to left right now go to left we go to the left right but then remember so here's one thing you need to we need to pay more attention here so basically remember once we reach 10 here we start from we start traversing the right side right remember we're traversing from top down right top down here so we'll get three first and then six right but instead we won't add six first and then three it's basically like a reverse right I mean they're like cut they're like a easier way you can do it you know you can like define out a temporary array somewhere here like instead of result you can define another one like to store you can use the same thing basically you can just keep adding these values here at the beginning of this like rightmost traverse the in the end you just reverse that's us how that sub-arrays and then you to Japan that sub-arrays and then you to Japan that sub-arrays and then you to Japan that reverse rate to here right that's one way of doing it and the other way of the really is we don't have to use like a hyper array so instead of adding this result at the beginning of the trip of each Traverse we can add it at the end right so add app and right so that's how we do a reverse Traverse that we added here but in the end that in that case basically when we get all the way down here right and then basically we'll add six first and then three right yeah okay I think that's all we need to do here let's try to run it cool oh yeah it's always the sanity check here if not roots simply returned empty array okay let's see so it has to be oh yeah I know so here remember here we are using the same leftmost sub helper function yeah here yeah same thing here because we're using the same recursion functions yeah that's why I got in future left right and right typos alright cool pass so just to recap real quick we do a leftmost Traverse to get all the left side boundaries and but we stopped before the left most unknown which is also part of the Leafs node so that we're gonna add this node twice and once the left side is finished and we will get the Leafs node from left to right you can use either pre-order or in other traverse here pre-order or in other traverse here pre-order or in other traverse here we're using a pre-order and then the we're using a pre-order and then the we're using a pre-order and then the last part is the to traverse T at the right most boundaries rightmost node to get the right boundaries but in this case we'll be adding the values at the end so that will get the result from bottom up right and here yeah some chaps are small things you need to take into account don't treat the root node as a leaf node and then we had root first do this and then finally we just return the result okay cool guys I think that's it for today thanks for watching right see ya bye
Boundary of Binary Tree
boundary-of-binary-tree
The **boundary** of a binary tree is the concatenation of the **root**, the **left boundary**, the **leaves** ordered from left-to-right, and the **reverse order** of the **right boundary**. The **left boundary** is the set of nodes defined by the following: * The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is **empty**. * If a node in the left boundary and has a left child, then the left child is in the left boundary. * If a node is in the left boundary, has **no** left child, but has a right child, then the right child is in the left boundary. * The leftmost leaf is **not** in the left boundary. The **right boundary** is similar to the **left boundary**, except it is the right side of the root's right subtree. Again, the leaf is **not** part of the **right boundary**, and the **right boundary** is empty if the root does not have a right child. The **leaves** are nodes that do not have any children. For this problem, the root is **not** a leaf. Given the `root` of a binary tree, return _the values of its **boundary**_. **Example 1:** **Input:** root = \[1,null,2,3,4\] **Output:** \[1,3,4,2\] **Explanation:** - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root's right child 2 -> 4. 4 is a leaf, so the right boundary is \[2\]. - The leaves from left to right are \[3,4\]. Concatenating everything results in \[1\] + \[\] + \[3,4\] + \[2\] = \[1,3,4,2\]. **Example 2:** **Input:** root = \[1,2,3,4,5,6,null,null,null,7,8,9,10\] **Output:** \[1,2,4,7,8,9,10,6,3\] **Explanation:** - The left boundary follows the path starting from the root's left child 2 -> 4. 4 is a leaf, so the left boundary is \[2\]. - The right boundary follows the path starting from the root's right child 3 -> 6 -> 10. 10 is a leaf, so the right boundary is \[3,6\], and in reverse order is \[6,3\]. - The leaves from left to right are \[4,7,8,9,10\]. Concatenating everything results in \[1\] + \[2\] + \[4,7,8,9,10\] + \[6,3\] = \[1,2,4,7,8,9,10,6,3\]. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
199
766
hello welcome to the channel and today we have lead code 766 topless matrix so given the damn time and matrix return true if the metric is topless otherwise return fast the topless is totally matches is being like from the top to the right bottom this uh diagonal line is all having the same number so we have two here three here five here it's pretty straightforward and now you can see this all uh fulfill the requirement so in this matrix so we return true but here the diagonal line which doesn't contain the same number then return false first of all when you solve this problem um what we will do is as a person is look at the first number here and then go down like this and look at the second number go down like this and just keep doing everything from here to make sure everything looks good but to the computer code that kind of complicated to go down like this with this pattern um now we have to think a solution that we only go to this area right here we don't need to care about the edges the top and the lab edges go from here to all the way to the bottom right so if this number is same as the previous left top and that we can move forward we check this one the same as this stewie is same as this it's five same and five and here we align to this line so that's the idea of these questions after checking everything up here and then if you see nothing is wrong and then we turn true that's it so to the code we know how to write a um for loop double for loop to loop through area of this character here so now we start from zero 0 right here and i will write the folder for everything first i less than matrix not length i plus y is equal to zero y is less than matrix um so this is double for loop for looping everything so let's start on zero and then the lane go one by one but in here we start from this corner here we go from one and one so we start from one row two all the way down and then column one column two all the way to the dn so the first one is gonna be one row one in column one so now we know this is the area we're looking for we need to check if matrix i y so which is this number here is not equal to matrix i minus one y minus one so it did not so this is the current this i mean integer so compared to the top left one which is minus one here if they're not the same return false and now we're checking every of the location here after the whole for loop if we don't see any false we just return true that's the answer the reason why i don't do the edge cases because i can assume uh the matrix is within the same uh it has the right lane so you see m and ends is within the right range so we don't need to do the um checking here so that's it for this questions now it's all true submitted and it is 100 and that's it and if you have any question comment below and i will see you in the next video bye
Toeplitz Matrix
flatten-a-multilevel-doubly-linked-list
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Linked List,Depth-First Search,Doubly-Linked List
Medium
114,1796
93
hey everybody this is Larry this is November 17. uh I'm gonna do a bonus extra question because the other one was kind of silly uh so yeah and number three maybe I should have talked about the number three a little bit more anyway I'm gonna do an extra bonus question just to kind of you know uh Flex my muscle a little bit um and I don't have put maybe I should have premium if you think I should have premium let me know maybe you can donate to the cause I don't know I just kind of have a thing about I don't know um okay so today's prime is 93 we store IP addresses so it's a medium and it looks like it's going to be a recursion farm and it's the um 20 and I am reading it really fast I haven't seen this before because I've only sat you know on the bonus questions I only saw the ones I haven't seen but given n is equal to 20 you immediately know that this is proof for usable um because this between 20 numbers or 20 digits rather um there's only going to be 19 spaces between them and you can do 2 to the 19 and then just you know check for these rules there'll be not 20 times 2 to the 19th uh or 20 times to the 19th number of work and that's like uh what does that happen 10 million so maybe I mean you probably have to be a little bit smarter but or at least not just python but um but you know it's gonna be fast enough or at least there's a route there um we're gonna do a little bit better um but yeah so okay I just kind of guessed at the problem I didn't really read it but it seems like it validates what I'm saying which is that given a thing you just figure out how many ways I've passed it and of course you know we'll see if it passes in Python but the outside the size of the output is already going to and that's not actually true I got a light about it 2 to the 19 up about because there's only four periods so it's not quite two to the 19 but I'm just thinking like in my head like okay well even if that's the case where it's 2-19 then that's the case where it's 2-19 then that's the case where it's 2-19 then that's good but actually in this case then there's 19 choose four right or 19 choose three to um to put the dots right so you have 19 slots you could choose three and actually if you do the math on 19 choose three and this is on my head it's on order of 19 to the cube it's less than that it's actually like 19 times 18 times 17 over six or something like that if you want to do the thing but um which is going to be less than 19 cubed is what I'm saying um so definitely that is very fast and so you can do it any other way and that's like the Brute Force way right and that's basically if you ask me about how to analyze it this is how I'm going to analyze it if it's worth doing before it's kind of making that progression of okay it's the what is one worst case well 2 to the 19 times 20 for each of the digits and then now next one is actually just 19 to choose three um times 20 I guess also for each digit but that's you know 20 cubed is what like 8 80 000 maybe eight thousand eighty thousand uh um no eight thousand right eight thousand times twenty is going to be you know fast enough uh was that 160. okay something like this yeah so that's kind of get started and that pretty much it brute force is the answer um I'm gonna just do it kind of old school way and which is um and there's other additional constraints so it's not purely 923 but I'm saying even 19 choose three is valid um because in the sense that uh in the sense it has to be between 0 and 255 which means that you can each stat has to be a most three digits array stuff like that so the additional constraints that makes it very um advantageous to do it for in a top-down recursive kind of way so that's top-down recursive kind of way so that's top-down recursive kind of way so that's kind of get started I mean I think maybe I've said enough so uh yeah I just gotta go because I'm lazy um and then just like a current away and then the index maybe index and current and I could just order better um and then if index is equal to four oh no just if length of current is equal to four or um uh if index is equal to n then something like ends without append uh oops Kern um and then return else we just return I guess because we don't have we didn't use all the digits is the point there and then otherwise we just something go like um hmm so for L is a mage of say from one to three so four inclusive or exclusive sorry um so something like go index plus L um and then maybe something like uh index per cell I may be off by one or two or whatever here but you get the idea right so that's basically kind of the um the thing um of course we didn't actually check um we didn't actually check you know this is um this is about a dress and cannot have leading zero so we have to add some if statements here but that's basically the call of the idea let's actually run it real quick just so that I you know I can I know that in this case it'll return more answers than I have and it won't have the right answer but it the answers should be consistent with my understanding of it and it seems to be true right because now it has five two to five which we don't validate so that's why it thinks it's good so I think we're on the right path even if we didn't have the right answer right so that's good uh okay so then here we do some if statement so if x is equal to zero and length of X is equal to one then we continue that means that we have a leading zero so now it if length is greater than one right because we have a leading zero oh uh I think I said zero and then I confused it um yeah right because we have a leading zero um I think one thing I have to check is also if index plus L is I we also can well we break in this case I suppose and also in this case we break because it doesn't matter this will this won't change and this will get bigger so we can break um and then the other thing is if uh int of X is between 0 and 255 then we do this is I kind of vote in a yucky way but you know the idea is still kind of the same we kind of used to always operator we want but um so this looks good it's possible that we missed some edge cases but on these things uh I am going to be a little bit lazy so yeah and I think one more case that we can do though that's a little thing is just like a lot of ones I think but not full just enough that it gives maybe a big answer yeah just I mean this isn't even that big and then maybe one impossible case uh still getting used to the GUI a little bit just to make sure that I return nothing correctly because that's not in one of the inputs okay so that looks good let's give it a submit um yeah we kind of already talked about complexities I'm not going to dwell on it that much but this is going to be at worst let's just say 19 choose to three or and choose three if you want to say that which is n Cube or a Big O notation um where n is at most 20. um but that's given these constraints and of course you can probably narrow it down more if you're really smart about it but I don't know I think that's good enough for me so yeah um cool that's pretty much all I have for this one so let me know what you think let me know if you've done this part with me if you did this plan with me and you stayed to this end of this video uh give a comment below I'll give you my props ring for my good glasses so yeah anyway that's what I have so stay good stay healthy to good mental health I'll see y'all later and take care bye
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
235
hey what's up guys Nick white here I detect coding stuff on twitch and YouTube check the description you can see all my information where to follow me where to do whatever you know explaining all these problems on lee code hacker inc these platforms because people have a tough time understanding the code so i'm here to explain it to you this is a tree problem called lowest common ancestor in a binary search tree problem 235 easy problem if you don't know what a binary search tree is or if you don't know what a tree is a bunch of nodes a binary search tree is a tree where each node can have 0 1 or 2 children right binary is the base to number system so you can have up to 2 children you can see that 6 has 2 children a left and a right 2 and 8 and then you know 0 has no children right a tree node has a value it has a left and a right child if the if it has if the tree node has no children then the left and right will just be set to null ok very straightforward so what's the problem well we've actually done this problem before lowest common ancestor binary search tree we did it on hacker rank so it was exact same thing right here giving a binary search tree find the lowest common ancestor to given nodes in a binary search tree thank you for following and subscribing so we just want to find the lowest common ancestor of two nodes so we get two nodes and we get the root of a tree so this is the root of a tree and we can traverse this tree right with the root we can traverse it we have two notes what is the lowest common ancestor well basically it's the node that is the lowest ancestor of two nodes right so let's just look at these examples right it's the by definition it is the lowest common ancestor is defined to be is defined between two nodes P and Q is the lowest node and T that as both P and Q is descendants whatever right giving it so here's the tree we have nodes 2 &amp; 8 right 2 &amp; 8 what is the lowest 2 &amp; 8 right 2 &amp; 8 what is the lowest 2 &amp; 8 right 2 &amp; 8 what is the lowest ancestor of 2 &amp; 8 well an ancestor is ancestor of 2 &amp; 8 well an ancestor is ancestor of 2 &amp; 8 well an ancestor is above it right you think of your ancestors right your grandma your grandpa ancestors they're above you right they were older so we'll the only one above two and a to six we want the lowest one so if there's a million of them above two and eight six is the closest so we want six two and four is another example right the answer is two in this case because a descendant the ancestor could be itself they're allowing that in this case so if you read this description right it's gonna say two and fours two since a node can be a descendant of itself I don't really that's weird but it's fine you know I'm not a descendant of myself am i no okay anyway right if we're thinking of just a couple other ones right so let's look at a more advanced one three and seven right lowest common one between three and seven well you gotta think you know all the way up to six I'm pretty sure right because you know boom alright let's think about three and five is four right three and zero is 2 right because 4 isn't an ancestor of two so yeah I don't know just look through a bunch of these examples right okay let's do the problem now it's a recursive problem it's pretty simple the intuition here is basically of the root and you have these values right so if you're getting 2 &amp; 4 we're starting at 6 well getting 2 &amp; 4 we're starting at 6 well getting 2 &amp; 4 we're starting at 6 well we have to at least find where these nodes are so that we can find the ancestor so we have to start traversing towards them so to traverse towards them in a binary search tree the little nodes that are less or on the left side the nodes that are great around on the right side so what we're gonna do is just okay if key Val is less than root Val and Q dot Val is less than root dot Val we're gonna traverse down the left side so this is gonna be a recursive call to the left node so we're gonna return the method lowest common ancestor on route dot left the left side because it's on the less than left side and we're gonna do just P and Q again we're just traversing down the left side this is the same thing now on the right side all right so the values are greater we're gonna look on the right side traverse towards them and easy simple problem as simple as it gets you just return the roof so basically what happens is okay think about it to 1/8 is an example if one is on the to 1/8 is an example if one is on the to 1/8 is an example if one is on the left and one is on the right that means that the parent is in between them so if both of them aren't on the left side and both of them aren't on the right side if both aren't greater or less than the value you're currently looking at that is the ancestor that's the lowest common ancestor so you return it so neither of these will get hit if you go to and 8 6 is the root mm-hmm both of them aren't is the root mm-hmm both of them aren't is the root mm-hmm both of them aren't on the left both of them aren't on the right so it's obviously that's the ancestor you return it otherwise you traverse towards it so like in 2 &amp; 4 traverse towards it so like in 2 &amp; 4 traverse towards it so like in 2 &amp; 4 you're looking for 2 &amp; 4 both of them you're looking for 2 &amp; 4 both of them you're looking for 2 &amp; 4 both of them are on the left see you traverse and you hit - okay now see you traverse and you hit - okay now see you traverse and you hit - okay now are both of them on the left or both of them on the right no so you return route 2 boom it's easy it works for any single finger 7 &amp; 9 finger 7 &amp; 9 finger 7 &amp; 9 okay 7 &amp; 9 both of them are on the right okay 7 &amp; 9 both of them are on the right okay 7 &amp; 9 both of them are on the right hits this condition you look you hit 8 so you're at 6 then you both are on the right you hit 8 look again up these don't get hit cuz the ones on the left ones on the right you return route boom 8 is then a common ancestor looking for any of them 0 &amp; 3 both are on the left you go to 2 0 &amp; 3 both are on the left you go to 2 0 &amp; 3 both are on the left you go to 2 that's it but not one both of them are in the left both on the right so you return - okay all you can do all as many return - okay all you can do all as many return - okay all you can do all as many cases you want that's a very simple problem that's pretty much it for this video let me know if you have any questions about trees or whatever but pretty straightforward maybe I definitely was a lot smarter in this video I was really trying really hard to study so maybe I do a better job explaining if you're having a tough time this is the exact same question with the same parameters and everything function just on Hacker rank so check this out if you want more clarification I go into more detail there so thanks for watching for this video like it subscribe so I can grow on Channel very straightforward solution and yeah that's it see you in the next video peace
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8 **Output:** 6 **Explanation:** The LCA of nodes 2 and 8 is 6. **Example 2:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4 **Output:** 2 **Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[2,1\], p = 2, q = 1 **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the BST.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
236,1190,1780,1790,1816
39
hey everyone this is site so let's start with the question so the question is combination sum so you have given an array of distinct integer candidates and a target integer target you have to return a list of all unique combination of the candidates where the chosen number sums to target okay so your unique combination sum will be equal to target you may return the combination in any order okay this the same number may be choose from the candidate and unlimited number of times so you can choose the same number as unlimited times as you want and two combinations are unique if the frequency of at least one of the chosen number is different so let's say you have a unique combination one so you can't choose again a subset as one okay and it is guaranteed that the number of unique combination that sum up to target is less than 50. okay so let's see with an example okay so we have given this candidate array and we have given this target sum so what we need to give is find the basically sub array which will be equal to the target and you can make any combination as you want so you can take the two as many time as you want you can take three as many times as you want so let's see we have this two three six seven and we have a target of seven okay so as you can see if we use 2 times 2 and 3 and if we calculate the sum for this it's basically 2 plus 3 is equal to 7 so this is our target sum let's see any other combination can we use with three no i guess we are not anywhere six will also not have any other seven we can use only the single element also so as you can see seven will become this target okay so we have two subs uh to subset or a sub array so you have to make the combination like this and we have to give all the combination that you make okay so let's see how we can approach this question so if you can clearly see we need the combination or the element that is less than or equal to target okay so that means we have two option either we can take the element let's say we have two option this is yes either the current element is less than equal to target then we'll consider it and either we will just skip that element okay because if that element let's say is 8 and the target is 7 so that doesn't means doesn't make a sense to take this element so we just skip that element okay so let's say the function is like something solve this array uh let's take a starting pointer as i and this is our target so what we will do in this skip case basically we will do solve array and we just increment the pointer okay and we will not decrease our target also this skip is pretty clear for the current what we have also option like we can take the same element as many as time as we want so what we will do for here so we will do solve array we will not increase our pointer because we can take the same element as it is and we will reduce our target the target will now become array of i okay so in this way we can easily solve and get a subset and what will be our base case like where we have to written so if your target is equal to zero then we what we will do we will add this basically you will take a list also which will be you taking the current element always so add it to that list this current and you will basically add to your final list okay final dot add disk list and the one more base condition is if your target is basically less than zero basically you didn't get that subject and your target is now in negative so you don't want to continue just written from here so let's see this approach with an example okay so now let's see the example of the previous approach that we discussed so let's take one sub list also side by side which will store the subset or the combination which is giving the target as some okay so we have two option either we will basically we will start from here from our current and we have two options either we will take it or either we will not take it so let's say we take it okay so we take it what we will do we will add this into our sub list also so sub list is now become two and this will be and we are not whenever we take we no don't increase our counter so basically so pointer will remain point two only and our target reduce to seven minus two which will become five so it will point it here only and let's say we don't take it so this will become 3 6 7 and target is seven okay so let's solve first this part okay let's solve first this recursion call so here again we have two option either we will take it and either we will not take it so if we take it we will add it into sublist also so it will become something like this 2 comma 2 and this will point again to 2 only and it is that here and your target is now reduced so it will become three and your if we don't consider it will become something like two this will become three six seven and target is remain as it is as five okay so let's solve first this part so for this we again take it will become 2 so it will become 2 to 2 and it will please remain pointing to 2 only and your target is now 1 it is pointing at here only and this will become now 2 we will not consider it so it will become 3 6 7 and a target of 3 let's solve this only so we will consider this it will become 2 and this will become i'm pointing at only 2 3 6 7 and our now target will become 1 minus 2 it will become minus 1 and let's say we will not consider it so it will become something like 2 and your pointer will become two seven and target is one okay so if we call again so we will check our base condition is target is now negative so we will not go for this we will return from this call okay so we will come back at this point okay let's solve the right part so for this if we go if we take it so it will become two three and it target will become one minus three and it will be minus two so similarly target is also negative and for all the case it will always be negative so we will return out from this call also okay so from here we are getting a empty like no set so it just returned from here also from here we are not getting any uh list or subsets now in this case let's see let's change the color it will be more clear to you so we are at here okay so we have again two option either we will take it or either we will not take it let's stay let's say we will take it so it will become 2 3 and your becomes 6 comma 7 so and your target is now 0 and let's say we will not take it so it will become 2 and it will become 6 7 and your target is 3 okay so we will call again so for this case you can see this is your base case so what we will do we will take one result list also because this in this case we are getting a target as zero so it will become so we will add it into our final list also that will add it like 2 comma 2. okay so we will return from this call and let's say we will go for this call so if we make the combination you can say 2 plus 2 is 4 and if we make any other combination it will be greater than our target so 4 plus 6 is 10 and 4 plus 7 is also 11 so let's say the call will not give any uh sub list so we will return from here also okay so from this call we written okay so now let's solve this call so two comma three six seven okay so as you can similarly see we will go deep down and we'll create all the sub array okay so similarly we will go for this array also we'll get this array also and from this we'll get one seven sub array and which we will add it into our result so this will be our final result okay now let's calculate the time complexity for this okay so before calculating the time complexity let's write the code so it will be clear for you after this so let's write a code so what we need a list of list integer let's name it as list equal to new arraylist okay and what we will do we will create one sub list also which will pass in the function new array list okay then what we will do we will call our function and we will pass solve this candidate array and your current pointer which will start from zero and what we will also pass is let's first okay we will pass target and our sub list okay so let's write code for this like directly it's all we will pass the array let's give it a small name this will be our start this will be our target and this is our list sub list basically okay the first step is basically we need to iterate over all the elements so what we will do take a look or end i which will start from start basically and it will go till nums dot length and i plus so what we will do either we will consider this or either we will not consider this okay so let's say we will consider this okay so what we will do we will add this element into our sub list and we will add the current element nums dot i and we will call our recursion basically solve nums and we will not increase our pointer we will pass it as same and we will decrease our target by nums i and we will pass our sub list okay so this is for left side but for right side we are not considering this target that means we have to remove this okay so we will remove publish dot remove comes and we will make or let's remove it like this remove the last element sub list dot size minus one okay so it will remove the last element because in the list this will be element is added in the last only okay there is one case which we have to handle also let's say if your nums i is greater than your target so that pretty clear we will not consider it so we will just do continue basically we are skipping this element okay let's write the base case also the first base case is if your target is less than zero so we just written because we don't want the negative combination and if your target equal to zero what we will do we will first add it to our final list basically list dot add new array list we will add this sub list inside this and we just written after this okay so this function i guess it's complete and after this like combination sum you're calling solve so we need to return list also okay let's run the code so this is accepted let's submit this as you can see this is submitted okay let's uh calculate the time complexity for this okay so first uh basically as you can see at this point what we are doing is basically taking the sub list and adding it to a list so let's consider the sub list size as m so th the adding the all element to a new list it will cause us order of m and for this if you can see what we so if you see what we are doing is basically creating all the you can see the combination so let's say if you have four position so what you are doing either you will take it or either you will skip it either you will take it either you skip it but in let's say if you have only either take it or skip it then you have only two options so it will be two so it will become something like two hours let's take a k okay but in this question it's already mentioned like you can take the same element as it is as you want so as you can see we are taking the same two at here also so what we have an option let's take an example so if i have a 10 and array as one so what i will do 10 basically it will become 9 then it will become 8 it will become 7 so what i am doing is i am taking it as twice to the target because i can take the same element as many years time as you want so this will be the time complexity for generating all the subsequence and the final will be order of 2 to the power target into m for adding all the sub list to a list and space will be you can consider a sub list size so this will be your space complexity hope you like my video thank you for watching this
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
787
Hello friends today I'm going to solve liquid problem number 787 cheapest flights within case tops so in this problem we are given an error flights where um flight at index I represents the value um which is also an array um which has three elements the first one is the value from where we are traveling the second is the destination and the third is the ply price that we that it takes to travel from this uh this city to this city now that we know that about the array there are also three integer values given to us the source the destination and the integer key and we need to find the cheapest price from source to destination and that price should be such that we only have to travel K stops in between the source and extension maximum of K stops if we could not find any such value we are going to return a minus 1 value now let's see how we could solve this problem so this problem could be solved in two ways uh DFS and BFS let me first explain you the depth first search approach so in the depth first search what do we do well basically we start from the root node and the root node here will be the source node so we start from our root node and we Traverse along its depth so we start from zero we go to one now one has two children two and three uh let's move towards two since two e's of uh Less in value right then three so we go towards two now what's the value of 1 here uh value of K is equals to one right so we moved from zero to one um the value of K becomes equals to zero now because we have already um okay let's say that is it this way the value of k um from 0 to 1 we moved right and from one to two we moved and now we know that we have already traversed one stop and the value of K is also equals to 1 and our destination is not equals to the destination that we want right we have only reached three we have two we have not reached 3 we need to reach 3 I only one stop right only one hop so what we do is we uh backtrack and then we go to the next child of one which is now equals to a destination that we want to go and here in this case uh we found our destination within k equals to one stop right so this will be our answer now that is the overall idea behind this but let me just tell you one thing here so what if from zero we have one more node suppose that's node four and from 4 we can reach node um we can reach node 3 as well and that takes us only 500 uh the cost is 500 from 4 to 3 and from 0 to 4 it's 100 all right so now since we have the number of nodes the number of cities is equals to 5 here um so we start from zero we go towards 100 and then we go towards two same as before but now we know 2 is not equals to our destination and we already have uh One Stop uh so what we do is we backtrack so we go back to one we go to the next node which is equals to three now if you just look at this case we have found our destination within the value of k equals to 1 right by which has only one stop so we found our destination what's the cost here it's 100 plus 600 which is equals to 700 but is this the minimum price to reach our destination well if you just look at this node 0 to 4 and 4 to 3 it's 100 plus 500 so that would be 600 right so we have not yet actually raised uh so this is not our answer we our answer would be 0 to 4 to 3 which is six hundred so now how do we do that let's look at in another way so we are going to use DFS but we are going to use 8 from bottom up approach so far I was showing you top down approach that is we start from our node and then we go we Traverse until we find our destination but now we are going to start from our destination that is the bottom most node and then we move upwards so now let's see look at this problem here so what we do is we start from our destination and the price to reach destination from the destination itself is equals to zero right so what we do is we return 0 to all of the nodes that is Con that are from where we could reach this node so we return a 0 here and the price to reach 3 from 1 is equals to the price 600 plus zero so that would be 600 itself similarly for this node 2 it would be 200 because 200 plus 0 is 200 and for this node 4 it would be 0 plus 500 which is equals to 500 now so far we have these values right now what we do is um from each of these nodes now we do the same thing so we start from Node 1 and then um we go back okay we start from let's look at node two here so we start from node two and the value here is equals to 200 right that is the least price to reach 3 from uh node two now what's the price to reach node 3 from node one what's the least price where the least price would be equals to 100 um if we return a 200 here then the price is 600 uh price would be 300 right via node two wire node two but in this case the value of K would be equals to zero um so we do not consider this thing here and our values is still equals to 600. because we do not want any extra notes in between then and so what we do is now we return the value 600 here so now the minimum price to reach node 3 from 0 is what 600 plus 100 right because we return the value 600 so that would be 700. so now so far we have found the value equals to 700 from via node one right next let's look at this node so to reach 3 from 4 it cost 500 right now to reach um we backtrack and to reach 3 wire 4 is equals to 500 plus 100 which is equals to 600 and now we have two values right one is 601 is 700 and we pick the minimum so we pick this value now zero has two children right one and four let's just move to uh child one first so when we move it to this child What's the total cost to reach Node 1 from 0 it's 100 right it's on right so the cost is equals to 100 here pan what do we do is we next move to its next child which is equals to 4 and the cost is still 100. so we have found the cost of all of its children now uh we uh do the same thing for its children so from one what we do is we move to its child so it's next child is two so the cost to reach 2 from this node is equals to 100 plus a hundred which equals which is equals to 200 here and the cost to reach it's another child three is equals to 100 plus 600 which is equals to 700 right so far we have found its cost now what about this from node four um the cost to reach uh this node is equals to 100 plus the price that is 400 which is equals to 600 right so we got this to price and so far we are satisfying the value for K that is the number of stops should be equals to one and so far that is being satisfied now between these two values which is the minimum value since we had the value 700 and our current value 600 is less than 700 right it's less than 700 so what do we do is we reject the previous value and we keep the current value now from node 2 we move towards this node again here and then what we find here is um the number of stops equals to two so we do not actually choose this path now let's just suppose we have one more node here just to give you an example of the number of uh like base cases that we need to consider and suppose this has a value of 200 and a 700 all right so uh so in this case we will first what do we do is we know that um the price to reach 5 is 200. now from 5 to reach the destination which is node 3 is equals to 200 plus 700 right but we know that um this value 200 plus 7 and we already have a price that is less than this price 200 plus 700 so we are not going to choose this path right we are not going to uh even choose this part because we need the path with the minimum price and we already have found the path with the minimum price which is equals to 600 so we are not going to compute this at all um so um that is when we have found our uh solution the result so things that we need to consider is um the value of K should be greater than minus one if it is -1 then we are going to return if it is -1 then we are going to return if it is -1 then we are going to return back and also we need the minimum value at that node right we need to find the minimum price to reach a given node so we are going to keep track of the previous values that we have found so uh so we are going to use a memory to keep that value so that we can compare and then also again if we already have reached that node with the least price that we are not going to compute it again right so we are also going to uh use that condition so now let's start coding using our DFS search so what do we need before performing any execution we actually need to create the graph that is to create an adjacent symmetric so let adjacency Matrix equals to new array it would be of length and that is the number of cities and then for each of the city it will have the number of flights running from that City to another city right so um okay let's just do it this way it's actually the flights so the flight what's the value of flight it has from two from uh from Two and the price right so from to price from so we are okay push the value 2 and the price to reach that value all right now that we have our adjacency metrics let's create our memory to store the values that we have already reached and let's fill it with an Infinity value now let's create our BFS function for our BFS function what do we need a queue right so initially RQ we will push the value Source start from our source and that from that's wild so this is to keep track of that is we are only traversing over the children walls and now we are going to Traverse over each of its child okay traversing over each of its neck bar with and the price of from the adjacency list and then we check if the uh distance from Naper that we have found is already less than the price to reach that node from this Source node um that is Price Plus okay price plus the cost of this node then we are not going to compute because we already have found the least valued to reach that distance to reach that city right so we are going to continue else what we do is we push to our cue so we push our navel neighbor and the cost of that total cost to reach that neighbor also we are going to set the value of our neighbor as the new price because that is the least price that we have found so I don't reuse this value here rather than Computing it again and finally we return the value to reach our destination
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
297
hey guys let's tap number 2 9 7 serialize and deserialize binary tree I'll skip the explanation is very simple just like we get a binary tree like this 1 2 3 4 5 we will see realize it - 1 2 3 4 5 we will see realize it - 1 2 3 4 5 we will see realize it - 1 2 3 new one two or four five and any in Reverse way you forget a strain like this we have to reconstruct the binary tree like this so okay let's do it so I think we have to remember that I think I'm not sure whether it is right or wrong but if we do DFS for binary tree it should be yeah a stack but if you should a BFS DFS a stack but BFS is cute okay so for this case obviously we're getting a BFS iteration so we're going to first do this is civilization by using a queue like we stack every we stack all the nose of same level and we trust them one by one okay for one node we were pushing to the left nodes and the right node and if it is but for now or we will suppose all we well because we don't because for this kind of outcome not for trees that are not complete we cannot decide whether four or five where it is we have to append the new one or like this two three as a placeholder okay so with first-week use a empty use array so with first-week use a empty use array so with first-week use a empty use array result array to store to sort the temporary result and at last we will join the resulting to a string if I strange fie the result okay so we use a queue and we'll push the root in it okay so yeah the roots may be what but it doesn't matter okay so we will say while the queue is not empty what we're gonna do yeah we're first we get the no doubt we get Q shift okay so we have to decide whether we have to check if whether notice new or not if it is null then we resolve just to push nor and it's done and if it is not we should result push node valve and then we need to push the queue to push result left cube urge result right so if it's a leaf node both of them are newer so we have a new war double new one so these will finish others the tree traversal and at the end we were just we return Jason strange if I result yeah now the serialization is done now we try this t serialization our result is a little different from about that we have maybe in a so not totally the same as it is not totally the same as the that each codes because we have an extra new at the end for one two three four five we have one two three one two or four five nooooo so we have to trim the last Lewis right okay so how can we do that so Wow oh so Wow we just pop it okay because buddy is cute I mean JavaScript that I think it's no problem so Wow let's I equals Q length minus 1 Wow q why not it's result not Q Wow result is Z equals 2 nor I - equals 1 so and then we well 2 nor I - equals 1 so and then we well 2 nor I - equals 1 so and then we well Q slice so we get splice I will stop add to the first element that is not new or so who was splice I plus 1 it's not Q result ok let's write I think so it's now to civilization first thing we said we get the data as string so we need to make it Khan sir if data we return more okay and then array equals JSON string a parse data and if this data is empty if it is empty or the first one is new we return new one yeah and so if there is a root we can do reconstruction we will also use this Q so this Q we will wait a minute will create a root node a new tree node ar0 cost you equals good Wow why were using a queue because for every time we get for every time we need to know where the parent nodes are like our first wish over handle these kind of nodes and then we handle these nodes eat without this queue we don't know we cannot go back yeah that's why when we are using queue we're handling with a breadth-first search handling with a breadth-first search handling with a breadth-first search well okay wow there's two elements in the queue we guessed getting load out so for each node we get the node we get a left a note and the right node for light per 1 we get 2 3 4 2 we get 2 new right so we get constant left value left a vow is array shift costs a right value shift if left value we only push we here we need to do something if the value are newel we just ignore them right so when the left of value but the new is already as default value so we don't need to handle it so if it is not new we will create the NEFT call new a new tree node left val and set it to the node left and if right now is not new we will do the same cost right equals new tree node all right Wow no the right equals right okay so but for this when we are creating a new node like creating this 2 4 1 2 3 4 1 that means okay these levels the nodes in this levels are down processed we will process the next level so we need to also queuing them mix flourish node left push the right in case for that too there are double Newell we don't need to push anything because for that case the two is dead like any the branches are from - like any the branches are from - like any the branches are from - these are already processed so it's this skin like ok we first got the one okay two three so we put push two three and then we get to Newell's but we pop - so we'll copy three four but we pop - so we'll copy three four but we pop - so we'll copy three four five yeah right it's done so the Rudy's done so we return roots I hope this won't pass and maybe there are some error oh yeah it's always ever it doesn't matter what no result push note Wow it says Wow I won't define new Oh is on define node is undefined how could we this be undefined mm-hmm it's strange console note it's mm-hmm it's strange console note it's mm-hmm it's strange console note it's strange does this mean what of them define only fine the next one is undefined ah decent Hut result it's your Vinod I'm sorry yeah our he's not defined so I'm a little overexcited and as a our hahaha it's shift not time limit exceeded what it shouldn't be like this that's add some lock Wow it's not q+ and here it should be Wow it's not q+ and here it should be Wow it's not q+ and here it should be Wow a Arden is there my bad oh here's an error so we get this one so we output this one but we got extra undefined no why what is this is undefined okay first council law deserialize i still de serie dice one two three new duel four or five hmm but gets the right one and shift the push no push note left this is should not be the access but maybe shift my bad accepted okay we will remove this console.log and submit remove this console.log and submit remove this console.log and submit wrong answer one two on so long the data and the Wow ar aha this problem that we Ahmet omitted emitted the last news so we may be that be there may be undefined so and we just to check more or on the fine still wrong answer ah God zero is not Sheila oh and left Wow should not be on defying submit right this I think I cannot I write it once and bug-free it's cannot I write it once and bug-free it's cannot I write it once and bug-free it's too difficult okay it's accepted and around faster than 87% hmm kind of good let's take than 87% hmm kind of good let's take than 87% hmm kind of good let's take like at this solution depth-first search like at this solution depth-first search like at this solution depth-first search TFS we should the civilization of binary trees sensuality until this value is more important and more importantly instructor EFS pre-order trans pre-order instructor EFS pre-order trans pre-order instructor EFS pre-order trans pre-order trial transversal trap try transfers transpersonal easy right or it should be Travis all transversal Travis old Travis or Traverse Oh Travis I always say Travis Oh bed one two three no new for no five no yeah one can travel attempt each the backpacks and it is well known that we have two general strategies to do breadth first search depth-first search the DFS track can be further distinguished as pre-order in-order and distinguished as pre-order in-order and distinguished as pre-order in-order and post-order yeah I reared with this in post-order yeah I reared with this in post-order yeah I reared with this in these tax however TF strategy is more adapted for our needs since then the link jimana adjacent notes is naturally encoded in order which is rather helpful for the letter of task of deserialization oh they chose the DFS I choose - I choose the DFS choose - I choose the DFS choose - I choose the DFS therefore miss the algorithms for so here's the definition of tree note a priority DFS trap Travis transversal mm-hmm travis white transversal mm-hmm travis white transversal mm-hmm travis white trousers transversal traverse try there's actually Travis all right Travis poppers I think I always think these Travers I'm right okay the priority for straps father's recursively in order to route left subtree right subtree example this arrest upon re-entry my territory this arrest upon re-entry my territory this arrest upon re-entry my territory want to yeah i think series asian is very simple super nice routes else yeah simple now it's this eraser as a string constructed it's along the string it he starts the code body and then caused itself to construct itself and try to the child loads so it's another way of writing it in a recursion this relies linked list this arrest data weaker so we did dirt if it's nor we move in left-right which i wrote it's very left-right which i wrote it's very left-right which i wrote it's very simple time complexity both surprises disarray function o n space Oh ed both suresh among should we keep the entire tree either at the beginning or at the end so evolution with BFS deep strategy normally will have the same time of space complexity and as was implemented both Evy which means n times V where these decides the value which is called natural civilization and we come from Berlin here physically for values can't be optimized first but there's a way to reduce part which is encoding of a tree structure number of unique binary tree structure can be constructed using EndNote CNN Racine is Catalan number please refer to the ad code for more information they are CN possible structure configuration for binary tree with n nodes so the largest index value that we might need store is this means story an index value could require up I don't know what they are saying okay we write this in queue but let's say we would try to use binary bcurtin let's do it again in a recursion recurse recursive way okay hmm okay cost walk I just used a walk right if node equals no then we say result push nor write else so walk you know the left walk okay and then we read the we strange by the result and when materialized data will also well say oh I will save this part is that is the same and cost work that's what we got just build or how can I say build your index okay they start cost roots equals build zero start so start nodes should be because we use what this order is a pre-order in-order what this order is a pre-order in-order what this order is a pre-order in-order write this in order so it should be 1 2 1 3 4 1 this so tribute will create the first node cost no equals new tree node start it means they are start this is the first node right note left equals build start plus one oh this is not right so when I build from here say this is node okay it started one next one is 2 because it should be good to the left load so it's 2 and then do all right so we have to check the next one if a our start next one and we're eternal it is equal to new bill you do noose Lisa starred maybe we just nutri cost item equals a hour shift I used to use this item if r0 is more we don't care about it so actually it is more and we will check the game for the next one so if it is not new it's like three they will bury the game right yeah so note left equals field no we can't just build yeah if item is law we return nor know the right cause view we turn no I'm not sure with it seems that is working that it's not working we console first we did it so to see oh it's not sanctify ah God else if it's not new results.push node bow hmm it is no the impersonal just now we'll push node Wow and then we walk left all right one two forgot what probably left is the kind of really part left on or good note I have to return God accept it so the recursion to take care that the first week at we got a complete a binary tree format it's one to like one to new hundred three four new 205 renewal so every time we build we get the first animal it is new then it's done if it is not then we create a new low node and start building the left right because each branch will stop at the arc when the odd leaf nodes are built so just to build a safe faith safely and we just return but it's also very simple it's just fast I think they just isn't the same whoa it's it is a little faster mmm cool I need to ride this one more time yeah cool so that's all for this problem see you next time
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,2,3,null,null,4,5\] **Output:** \[1,2,3,null,null,4,5\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
271,449,652,765
328
this leaflet question is called odd-even this leaflet question is called odd-even this leaflet question is called odd-even linked list it says given a singly linked list group all odd notes together followed by the even notes please note here we are talking about the node number and not the value in the notes you should try to do it in place the program should run an O of one space complexity in old nodes time complexity so for example 1 we have the linked list 1 2 3 4 5 null and the output is 1 3 5 2 4 not because the odd nodes which are 1 3 &amp; 5 would come first followed by the 3 &amp; 5 would come first followed by the 3 &amp; 5 would come first followed by the even nodes and for example 2 we have the linked list 2 1 3 5 6 4 7 and the output is 2 3 6 7 1 5 4 because the odd nodes which are 2 3 6 &amp; 7 are in the front which are 2 3 6 &amp; 7 are in the front which are 2 3 6 &amp; 7 are in the front followed by the even nodes alright so for this question we want all odd nodes at the beginning and all even nodes at the end so to make it less confusing let's change this to this with all odd nodes in blue and all even nodes in red and let's go one step further and change this to this note that none of these changes are actually being made in the code I'm just changing the example to make it easier to understand the nodes values in the examples are numbers but that can be confusing because you might think that the number corresponds to whether it's even or odd so let's say this had the value of 2 and this had the value of 3 instead you might be tempted to think that this is an odd node and this is an even node based on their values but this is not based on the values of the nodes it's based on the positions of the nodes so starting from the beginning every other node is odd and the ones that remain are even alright so the way to solve this problem is to split up this one linked list into two linked lists the first link list will contain only the odd nodes and the second linked list will only contain the even nodes the way we're gonna do that is like this will reassign the odd nodes to only point to other odd nodes so here now you see a pointing to c and c pointing to e and you'll notice that the even nodes point to each other as well so B points to D to make it look better let's just put them closer to each other all right so now that we've put them closer to each other it should be more clear that we have two separate linked lists now all there's left to do is to reassign the last node in the first linked list to point to the first node in the second linked list now with that you have one continuous linked list let me just make it look a little better so this would be your final result with the odd nodes at the beginning in the even nodes at the end all right so the way we will do this is by using four different variables the first will call odd head this will be the head of the odd linked list and will never change the next will call even head this will be the head of the even linked list and will never change the next one will call odd this will start off at the head of the odd linked list but will be reassigned throughout to help us link all of the odd nodes together and the last will call even this will also be reassigned throughout in order to link all of the even nodes together and just decide no at the when we talk about a nodes next property it's just the next node that it's linked to so C's next property is d DS next property is e and E's next property is actually pointing to null so let's begin will reassign ods next property to whatever even's next property is that would look like this and after we do that will reassign odd to whatever odds next property is and after we do that we can do the same thing for even will reassign evens next property it's a point to odds next property and we're continuing to make progress so now a is pointing to see both of those are odd and B is pointing to D both of those are even now we just reassign even to whatever even this next property is and now let's just clean up the diagram to make it more obvious what's going on alright so a is pointing to C which is good because both of those are odd and B is pointing to D which is good because both of those are even but we still have C pointing to D which is bad because one is odd and one is even so once again we have to reassign odds next property to be whatever evens next property is and then we move odd up to whatever odds next property is this is good because we now have C pointing to E and both of those are odd and we'll do the same thing for even will reassign its next property to whatever odds next property is and then will reassign even to whatever evens next property is and I'm sure you can tell the progress we've made so far a is pointing to C which is pointing to null that's one linked list and then E is putting to D which is putting to null which is another linked list so let's clean that up a bit again alright so we're done reassigning odd and even and we know that when we get to the point where either even is null or even dot next is null so all there's left to do is to reassign odds next property to be the head of even and cleaned up that would look like this we have one continuous linked list with the odds at the beginning and the evens at the end alright let's get to the code what Lee code has given us is a function called odd-even list which accepts a called odd-even list which accepts a called odd-even list which accepts a parameter head and head is a representation of the linked list that we want to reorder in such a way where the odd nodes are at the beginning and the even nodes or at the end so the first thing we'll do is we'll say if head is null then we'll just return null because that means there's no linked list this time around I won't name the head of the odd linked list odd head because it already has a name which is head so just know that when you see head here it's the same thing as odd head in the previous section alright so head is naturally the head of the linked list we'll set odd equal to head we'll set even equal to head dot next and we'll set even head equal to even now we'll just need a loop so we'll say while even doesn't equal know and even dot next doesn't equal no ah dot next would be even dot next odd will be reassigned to odd dot next even dot next with 0.20 dot next and then dot next with 0.20 dot next and then dot next with 0.20 dot next and then even would be reassigned to even dot next that would look something like this Oh dot next is even dot next odd is reassigned even dot next is equal to odd dot next even is reassigned we'll do it again odd dot next is gonna be equal to even dot next odd is reassigned even dot next is going to be equal to odd dot next even is reassigned we're finished with that step since even is equal to null at this point the even and odd linked lists are completely separated now all there's left to do is to reassign odd dot next to even head in order to connect the two linked lists so we'll say odd dot next is equal to even head that'll look like this and we'll just return head all right let's run the code see how we did looks good let's submit all right so our code is faster than about 89% of JavaScript submissions and about 89% of JavaScript submissions and about 89% of JavaScript submissions and takes up less space than about a hundred percent of them as usual the code and written explanation are linked down below and if you're interested in other algorithm resources those are also linked down below see you next time
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
701
hey everybody this is larry this is day six of the october eco day challenge uh hit the like button the subscriber and join me on discord let me know what you think about today's problem insert into a binary search tree uh okay give it a treat does have to be balanced no it doesn't have to be balanced okay so that means that you could probably just do the textbook method of how they do it which is given a number go left if it's smaller go right if it's greater and because all the values are unique we don't have to worry about uh typefreaking so this should be pretty straightforward um so i'm gonna actually try to speedrun this a little bit uh let me know if you don't you know you have any questions about this in general but yeah let's just say well true for now um it couldn't know that value is greater than value then we want it to be the right but it's because to the right something like that i think should be good but uh but we have to take care of it let's just go to the next node and i wonder i mean i think maybe i could have done this a little bit queen i think maybe i could have done this also recursively but that's big that's okay and then at the very end and then so maybe i'll couldn't no it's not none no actually now we should return on this or break anyway and then just return the root note it should be pretty okay we'll see i have a typo somewhere let me finish copy pasting to test cases okay is this good enough i actually don't know so i think that looks good uh it there's no visualization here so uh let's submit it so i did not visualize that right they copy that right so this is the tree that i have did i just have to left and right uh mixed up i think that's the only thing that could be well oh that no that's the expected what do i put oh this is what i put yeah okay so this is definitely wrong because if the current note is oh yeah the value is rated it should be on the right whoops oops see the easy so even on the speed running you'll a mixture of mistakes and actually now it looks exactly the same uh the problem the reason why um yeah the annoying thing is that because there's uh multiple answers uh it wasn't guaranteed i wasn't right okay and i don't check for could let's run it for that one uh okay glad that didn't happen during a contest okay yeah so what is the complex of this algorithm uh well it's just going to be o h where h is the height of the tree which could be of n in the worst case um oh yeah and you don't have to care about that whether it's balanced so that's okay uh yeah um and you can really do faster than that because the tree they're giving you is not balanced right so it doesn't matter uh unless you want to balance the tree but yeah uh cool so this like i said this is pretty uh textbook problem uh let me know what you think uh hit the like button hit the subscribe button draw me to mine i will see y'all tomorrow bye
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
886
Hello gas welcome back to my channel need code challenge possible by partition so what to do in this question and there are some people who like someone like this okay so what you have to do is to separate those who dislike them into different groups We have to divide it into two groups and make two groups like this. Okay, so like this is one and two, so both of them dislike each other, so we have to make only two groups. Okay, so we took this group zero and took group van, this is the second group. Keep them in a group, okay, then let's do another three examples, then we will have to keep one more three in this group, okay, so if you are throwing them out in such a group, then return them, then how would we do if we return them? So how to do this, look at what we do, we make it forward between them, so we display van and tu, what does it mean that both those notes dislike each other, okay, why am I doing this? Now I will tell you, take the notes of the person who likes this, there is one ahead among them, now what will I do, okay now what I do is, I will take an agency list, we will have to make a graph of it and we will also have a handle with this zero. If we have to do it then we will not leave the one with zero. Okay then kill him with Neglect and we will start with main. If 12 and five agency list is being made then we will go to this. First, who is connected to the van? Your number four. What are you telling me? Who is your number? Four is only okay. 123 Now what will we do? Like what have we done? This is our list. Our list is taking the open sign and giving color to everyone. Mines van is okay. Now what will I do? Function I will call, okay who will do this function? Now what am I passing in it? I am passing four. Okay, so the source is done. Four, I can pass any source out of these five, so for now I have passed four. If I pass four then what will I do? Now I will give it a color. What is the meaning of everyone's color? Now I have given it a color. Van. Sorry. Van. Okay. Now give me all the numbers. What will I do? I will go to four in four. Okay, so all of them. What will the color go to zero this then I this which I always run like BF okay then I go to an element because then what I do is like U is the front and then what I do is I go to each and every layer of this. I am UK, okay, in this I will explore all the neighbors, okay, I will give them the color of this, my color of you, I will give it to them in the opposite color, okay, so what will happen with this, okay, then for the powder, which number will I give them. Which color will I give, if I have already given it a color, if its color is not minus one, then it is okay, if I will not color it, if I will explore the one whose color is minus one, okay, then what is its color, its opposite color? If it is zero then I will color it as van. Okay and I will push it. Why then what will I do? Okay, who is the woman's number? I have already given it a color so I will pop it too. Okay then I will go to five, we have given it and it has also been given color, van and three are its names, we have given color to all of them, so we will do this and will not do anything else, so if we can do it forever, then what will we return, okay And we will not always be able to reduce it and man lo if it is done in between the two then I will not be able to put both of them in one group then I will not be able to put both of them in the same group then it is okay then the same thing if I man lo in Make a catch between the two, okay, that means, what should I do, I will take one more thing from here, Van and you also dislike each other and I will not let it come between these two, then okay, what will I do now? I will do it, I can start it from anywhere, I started it from four, so I gave color to four, van is ok, it is ok because we pushed 4, its opposite, its color went to zero, and its color is minus. If it is a van then what to do with it, put it opposite its color minus its color, it is not van and its color is equal to this, its color is U of I, here we can solve this question, okay, if its code is found then see its The code is simple, what we have done is go to its neighbors. Now in the neighbors, we will check the condition that the color of the neighbor is the color of the member. If the color of the member is one then it is ok. If the color of you is not equal then what should you change its color. We will do its opposite and it will be color off UK, what does it mean? Hey madam, we will do it true, okay, this happens, so now you have solved it in this graph here and for this, but like this is not connected yet. 678 Like here, if we also have two more things, then we dislike them in six and seven, so we make them between six and seven, and if we dislike six and eight, then we make one in between 6 and 8. What have you done, you have called this function from here from this source, it is ok but what is our color now, is it mines van, the color of all these is still mines van, so the color, if theirs is mines van, then we will call this function from there. We will call check. Okay, we will call the check function. So I told you that you can take anything as the source. So, we took this source and solved it for the graph. 01, we got its color, now it's mines, what do we do from here. We will do whatever is here, we have made it here and if we get zero color here, then we will return zero because we cannot create a group. If this had happened here, we would not have been able to create a group for it. Subscribe So That's Question
Possible Bipartition
score-of-parentheses
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
String,Stack
Medium
null
141
141 link to list the cycle and it's an easy legal question so giving head ahead of a linked list to determine if the linked list has cycle in it there's a cycle in the linked list if their cell node in the list can be reached again by continuously following the next pointer initially pos is used to denote the index the node that tails next pointer is connected to note that pos is not passed as a parameter then return true if there's a cycle in the linked list otherwise return false and in this example they give you a linked list like this and the pos is connected to lesson one there's a cycle in the linked list of where tail connects to the list um the first node basically uh to here so there's a cycle in it so you want to return true in this case and then the next one is the pos is connected to the node 0 and you can see obviously there's a cycle in it so you want to return true right and the pos is -1 -1 does not right and the pos is -1 -1 does not right and the pos is -1 -1 does not exist and you want to return false in this case basically there's no cycle there's some constraints here and you can see that in the last six months still gonna ask that by a few different companies um on this question so um let's see how we can solve this uh question um there are two different ways that you can do it one is i'm gonna use our hash set so i'm gonna put f go through every single node right and put every single node into this hash set and if i see this when i'm going along this list to the end of the list if i'm putting i'm see a duplicate in the hash set in the data structure because hashset does not allow duplicate so in that case you will be able to detect that there's if you see the same number like two twice then you know there's a cycle in there um that's basically how you can do it and let me show you how to do that in code so you want to rule out batch cases if not had and that you want to return force basically empty of course it's false then there is no cycle in it and if um so i'm gonna do a hash uh high set and basically set up put um scene equals to set and then this is a set here i'm called this calling the set as seen so while had wall head existed right i'm gonna if head in scene if the head is already inside of the headset the node that i'm going through then you want to return true because there's a cycle in there and um otherwise i'm gonna add this uh hat into this set every four every single node that i visited i want to add it to the hash set so next time i know that i have visited just showing that i visited this uh node already and then i'm gonna continue head equals to head on next i'm gonna continue to go through the entire list a while ahead until the head does not exist anymore i'm gonna go through this right basically add every single one of them if i go through the entire list here i still don't find any um there's no duplicate there's nothing is duplicate and i get out of the list then i want to return false basically there's no cycle in there yep so this is the hashtag method and there's another algorithm it's basically florid's um algorithm where you can detect the cycle and you would not know how to do this unless you know this algorithm basically how you do is that you want to have a slow pointer and you want to have a faster pointer and a slow pointer move one faster point move too it's kind of similar to how you find the middle point of a linked list and when you go through when the slow and fast continue to move right slow and fast eventually it's going to be able to meet each other at some point they have to be able to meet if they are able to meet that means that there is a cycle in there if they are not able to meet then that means that there's simply no cycle because if there's no cycle in there when the fast the move to the end of the list because fast move two step and the slow move one step slow supposed to be in the when fast is at the end of the list of slow supposed to be in the middle of the list right so they will never be able to each other meet each other and the only situation there they are able to meet there's a cycle in there and i'll show you how to do this in code also and i keep this part because the edge cases is the same so i'm gonna put slow and fast i'm gonna set two pointer and both of them start from the uh head node and i'm gonna say wow fast it's kind of same code as um find at the half of the linked list and while fast and fast on next what i'm gonna do is i'm gonna move slow to slow down next so basically slow moves one and i'm gonna move faster too and a faster too faster down next the next that's what i meant when you move slow they all at the beginning of the list at three right and when you move slow to two and a fast is already moved to zero if that makes sense so you just move one and you just move two and then the next step to the slow will move to zero and then the fast will move from zero a zero to minus four and then go back to two right and then the next time slow will move to zero minus four and then the faster will move two step one two so slower and faster we'll meet at -4 here slower and faster we'll meet at -4 here slower and faster we'll meet at -4 here so then if slow is equal to fast at some point then i'm gonna return true in this case because i while i go through this list right they are able to meet each other like i mentioned that means there's a cycle in there i want to return true otherwise if i'm not able to find anything at all while i go get out of the while loop i'm still not able to find anything i'm going to return false in this case so that's how you find the uh that's how you detect the cycle for this um uh you by using the slow and a faster pointer and let's see yep so if you think that this is helpful please like my video give me a thumbs up and subscribe to my channel and i will see you soon with more legal questions okay bye
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
967
Hello hello guys welcome back to my channel thank you got introduced to challenge what is the difference of the same digit from the phone number Rashmi Karne meeting you girl has to be edited in such a way that what is the difference of the same digit from the number and which get even digit. That's K Okay like what's in it in this inko 191 So how much difference is there in this and in this Samsung is the difference in this How much difference is there in voice MS Word printer 292 Look at them zoom-in How much 292 Look at them zoom-in How much 292 Look at them zoom-in How much difference is there in these The kind of difference is meeting is so and How many lenses have to be returned, whether they are N, they should be of Indian gold, okay, all these links are there and when they are of MP3 DJ, then they have to be returned by you and one short answer is that the leading should be Shyam, okay, so how to do it is very simple. What will we do, we can't start from zero and subscribe 1234 till here, okay, so what will we do, we will put them in why, okay, like this, we will do 123 456 no from, Jatin, okay, so we will check that we Kepler can three thirds, okay, so hands-free, that means four, okay, so hands-free, that means four, you can put the forum, okay, and we will check one more. 51 - Can't put 51 - Can't put 51 - Can't put because that makes this example 2538, so this is eight no difference and we can do 542. It means that we can put five plus, we can also put five plus, so we will check that this is our last digit, it is okay and we can put plus in it is okay, plus that. If ours were, we can press the lens icon, okay - were, we can press the lens icon, okay - were, we can press the lens icon, okay - camera - we can enter 10, this will tell the camera - we can enter 10, this will tell the camera - we can enter 10, this will tell the last digit of the village, how much difference was there in this case, okay, in this case, if it was Taliban, then we can fuel, okay, A Param OnePlus 3T can do it, okay, then we will put it like we have topped it is okay, element for it, take it, drink it, why note friend that now we will reduce the speed, we will take out the last digit, how do we take out the politics, drink that all this is okay Then what will we do that we will check that this Lucy 208 A tier of R Plus has threatened and asked that we will make Shami's flower, we will take this piece, now it was our element, we will entertain him, okay * we will do it plus okay * we will do it plus okay * we will do it plus today we will do it for you Daal denge ok hai will be discarded and this is our R - K ki and this is our R - K ki and this is our R - K ki ne 400 what will you ask and Pintu 04 - K ok hai ke will be 04 - K ok hai ke will be 04 - K ok hai ke will be used mara ok so same now example neither have we gone on tour in this Na what will you do, how will we travel, our tuberous guest will ask 525, this mind will post three layers of input, three plus 36 and three MP3 - ॰ Okay now, so MP3 - ॰ Okay now, so MP3 - ॰ Okay now, so he will ask and still do something, okay then phase's This is all right, we will kill all these in one line, okay, and here how much implementation was there, how much was one, here the end deposit will go, then assume that we have removed even the nikalti or paragraph has been removed, so what will we do with all these elements. Okay, send a level, then we will keep pushing them, it's okay to do the same thing, now it's good bye, Modi ji's cord is also his, so we spoiled it, like why did we take one in it, from our mind till 9? Pushed all these movies, turn off the level, then we will try all of them together in that level with the shoe element, okay, like how many limits have I set on this channel, which we will process on this channel, hmm, okay and like We are ok donkey, so fold the last digit of the shooting like this and subscribe. If you subscribe number - 3, now you can also add this, subscribe number - 3, now you can also add this, subscribe number - 3, now you can also add this, then we will add both of these. 147 148 ok, okay and this is equal to our ghagra, now we will braid it. Then what will we do so that why should the element be ours that it will pop all of them and give the answer rich and okay and in one more thing, as if it is a well, this is 10, and from both plus and -, we this is 10, and from both plus and -, we this is 10, and from both plus and -, we understand that we want to do something. Like if we turn off the oven, which stops human life, then the forest will be back, then we will fold it, or do something with the help of detergent, okay, then this message is just It is not a big deal and the legs will be used, then what should we do, like on this channel, we neither, therefore, consider it to be our year, in this case, this one, he caressed both of them. Okay, so there is death here, so next time how many will we take, nine to two will wash. Elements are ok, then next to that, we will give nine two * 2, ok next to that, we will give nine two * 2, ok next to that, we will give nine two * 2, ok and on how many it will go, it is ours that no * * like two has become pure, no * key has that no * * like two has become pure, no * key has that no * * like two has become pure, no * key has become part that it will go here because favorite is good, okay because How much Madhu Kitna should be kept in our festive maxi? Today, during the new moon, the time complexity will go away. 99219 Bluetooth is an important part of doing this because it is outside, okay, if the note is handed over, then one plus two and Stuart give their suggestions, okay, then what would this be? That is, if you turn it on then it comes, it is ok, then it will pass us, ok, no, the notification of entertainment is very less, ok, so that is the question, it is equipped with the 10th house, ok, no, it improves only and only. Question and Space Complexity: We need our Question and Space Complexity: We need our Question and Space Complexity: We need our Space Complexity, which is our level of 11. Maximum marks are being taken from this. How innocent and intuitive our people are, then this is Space Complexity. In this case, it will go spongy. Time Complexity will increase. Okay. Ok morning open office question please subscribe my channel thanks a lot
Numbers With Same Consecutive Differences
minimum-falling-path-sum
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. **Example 1:** **Input:** n = 3, k = 7 **Output:** \[181,292,707,818,929\] **Explanation:** Note that 070 is not a valid number, because it has leading zeroes. **Example 2:** **Input:** n = 2, k = 1 **Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\] **Constraints:** * `2 <= n <= 9` * `0 <= k <= 9`
null
Array,Dynamic Programming,Matrix
Medium
1224
1,746
hey everybody this is Larry this is me doing nextra Alo problem because um well we just had a yeey prom for the da prom so let's take a look uh did I click on it I think I clicked on it right oh there you go and today's prom is uh and it's February 26 2024 almost said 2029 I don't know these years who knows and why is things not loading is it lead code is it me who knows hope everyone's doing okay it's uh been a little bit chaos in my life a little bit the last couple of days just I don't know why but um I did do okay on the contest so that's fine all right it's finally loaded today's problem is 1746 maximum sub array sum after one operation so you given an integer nums you must perform exactly once so you have to do once where you place one element IE with the I Square I okay we return the maximum possible subar some after exactly one operation okay that's interesting H um okay I mean that's actually a cute problem we'll see I actually don't know this off I head but let's go play around the observation right the first thing to note is that n is 10 to the 5th so you cannot do n square and here you know that if you are able to do n Square the um my do might be that you do kadan's algorithm and just like you know try every possible number and then use kadan's algorithm I'll type it up and contains algorithm is just like a name for things but it's just like a it's dynamic programming in a way uh linear kind of way so I think the idea here then right um from that is um just want it in parallel um and what I mean by that is that because you have exactly one operation so at every given time and if you kind of think about as DP which Cain's algorithm is even though um most people do the space optimization you know directly because it's just easy to remember I guess um because you can lift that one operation to a new dimension so from that it's definitely possible to contain this algorithm with one operation and you just keep um you know keeping more things so definitely if you're looking at this and you're watching this and you uh you know you haven't studied kain's algam yet kain's algam SES maximum subarray some so like I think there at least one but probably a couple if I don't remember these problems on lead code um but in general there probably a couple of leco problems that uses cadan so definitely um search on that and you know go over it but yeah but basically for now uh I will go over I won't go over it in details because I don't know but I will just write the core because we do need to write the core right so basically the idea here is that we have a current thing we have a Max answer so maybe just max answer I don't know or Max something um can we take zero elements this it doesn't matter we'll just do negative Infinity right so here then for x and nums we do current right if current is less than zero current is equal to zero um but before that we want to do Max sum is um you go Max of Max sum current though technically that's a little bit no I think that should be okay yeah and basically the idea here is that and this is contain algorithm right basically the idea is that you take the prefix and then as the prefix gets into negative then you want to start over from the next phase because that means that prefix there's no way to get a bigger positive answer right so that's generally idea okay so this is going to be the Cain algorithm is going to be incorrect because we didn't do the one operation and we have to do one operation it's not given one for some problems it's like maybe you take one but uh yeah so then the idea here is that maybe you can have so current will re write it as current no operation or no op maybe yeah okay fine I'm copy and technically we won't use this anymore because Maxum has to have exactly one so this doesn't make sense really but we'll leave it here for whatever and then maybe we have a current one up right is equal to zero and then basically the current one up is the uh and maybe this is actually negative Infinity because technically we should have at least one thing right and basically this is um now we do the tick no tick except for we're doing it in a DP kind of way or bottom up kind of way instead of top down maybe I should have done this top down I don't know but yeah basically here this is no Tech right and then tick is uh well one up we just sometime um is equal to well it's either the max of this plus X or because basically we only took one operation and then we add the current number because we don't have any operation left or you um is the current oper no op plus x * X right using the square thing x * X right using the square thing x * X right using the square thing and then here of course you convert it to one up and if the no up is less than zero we convert it to zero i h do we convert one up ever no I think we're okay with the we don't have to update the one up because it will come from no up anyway so I think that part should be good do not yeah so I think I why this takes so long I think this is just server because we don't this is just a fall Loop all right lot of technical difficulties all right we have the wrong answers but that's fine let's see why that is yeah okay no I think I like the way this is structur it so why is this wrong okay so two and then one and then 16 so it's 17 right so okay so I mean I think the right answer is let's print uh print it out to see what is going on um instead of me guessing really oh this is a little bit awkward I see why this cuz this is at way at least this um this double counts this cuz this we update the current no Ops so that's just a little bit sloppy actually okay so I guess that was it whoops oops um but all right so this looks good let's give us submit hopefully we didn't miss an edge case and there you go um this is linear time constant space uh but yeah but as I said this is how you can convert I guess Cain's algorithm with one operation with exactly one operation and that's how you kind of do it um yeah and I guess I did also do the space optimization thing right here uh explicitly but or ahead of time I don't know uh let me know what you think I think this is a pretty cute problem definitely also to be honest um if you're trying to do dynamic programming this is a very good um like intermediate dynamic programming problem like maybe not the first 10 dynamic programming you learned but after that especially if you learned kadan's algorithm I think it's a good thing to kind of like give you this idea about like playing with that with the dimensions and stuff like this and adding a dimension this is I didn't do it I didn't write out the code in a way that explicitly shows an extra Dimension but it is there so I think that could be interesting anyway I'm going to go for a walk I have high blood sugar uh being old don't do it if you can't help it so yeah need to go over a walk after lunch so that's all I have stay good stay healthy to your mental health I'll see you later and take care bye-bye
Maximum Subarray Sum After One Operation
largest-substring-between-two-equal-characters
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
Hash Table,String
Easy
null
423
hello everyone welcome to another episode of coding decoded and today we'll be solving march 28 lead code challenge and today's question is reconstruct original digits from english in this question we are given a string that is out of order english representation of digits 0 to 9. just one line is given the question the description is shitty we need to output the digits in ascending order so it's a little complicated not the question but the description is very complicated even it took some time for me to understand this question what this question is asking and what should be the approach there to explain that let's just move on to the presentation and let me just start the slideshow as usual reconstruct original digits from english and let me just take a pen here lead code 423 so let's talk about the english representation of digits so one is represented as one two as p w o two three r t h three r double e and four as f o u r five f i v e six s i get x 7 this and 8 like this and 9 like this so this is the english representation of digits and all of you must be aware of this representation and what we have to do let's create a map where the character z occurs in how many digits so z occurs only in zero s occurs only in six four occurs only in four like u occurs only in four w occurs only in two eight occurs only in eight f occurs in five and four o occurs in uh one two four and zero so one two four and zero t occurs in three a two so this is the t e this is the d three a two s occurs in six and seven and i occurs in nine five six and eight so i hope this is also clear to you this portion of the logic is also clear to you that we have created a map of character and checked in how many digits does it occur and now let's take the example so let's we are given this string this is same thing that was specified in the question o w o z t n e o e r and let's just count the frequency of each of the digit so zero occurs three times w occurs one times z occurs one time t occurs one n one e two and r one and let's just try to map the digit with its corresponding character so we are sure that the that zero maps to z so uh there's no there's one z so the frequency of zero would be one and let's move on to the next one we have six maps to x and is there any x in this string there's no x the frequency is zero so the frequency of six becomes zero then move on to the next one we have four and how do we have any u there is no u the frequency of 4 becomes 0 do we have 2 w there for 2 let's check we have w for 2 and so just write 1 here because the frequency of w is 1 so two maps to w and w frequency is one so we'll write one there and let's move on to the next one we got eight and eight maps to g so let's check whether we have g there no so the frequency is 0 then we have f 4 and 5 in f so let's check uh the frequency of f do we have any f's there f is not there frequency of f is 0 and we know that the frequency of four is also zero so f maps to four frequency of four plus that of five so this is zero so f is also five is also zero maps to z so i'm filling in 5 there 0 there and so next we have uh o and o is present in 0 1 2 and 4 so the frequency of os 3 equals to frequency of 0 plus f of 0 plus that of 1 plus 2 and plus 4 and let's check do we have that information with us or not so for 0 it's 1 so this gets replaced by 1 and for one it's pending so let's call it a variable x and for two is again one so and for four it's zero so plus zero and we can find x through this equation so 3 minus 1 would give us x which would be frequency of 1 so let's that would be equal to 1 itself so 3 minus 2 is 1 x is 1 frequency of 1 becomes uh one so pretty awesome let's move on to the next equation we have t as three plus eight plus two frequency of three plus eight plus two so uh do we have that information with us or not yes we have that information with us uh t is only present once so one equals to frequency of three it's pending so let's call it x what is the frequency of eight it's zero what is frequency of two it's 1 so that means x is 0 so assigning 0 here and let's move on to the next one we got 6 plus 7 as in s so frequency of s is 0 there's no character as s in the string and then we have six and seven so six is already zero seven must be zero then so sign zero there and then we have i is also not there so frequency is 0 and what is the frequency of 9 spending so let's call it x and then we have 5 is 0 6 is 0 and 8 is 0 so x also turns out to be 0 so sine 0 there and now let's just create the string how will we create the string we'll start from this index and as many times as the frequency occurs we'll assign that character into the string so this means you got 0 once and then we have 1 and then we have 2 so that index got added and we created a string and we will do that as many times as each character occurs in that string i hope this logic is clear to you and it's slightly complicated to understand it from the question i tried my level best to explain this question to you and moving on to the coding part so i'll be needing that table for reference so as to correctly form the mathematical equations so i've copy pasted that from the presentation and wrote it here and let me just define so let me just define a map of size 26 and let's calculate the frequency of each character in the string car c s dot 2 card 8 and let's just increase the frequency in the map c minus a pretty simple way of doing this we have been doing this a lot in the past and let's now define a digit array that will store the count or the frequency of each digit using the map generated using the map so the frequency of digit of 0 would be equal to map dot get z minus a because we are pretty sure that frequency of zero maps to the digit zero and let's write it for the other digits as well so frequency of 6 maps to x minus that of a and let's write few more we are sure of you and that maps to 4 and next we have 2 we use w for it and then we have g and the digit is 8 and then we have 4 and 5 so 4 is already known to us let's calculate it for 5. so 5 would be equal to map of f minus digit of 4 so the mathematical equation is something like this we are aware of this value and so i'll move into the right hand side and use a minus sign there so this is how i derive the logic and next we have let's use do these first s let's do it for s six and seven we already have six so let's do it for seven so it will be something similar to a linear equation of two variables and seven is unknown 6 we are sure and s we are we already know frequency of s we already know and 6 we are we have just calculated using x and next we have oh let's go for o that means we need 0 1 2 and 4 so 0 we have 2 we have 4 we have so let's calculate the frequency of 1. so how would we do that we'll use o character and we'll subtract frequency of 0 minus 2 that of 2 and minus 4 again mathematical equation you can derive it yourself you take these values to the left hand side and you'll form that mathematical equation and next we have i so i will be something similar to this so let's replace i first and how many values we have five we have six and we have eight so the variable is nine so i'll keep nine here and we have five we have six and we have eight awesome we have filled in all the digits now and let's just read the string i am using string builder for it because it is not immutable our strings are so let's generate the answer and new string builder and let's start the iteration from the zero with digit update 10 i plus and let's calculate the frequency equals to digit dot i while frequency minus while frequency is greater than zero will keep on appending that character that index n is dot append i and frequency minus sounds good return n ns.2 string and let's try this up hope it works in the first go awesome so surprisingly i missed the equation for t and let's just write it up so t equals to frequency of t equals the frequency of 3 plus 8 and plus 2 so let's just form the equation and what frequencies do we have eight with us we have two with us and three is pending so let's just write that up frequency of three would be t map of t minus eight and two minus two again so now let's try this out accept it hope you liked the video and understood the problem thanks for watching it and please don't forget to like share and subscribe to the channel
Reconstruct Original Digits from English
reconstruct-original-digits-from-english
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_. **Example 1:** **Input:** s = "owoztneoer" **Output:** "012" **Example 2:** **Input:** s = "fviefuro" **Output:** "45" **Constraints:** * `1 <= s.length <= 105` * `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`. * `s` is **guaranteed** to be valid.
null
Hash Table,Math,String
Medium
null
394
uh this question is because shrink so uh I'm going to just quickly summarize it so you're giving a student s then there are integer and a bracket and a character right then you just want to decode it okay so this is the super straightforward summarize summarization now I'm going to explain how you uh solve this question so you are using a two-step two-step two-step why is what the instant the other one is stream Builder step so uh when you see it now okay it's just you know multiple multiplied by 10 plus the current chart minus the zero this is how it expires from num equal to num times 10 plus C minus character Zero so this should be a num right so when you see opening when you see the opening you want to push the num and also the current stream Builder into lower into the step so my third number is three My Stream Builder is nothing so I push three and nothing into the ocean Builder so when it's when I push nothing it's not zero it should be empty right and I see a so my transmission Builder is over a micro Norm is zero right now because I push into the stack I need to reset and then I Traverse the next index is two so I push two I mean sorry I obtain my num equal to two I see the opening so when I say open it I need to what I need to push mine two into the stack I need to push my stream Builder into the distributor stack as well so I will reset this to empty and now I'm equal to zero right all right so uh again I'm right at the opening bracket so the next thing that is easy so I push this charges into stream Builder all right the final solution I mean the final step is the ending bracket so the ending bracket represents what you want to pop your current in out and then repeat the number of the time with the currency so it's gonna be what you publish you pop the QR right so you want to repeat you so using a value or for Loop doesn't matter two times of what two times of currency right sorry two times of C so it's going to be what CR 2C right so two times OC is CC right so uh the next one is going to be one you have a you are so this is the current stream Builder right so you update your current stream Builder to CC next one use next one is for the ending bracket as well right so you pop the A out you pop the AR so top the arrow will be HTC you pop the end out will be three times ACC is going to be ACC so this is a solution all right so enough talking that's a little stop typing so I need a stream builder for currency Builder right and I also need a stat for integer right so this represent a numb style so you can say instead doesn't matter so I'm going to put instead and also the stack for one the stack version Builder so it's going to be screen stack you can call whatever you want and I want to have a noun the num will start at zero this is because I want to push my noun into the instead push my stream Builder into the stream Builder step right so I'm going to Traverse so I'll see it's too far away so I can determine the current territory but this one it's the current character is needed by then I want to just you know multiple that I can then plus C minus zero right and also uh if LC sorry LC if c equal to opening right you want to do another stop it's L6 c equal to closing this is another stop and also the next one is going to be one the character right so it's gonna be what just you know okay speed up a pen see all right so again if I uh if I say opening right if I say opening if I see the opening bracket right then you want to push your stack I mean push it down into the step all right then you want to reset the norm right and also you want to push the stream Builder stack into the uh push-up stream Builder stack into the uh push-up stream Builder stack into the uh push-up stream Builder into a stream Builder step right so it's going to be SP and the easy way to reset is going to be well right all right when you see the closing right you want to take your current sorry Tab 10 SP so you want to take your current stream Builder as a temporary right and I you know you basically uh you want to take out the stream Builder stack out right so the string step up and also the number of times so for I equal to Y in uh instead and I greater than 0 I minus right and then you won't just append just a pen you know ten dollar pen sorry just sp.10 sorry just sp.10 sorry just sp.10 this is your current this is occurrency right the currency is C so you want to repeat a number of times two CC right so this is going to be what spsv power is what a times a pen C two times so a c and then C again so it's ACC and then later on you'll just keep doing until you finish so the final solution is from the what return a speedo to string so let me run it should be okay all right submit all right so for time and space it's pretty straightforward the time is this that right you have the two uh you know one for in the other one Fortune Builders that's going to be all of s representative and also uh the time I'm sorry this is space and this is time right time is all of this as well so Traverse every single character right so it's going to be all of s as representative and it should be you know I'm going to just pause some somewhere here all right so just quickly pause and you'll see just what happened I have finished so uh no I mean they should be the here it is sorry so just pause the intersection you feel confused this is AAS pcpc right so uh test case for this one they should be harder but it's still the same idea I just you know pause it any second doesn't matter all right finish right so uh again this is easy like if you still have questions leave a comment below subscribe if you want it and I will see you next time bye
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
806
hey everyone today we'll be doing another lead code problem 806 number of lines to write string this is an easy one you are given a string as of lowercase English letters and an array which denoting how many pixels wide each lowercase English letter is so width at 0 will represent a and at 1 a will be representing B and so on you are trying to write s which is the string across several lines where each line has no longer than 100 pixels starting from the beginning uh basically what they are saying you can write minimum maximum of 100 pixels in each line and after that we have to continue our s which is our string and write it on the next line and that's it return that total number of lines so at will be returning a list in which that is zero index will be having uh total number of lines which we consume to write all this s which is just asking all these characters and the one index will be representing the width of the last line in pixel so it will be the remaining you can say half line or more than half or something The Words which we have in our last line so that's it so what we'll be doing is just uh making a resultant place first of all and for every character in s we will also make the width starting from 0 and you can say lines which will be uh starting from one because obviously we are going to write from the line number one and for every character in s what we can do is just take its pixel so how can we take its pixel which will be uh in words so character width will be taken like weird taking the ASCII value of that c and subtracting it by a this will give us the index of that certain you can say character it self so a minus a is going to return as 0 and we can just take the pixel from you can say uh from that it will be returning 0 so bits at 0 will give us the pixel for a it will be 10 in this specific case and after that if C with uh plus the width so character weight plus the previous width we have which is in the first case is zero if it is greater than 100 because we know if it is greater than 100 we are going to increment our line by 1 and our width will be resetted to zero because we just started a new line and if it is not the case what we want to do is just width add that character width in the width total width and that's it after doing that we can just result dot append uh first of all at first index we will be returning the lines so lines appending it to result and result dot append the width the character which we have in the last line so that's it after that we can just return as if you have any kind of questions you can ask them in the comments
Number of Lines To Write String
domino-and-tromino-tiling
You are given a string `s` of lowercase English letters and an array `widths` denoting **how many pixels wide** each lowercase English letter is. Specifically, `widths[0]` is the width of `'a'`, `widths[1]` is the width of `'b'`, and so on. You are trying to write `s` across several lines, where **each line is no longer than** `100` **pixels**. Starting at the beginning of `s`, write as many letters on the first line such that the total width does not exceed `100` pixels. Then, from where you stopped in `s`, continue writing as many letters as you can on the second line. Continue this process until you have written all of `s`. Return _an array_ `result` _of length 2 where:_ * `result[0]` _is the total number of lines._ * `result[1]` _is the width of the last line in pixels._ **Example 1:** **Input:** widths = \[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "abcdefghijklmnopqrstuvwxyz " **Output:** \[3,60\] **Explanation:** You can write s as follows: abcdefghij // 100 pixels wide klmnopqrst // 100 pixels wide uvwxyz // 60 pixels wide There are a total of 3 lines, and the last line is 60 pixels wide. **Example 2:** **Input:** widths = \[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "bbbcccdddaaa " **Output:** \[2,4\] **Explanation:** You can write s as follows: bbbcccdddaa // 98 pixels wide a // 4 pixels wide There are a total of 2 lines, and the last line is 4 pixels wide. **Constraints:** * `widths.length == 26` * `2 <= widths[i] <= 10` * `1 <= s.length <= 1000` * `s` contains only lowercase English letters.
null
Dynamic Programming
Medium
null
1,963
What does the question say? The question says that if we give you the input of open closing bracket like this then what will be the minimum required to balance the string. Basically if I have to balance this string then I will check the last to last first position. If I do whatever it takes then something like this will become mine, so what will he give me in this from the minimum, you will have a right, basically if I consider this, then let's see how we have another one, what has become like this, okay, I will then have a I will do this and then I will do this and but my friend, it took me three swaps to solve this, right but here only two swaps have been given, so what does it say here, what has he done that here which is 300 and here three What are the steps? The first zero and four positions have been swiped to the right. This was the zero position. We did this in the class. He swiped this and this position. Your entire string will be in your balance and if you feel that you are only here, then this is it. Gone is the last of the first position thing, you swipe here, tight, I won't exit, but take this pattern, right Spider-Man, just to balance me, I'll show you back if something is wrong with your screen. This way, if you clean the zeros and fours, right, then you just have to balance the question for one week, so whenever we have to string, I got this, after that, then got this, I got this, after that, then I have been given in the beginning that Exactly ny2 opening bracket and closing bracket will be there so I will also have this next and if I get any such pattern that whenever I showed you that the zero third position we will swipe, in any such pattern we will get right and whatever we have in between If the string is found in the middle, even if it is found in the open starting after that, then bed definitely, I will get the closing right in the last part of the showroom and he will balance the closing, then our swap will be zero in that, so whenever I get the input, I will get it. Bye tu se divide karunga Right tu se divide karunga right But here the problem is not solved exactly Suppose I got three such patterns right Something like this And something like this Again I know that I am this one I will balance in the swap itself, but this too will be saved, so whatever my answer will be, I will divide the account of the account by two and take a mod basic from that and add it to that, so that I will also know that brother. At the end, if one mine is not left, then this will solve our entire problem. In range and from now on, not range. Directly, we will call it character in string and then what will we do and then two, then three, and then in some way, first I, mine. I did the opening packet, after that I got the second one, I will get something like this right, this is my second character, so now I have got these two, which means I don't need them because this is already the balance, right now I got something for me, the third character is mine. Something like this and the fourth one will be my character, something like this one right, now I will do that if there is something in this tag of mine, then you directly tax me and if there is no tax on me, my string of tech men is not in balance because if friend If I had come, then my balance is there, meaning this is the date main's A and after this, if any other string is A and there is any very-very small string in my strike, then my any very-very small string in my strike, then my any very-very small string in my strike, then my balance is my strike, it is not my balance because there is no It condition in the stack. I am worried that string is not in balance, so what will I do, I will simply take the counter and increase it, I will open the counter, increase it, I will kiss it in the account, then you will get these patterns from this, it is good, my brother, last one. What did I tell you that we know that we have to return, so just by changing the position, you single it was a mistake on my part, I have accounted for the variables and what is going on in my mind here, so our test has been passed.
Minimum Number of Swaps to Make the String Balanced
find-xor-sum-of-all-pairs-bitwise-and
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. A string is called **balanced** if and only if: * It is the empty string, or * It can be written as `AB`, where both `A` and `B` are **balanced** strings, or * It can be written as `[C]`, where `C` is a **balanced** string. You may swap the brackets at **any** two indices **any** number of times. Return _the **minimum** number of swaps to make_ `s` _**balanced**_. **Example 1:** **Input:** s = "\]\[\]\[ " **Output:** 1 **Explanation:** You can make the string balanced by swapping index 0 with index 3. The resulting string is "\[\[\]\] ". **Example 2:** **Input:** s = "\]\]\]\[\[\[ " **Output:** 2 **Explanation:** You can do the following to make the string balanced: - Swap index 0 with index 4. s = "\[\]\]\[\]\[ ". - Swap index 1 with index 5. s = "\[\[\]\[\]\] ". The resulting string is "\[\[\]\[\]\] ". **Example 3:** **Input:** s = "\[\] " **Output:** 0 **Explanation:** The string is already balanced. **Constraints:** * `n == s.length` * `2 <= n <= 106` * `n` is even. * `s[i]` is either `'['` or `']'`. * The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`.
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum.
Array,Math,Bit Manipulation
Hard
null
1,062
hey guys how's everything going and it's continued our journey to these code this is one 0-62 longest repeated substring is one 0-62 longest repeated substring is one 0-62 longest repeated substring we're given a string s find out the length of longest repeated substring which is zero if not none is fun fine found it none is found for ABCD none of them are the same so no repeating one a B ba maximum is a b or ba a third one a B of course the longest will be a B right so a B is here and the last one all a that the first four and last four so yeah how can we analyze this problem let's suppose we find the longest one all right it's the longest one like a B and a B so how can I capture X these two sub strings well there's a starting X and the length right if we have two index sub starting X and the length 2 so this reminds us that we could actually find all the possible starting X pairs and to check the longest and then from this to starting X right like for like okay first one and then start here with how far we can go from these two index and or if you pick this a and the freebie say see how far we can go from this to index and that we got two so after we traverse through all the possible index pairs and we can get the maximum so the first one is actually I think it's kind of brute force loop through starting next pair and this will be in square and for each pair check the longest that will be linear right space we don't use any extra space Wow well after well check it over again after we finished it okay so there is a result variable called Max and we now find every possible starting expand for this first one if we started with zero like this right the last one couldn't be because if we would go to a there's no more the more string we can compare to J will start from IMU Swan it could be good they could go to the last one and then we define the longest a length that we can start from both index sorry zero and for K okay Wow will Q swell s i+ k equals s j+ k if they are Q swell s i+ k equals s j+ k if they are Q swell s i+ k equals s j+ k if they are the same mm-hm I think we could use do the same mm-hm I think we could use do the same mm-hm I think we could use do Wow do Y is better so if we do if do wow is Wow under that we should use Wow if this is the same we were opted max right plus one plus 1 and then plus K to the next one so now k will end at a position where the two catchers are not matched if the first one is first status is not matched then k will stop at a zero so no max of god I'm confused now plus one and before that oh yeah plus 1 and then we update the maximum right okay and Max and finally yeah we returned the max let's try run code cool let's submit yeah rock septic but not that fast right so let's try to improve that to improve our solutions we first analyze what was done in provost proves solution like for the we are if we give our given this kind of string now what happened when we are checking the checking this in this brute force solution we first we check a against a right and then we find the K we find the fine they are matched so updated Max is 1 and then we will check this a and this B and then this a then this C so this obviously is a waste of time because when we are already checked one string we actually needs to who can forget about this kind of right we don't need to check a B and again okay directly check a and B C right yeah for this kind of solution after we check a B and a C we will still check a B and a C suppose we are already checked a which might matches this a or this a matches this a and in that for loop we will check AAA and AAA again well and then we will check a B and a B again and we already got a three right or we got three we already know that the maximum is three until here but now we will go to for the first loop we will go to this a again and it will go to a here again so there's a lot of duplicate compare comparison I think we could avoid that if we check know that a and here matches and a week and we can be assure that if this a is the same we can just get we can just a plus one to the previous redock with this and this right so we can improve this by checking the ending solve to substrings of possible sub strings and catch the result right so I think it's kind of dynamic programming which means FN if I J we say is it is longest matched string and the ending at I and J if that's the case if I J so all the cases that I small that I somebody that I and a smaller NJ will be already calculated right so equals if I minus 1 J minus 1 plus 1 if si equals s J if not then of course it's 0 if not right sure so let's first use a array cache the result it will be a two dimensional array so I say result equals new array and what input s would be is empty no it will be bigger than or equal to 1 fill with 0 and then map it with a new array this new use could be omitted because for JavaScript he doesn't matter s net ok this is the result we're going to cache and then we will loop through the string all the ending pairs right ending pairs would be the same I think start from somewhere which were ending with this and this or this with this so it's the same as previous one we set it to this now if I zero which means there is no previous if there's no previous element which means we could just this is the ending case for our Travis alright that's Travis all but there is no previous result we can refer to so if I equals zero do I just set the result which means I J equals s I equals SJ then 1 if not zero and for the article for the other cases results i J would be of course the same ternary if it is same then result I minus 1 J minus 1 and J is just not zero but one so this could this always we've added and if not is zero so and we need to update it the maximum at pass we did before and the max equals MA max result I and J well this access actually doesn't matter but let's cash it to make it better let's count equal zero so count equals this and we set it cash I J close count and finally return max so this should also be working right hmm no cash oh this is not cash but results not a number what maxing zero County kizhi will count is this if I is zero okay results I minus 1 and J minus 1 not 0 yeah and the results I J count hmm maybe there's something wrong here array s done then Theo 0 ma'am array s then hmm this is still nothing wrong I think I for look I works J works and then count if I say zero count equals if your same Z 1 if not zero if not and check this results I minus 1 J minus 1 cool 0 Max results was calm so I'm they returned Maksim yeah so the count is not a number well that is weird hmm ah God my bad this should be start with I plus 1 just like we did before that but it's one what this is that's uh well actually in a real interview this could not be let's just start with mine with our mind to see if we can debug it okay if I zero for aaaa first one we got a and then we got this a and then County 0 if I is zero so all for B once right and then math.max count okay said it can then we go to 1 and the 2 so 4 1 2 because they're saying so we got 0 1 oh my god we forgot to plus 1 cool as a myth as we see it's better than the previous one at the time actually as we catch the result it will be in linear we made it to avoid the extra move through so time is this a space of course it's the same as square right we'll catch the result while cui do better let's just go back to this solution let's revise this example opening to our solution here what's the comparison queue sequence will be well of course it would be comparing a and then what then would be a B right a B and a C and a acquaint again eh well you see there's still problem that is that even though we reduces the ex duplicate comparison right complicated comparison but we still didn't remove the unnecessary comparison like when we found a actually there's no need to find a to compare a B right at least in this case there might be some extra like a B or is the same as these two but basically this comparison is not necessary we just need to find the next one if you found okay so a its mattes then you could start if there is a fine final to substring which is has longer than these two double a it must be after this right if it is before then it won't be handled before this that way so after we met this a and we can start working on a and a B and just to try to search for longer length than m1 started to start study from - there's no need to compare study from - there's no need to compare study from - there's no need to compare these ABAC anymore right so the compares would be if you compare a and fine it and we will start from a and a B it doesn't match it so we go to this a b and find bc not match it doesn't match a my bad so if you found a and ib doesn't match we will compare a to b c and then do this again and we found a and with this a right okay and that's we will start with a B because this is already the longest until current and content comparison there's no need to check the strange before it what with this I think it will be save us a lot of time of course I have over tried it so he actually does so I would just as I just did some deduction that might need to our better solution wow this is not actually this is editing can him come up with this solution the best one has is I did like this but I wear some materials and deduct to this one so this is actually how to say a simpler mindset to understand it okay let's start with this approach so the basic idea is find the match first match off length I and then find the next match often in I plus 1 starting right from previous position right okay now let's say the max would be 0 according to our analyst here well first and loop through all the index right and then start from next one so for net I what will the max is updated and this length will not be necessary it should be max minus 1 for 1 it should be like this so it would be less - okay now let's search for the be less - okay now let's search for the be less - okay now let's search for the next substring right well this is basically a for loop just to loop through it and to check if it is the same or not okay because we're searching the next possible right so the next target would be s slice hi max plus 1 yeah so if max 0 we're going to search this actually this actual or factor and now let's do the search let's start from next one J will also be smaller than that smaller than this J plus 1 well and then we can just slice the same right I just say substring equals s slice J no here should I plus max tip that's my X plus 1 now if they are the same I mean if they are like this if they are the same we just continue checking the next one right checking it a B okay so if substr equals next target max should be pass one a core of course next target should also be updated so next target would be plus with s i+ max next target would be plus with s i+ max next target would be plus with s i+ max plus 1 and the J will be next one so we need to keep J at the right position and if they doesn't match so we got goes to the next string just next position like for a B and then we walk after we okay so for this a we found that it is matched and then we will update in the max and the next target will be a B and the J will minus 1 to keep the J at the at this position here and they will eat walk compare this again they are the same again so update it yeah so after this the max will should be updated returned max of course why we fair why we've failed let's do the analyze okay max may 3 so so the IAA and the next target would be because max is zero so this should be okay we're searching for a and we go to Jay from here and I just modernist okay Jay will also be smothered oh I made of me I think I made a mistake for zero I this should be right but Jay should not just should be stalked into the laughs a right oh I made another mistake so cool it's a met Jay oh if this is the case oh yeah it's right oh I forgot to that if they doesn't match actually just oh it doesn't matter mm-hmm okay if they matched we find it mm-hmm okay if they matched we find it mm-hmm okay if they matched we find it and then go to next one to do the chat seems no problem yes console.log substr thanks target for yes console.log substr thanks target for yes console.log substr thanks target for this one the first check a B and find a so we check a B and then a B a BA mm-hmm right oh I should there B a BA mm-hmm right oh I should there B a BA mm-hmm right oh I should there is a problem that is next target and it seems the problem here mmm a B and then a B Y a B and then we met a B and then we check a BA and a BA hmm something we are here I J what's wrong here ok 0 1 a B right 0 2 a B D 3 a and then 0 3 still a 2 3 a BA be still 8:03 is a be a ah oh I made a mistake of updating the max before this next start still sub-string should be makes dark it okay sub-string should be makes dark it okay sub-string should be makes dark it okay a be a substrate is a why so a still ice max please max top what did i do i'm this should be right cool ah god wow this is very subtle mistake Wow I'm sorry right now we're a faster than eight and seventy seven percent of the JavaScript submission so I think this is good enough for our journey wow this is a pretty deep topic and let's analyze the time and space comparison for this one mmm what is the time what is the space so if all the strings like if let's say if all the strings are different like ABCDE what will happen and then we can we analyze some case of like all same whatever happens okay for they are all different so we find a and then a b c d e done there's nothing to be all know and then b check c d e a CD right even if there is a small character that it is match they will faster the faster this sub like when we get a and fine a let's start working on a B ad and then B a so the worst case is that all different and we walk worst is that all actors are different this is well check square of and for best if they are the same yeah we check a and AAA BBB so remember that slice I think for JavaScript I don't know the exactly implementation of how a slice but it because it's slice I like it was supposed to use array we can just to act actually do direct access so a it's actually is constant time and for space you see we don't use extra space for this right without creating an array so it's constant so actually the time complexity is the same as previous one but it's for only for worst case so the why this that's why this solution is much faster than a previous one okay and without extra space so that's all for this problem we use different approaches actually that's what I didn't can come up with it but from the first solution to the can one to the last one I learned that we need to analyze the cost a cry call sequence of the comparison of this like this problem well let's see what has be compared and we can deduct improvement okay so that's all for these problems hope helps you next time bye
Longest Repeating Substring
partition-array-into-three-parts-with-equal-sum
Given a string `s`, return _the length of the longest repeating substrings_. If no repeating substring exists, return `0`. **Example 1:** **Input:** s = "abcd " **Output:** 0 **Explanation:** There is no repeating substring. **Example 2:** **Input:** s = "abbaba " **Output:** 2 **Explanation:** The longest repeating substrings are "ab " and "ba ", each of which occurs twice. **Example 3:** **Input:** s = "aabcaabdaab " **Output:** 3 **Explanation:** The longest repeating substring is "aab ", which occurs `3` times. **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
If we have three parts with the same sum, what is the sum of each? If you can find the first part, can you find the second part?
Array,Greedy
Easy
2102
264
hello friends welcome to algerie po so today we are going to solve ugly number to lead code week one day for the challenge so let us see what is the question so the question is that you have to find so you will be given an N equals to 10 so you have to find tenth ugly number so they will be giving position so you have to find that position ugly number so let us see first what funny number means so ugly number are positive numbers whose prime factor only includes two three five and one more thing and we'll take one has initially has a ugly number only so we will treat one has ugly number so first we'll have ugly number one so and we'll see if two is only number or not so yes because to prime factorize comes under - so this is - in the same comes under - so this is - in the same comes under - so this is - in the same way three fine and what will be my next early number so for this for two - early number so for this for two - early number so for this for two - family number will be four in the same way again x - y again x - 16 in the same way again x - y again x - 16 in the same way again x - y again x - 16 in the same way for 13 over 3 6 9 12 and 4 5 10 15 20 so these are only number because this number has so if we see here 2 into 1 so this 2 has only 2 factors that is 2 &amp; 1 this 2 has only 2 factors that is 2 &amp; 1 this 2 has only 2 factors that is 2 &amp; 1 and both are early numbers and let's suppose take 9 if we take 9 3 za 9 and this both are ugly numbers and let's suppose stay 15 so fight twos are 10 so 5 &amp; 2 both are early numbers and let's 5 &amp; 2 both are early numbers and let's 5 &amp; 2 both are early numbers and let's suppose take 7 so 7 factors of 7 &amp; 1 so suppose take 7 so 7 factors of 7 &amp; 1 so suppose take 7 so 7 factors of 7 &amp; 1 so 7 easily number but not 7 so this is not another number suppose take 14 number so 14 is allele number or not so the factors of 14 is so let's take seven twos a footing so two is any number but not seven so this is also not an ugly number so what re number is let's suppose if n is ugly number then factor solves and let's suppose I 1 and I 2 and I 3 so this is the factors of n so all the factors of n should be ugly number means the factors 2 3 5 even 16 is also fact 16 is also ugly number so 16 into 2 will sorry 16 into 2 n so let's suppose n so n in fact factors are 16 and 2 will so you will see 16 and 2 in both are a real number or not if both are ugly numbers then we'll say that n is also ugly number so this is it so let's see how we are going to solve this question so let me erase this first after that discuss so let's see so we have some problem here so let's see if so what will be my brute for a brute force approach so let us see so this is one is my initially my ugly number is 1 and for finding nest for finding necessary number we'll just do so 2 into X 3 into X and Phi into X where my X will go from high to and this all numbers are ugly numbers 1 to n all the ugly numbers comes between 1 to N so let us suppose X is 1 so 2 next give my X's or two years so food my ex is three so my value will be two three juh 6y8 in the same way for let's suppose for here we'll take different variable so that will understand properly let's suppose we'll write here Y and let's suppose we will write here Z so again even Y 1 to N and all 1 to n all our universe only not different numbers so for one it is 3 and the National number will be 3 2 6 and again because 2 is also because 3 &amp; and again because 2 is also because 3 &amp; and again because 2 is also because 3 &amp; 2 both are universal 3 2 - it's an FIA 2 both are universal 3 2 - it's an FIA 2 both are universal 3 2 - it's an FIA right 3 to the 6 3 these are 9 3 forza to win in the same way for x equals to 5 z equals to 1 to n so 5 into 1 by again Feitosa 10 because pi into 2 both are prime factor pi/3 is a 15 so 15 both are prime factor pi/3 is a 15 so 15 both are prime factor pi/3 is a 15 so 15 also and pi forza because 4 is also prime ugly number so phi forza don'ti so we are what we are doing we are just adding so first i have so here my x y and z values are increasing like this so first we got one so my value is 1 but all again my value for again my value will be increasing 2 and 2 so I will multiply so let's suppose we'll just take what X only we'll just take / X only faster so first we'll just take / X only faster so first we'll just take / X only faster so first my X was 1 so my values will be 2 into X but second for finding factors only having number 2 so first one so I will get 2 and after that I will insert this 2 X here so - to puja for so for puja - to puja for so for puja - to puja for so for puja yeah in the same way because we also have three as a prime factor we also multiply three so we have one problem if we see if you see here because we have to find and the number 10 so if you see here 10 so this is 1 2 3 4 5 6 7 8 9 10 so this is my 10 prime factor right so every number so we have to return to earlier but if we see here so 1 is my first onion number and if we see from here this is my second ugly number that is 2 if you write 3 my this is my farinelli number this is my fourth ugly number 5th ugly number right but when we again will find 4 3 will see that 3 comes here between 1 2 then 3 then 4 right so it is coming in middle of the number so we have to find in proper way because if Pam 3 into let's suppose X Y Z values are 2 so see here 2 into 2 4 3 into 2 6 5 into 2 n so 1 2 then from here for from here 6 and from here 10 so how my index is increasing so this is my 0th index this is my one index and this is second index but we have 3 we come here 3 use threes also ugly number so I should write three-year so instead of I should write three-year so instead of I should write three-year so instead of increasing our y-values so instead of increasing our y-values so instead of increasing our y-values fell same like forth X Y Z increasing same number like two I have to check if in between these numbers is any another amelie number is present or not so for that we will use one we will use minimum concept so what minimum constant is concept is that what we'll do we'll just do minimum of so our formula is x square y Y into 3 and Z into PI right so we'll do X into 2 minimum of Y into 3 and Z into Phi will find minimum of this number and we'll add to thee so let's suppose this is my result array so we'll add the value here and if I will not increase so if my eye let's suppose my x value was 1 so I'm not going to show it will increase to 2 but I will not increase well Y &amp; Z I will not increase well Y &amp; Z I will not increase well Y &amp; Z I will just increase / - so let's code then you just increase / - so let's code then you just increase / - so let's code then you will get proper understanding what I am want to explain to you so first of all we have to create one vector to store values for that time let's suppose I am taking result or let's say okay result and first we will make size one and store one because initially we know that one is an ugly number and after that I'll need three integers I J and K and all are equals to zero because it they are pointing to zero index that is value one so in reason result they are pointing one so what I will do and so at the because my array index will start from zero so I have to see till my result dot size is less than N equals two not any equals why we are not writing equals to n here because our index starts from zero that is why we are writing and because we have to find n it ugly number that is strength value number that is here to L so what we'll do we'll store in result dot push back what we will do minimum of what was our formula so result of I right now it is 0 10 else so result of ice that is 1 in to 1 this is 1 into 2 and also minimum of result of J it is also pointing to 0 for now and result of Z into 5 so now we have stored minimum of that number and will only increase whose number is minimum here so if let's suppose after multiplying here 1 into 2 3 2 1 3 5 2 1 5 so we got 2 3 5 so minimum value is 2 so my only ayat index will be increasing not J and Z so for that how what I will do I'll check if result dot back is equals to result of I into two I will just increase i displace only increase I attend X and J I am said will be remain same in the same way I will also check in the same way I will also seek well check / j + z so further j and this well check / j + z so further j and this well check / j + z so further j and this will be multiplication of 3 so it will be j + space and if it will be said that be j + space and if it will be said that be j + space and if it will be said that is z it will be multiplication of phi and it will increase Z + space and after and it will increase Z + space and after and it will increase Z + space and after at the end I will just return last Anette index n - 1 index here so what I Anette index n - 1 index here so what I Anette index n - 1 index here so what I will do just return the result dot back so let's run now let me once again check it okay so we have error here sort of jet into PI said ok I have wrote here capitals it I have to write k here i j k and i have to write k here and here okay how initialize K for that and let's run now and so no yes it is finished so test case is running let's see if my solution will be accepted or not so yes guys so it is accepted so thank you guys for watching my video and if you are new here please subscribe and if you have any doubt or how any have any doubt please comment I will respond to it thank you guys
Ugly Number II
ugly-number-ii
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return _the_ `nth` _**ugly number**_. **Example 1:** **Input:** n = 10 **Output:** 12 **Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers. **Example 2:** **Input:** n = 1 **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Constraints:** * `1 <= n <= 1690`
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
23,204,263,279,313,1307
48
welcome to a new video in today's video we're going to look at a liquid problem and the problem's name is rotate image so in this question we're given a matrix so in this question we're given our nbined 2D Matrix representing an image and we need to display the output by rotating the image by 90 degrees clockwise and the condition given is that we have to do it in place and do not allocate another 2D Matrix to do the rotation so let's see how this question can be solved and identify a pattern like how we can generate the output from the input image given so let's take the same example they have given us we are given the input array and we have to get this output array so we have to turn this input array 90 degrees in the clockwise Direction so we'll get the output array so to form this output first you have to perform the transpose of the original Matrix so if you perform transpose on the input Matrix you have to Interchange every column with its row so the elements inside this row are one two three we have to make it the First Column inside this so those row elements are now displayed as columns let's do the same for the second row will become the second column let's do the same for the third row that will become the third column now we found out the transpose of the input Matrix you can find little similarity between this and the output array so if you see this transpose the elements are displayed from right to left so for example here the elements are displayed as 1 4 and 7 and here they are displayed as 7 4 and 1. so it means that and rest of the elements are also following the same Trend so it means that we have to reverse each row inside this transpose Matrix so the next step is to perform reverse operation on every row so this 147 is the first row this will be displayed as 7 4 and 1. let's take the second row this will be displayed as 8 5 and 2. this is the third row this will be displayed as 9 6 and 3 and these two are same so we now have the output Matrix so let's perform these two steps using a Java program so now that we have seen the steps how to get the output let us code it up so here we are given a method called rotate and we are given the input a matrix on which we have to do the operations so let's do it by following the steps I've shown you first we have to write a method to transpose The Matrix so let us create a method transpose Matrix and pass the input Matrix here and the Second Step was to reverse each row in the transposed Matrix so let us create another method and call it here so I'm going to call this method as reverse rows and pass the input Matrix so now that we have called the two steps and there's no need to return anything because the return type is void so first we are going to transpose The Matrix and then on the transpose Matrix we are going to reverse the rows now that we have called the two functions here let us Define the functions transpose Matrix and reverse rows the return type is going to be void and we also need to pass the input Matrix on which we are going to perform the operations and the second method is going to be also of return type void and it's called reverse rows and again pass the input Matrix on which this method will be working on now let us write the code to transpose The Matrix we need two for Loops the outer loop will be denoting the rows and the inner loop will be denoting The Columns so for and equal to zero is listen Matrix dot length so the inner loop J is going to start from 0 and go on until it is equal to I now let us transpose the element at the row with the element at the column so I'll use a temp variable to swap the two target elements so in temp which is initially pointing at the element at the row Matrix of I J and now we need to swap it Matrix of so this is pointing at zero and swap it with the element pointing at the column Matrix of J I and now Matrix of J I will be pointing at 10. so with this we are going to swap the elements and finally this will happen for all the elements and we'll get the transpose of the input Matrix now we have to write the function to reverse the rows where that let us iterate through the Matrix using a for Loop so this will be ah indicating the rows the I variable so to reverse the rows again I'm going to use a temp variable for that first I need to find out the leftmost element inside that row so here it is going to be 7 and the rightmost element for this row is going to be I so two pointers will be pointing at the leftmost element and the rightmost element so the left pointer I'm going to point it at the index position 0 and the right pointer I'm going to point it at the end of The Matrix now we have the two pointers pointing at the index positions left at zero and right at the end and now using a while loop until left is less than right this while loop will run so while left less than right now again using the temp variable I'm going to swap the elements so n temp is equal to Matrix of I and left now swap The Matrix element at left with the element pointing at the pointer right so I is going to denote the row number so row 0 left most element swapping it with the row 0 right post element and now Matrix of right pointing at temp so with this we are swapping the elements pointing at left pointer and right pointer until left is less than right and now for the next iteration I am going to move the left pointer one step to the right and move the right pointer one step to the left so this while loop will run until left is less than right and finally this method will reverse the rows after we have performed the Matrix because first The Matrix is being transposed we're calling this function and then after that on the transposed Matrix we are going to perform reverse rows so now let's try to run it there you have it our solution has been accepted let's submit the code there you have it our solution has been accepted so the time complexity of this approach is of n square and the space complexity is constant because we did not allocate a new Matrix to do the operations so it will be of one that's it guys that's the end of the video thank you for watching and I'll see you in the next one
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
116
hey what's up guys babybear4812 coming at you one more time today we're doing problem 1017 the populating next right pointers in each node part two problem there's this is a obviously a part two to a part one that i haven't answered before and i'll leave a link in the description um i'd say the problems they're not entirely mutually exclusive you can do one without the other there are some differences uh the differences are not radical but they exist i would still urge you if you haven't done that other one go check it out before doing this one because i think it might be slightly easier now with that said uh this problem has been very popular with bloomberg facebook amazon as well have liked it and i think it's a good problem all right it won't be too difficult i think we can come up with a pretty intuitive way to do it but at the same time not so obvious either so i'll zoom in here and say that we're given a binary tree with the following structure where every node has a value a left and right node and also a next note so this part's new the rest of it we're familiar with the standard node otherwise we're told to populate each next pointer to point to its next right node there is no next right no the pointer the next pointer sorry should be set to null initially all next pointers are set to null uh we may only use constant extra space recursive approach is fine we may assume implicit stack space does not count as extra space for the problem um this is a follow-up so the version um this is a follow-up so the version um this is a follow-up so the version i'm going to be doing we will be using um extra space i'll leave it for you guys for the child to do the recursive way um but anyways that's just like a fair disclaimer ahead of time if we look at an example of what this looks like this is the original tree and the next point always pointing to the right well the one points to null that's our root the two is going to point to the three and three points outward or points out um and then we've got four points to five points to seven which goes to null in part one to this problem we had perfect binary trees meaning that we always had left and right pointers and everything was perfectly balanced this isn't the case here so we've got to figure out how to deal with this scenario over here um and they give us a little explanation of how this works but basically we're going to return the root after populating all the null pointers uh constraints we're told the number of nodes is less than six thousand sure that's not really going to change anything for us let's take a look at how we're going to think about this if i've got this first pointer over here okay and what makes this again and i always say this with tree problems but we think about how could this problem potentially become more trivial it would be more trivial if i was sitting at this too and i was able to say well if my parent has a right child let me just go up through my parent find the right child and set a pointer to go that way right we can't do that here because there is no pointer to the parent node okay and that's pretty common so then we think to ourselves how else can we go with this problem well in general if we think about how we go through tree problems we often have to traverse them and sometimes rather i'd argue maybe every time it's a good idea to ask yourself how do i want to go about traversing this tree if we're going like this we're trying to point from left to right so all the way we start at the most the leftist side and then point to the right um and we go down level by level that kind of screams breath first search to me all right and i think with the constant space solution ignoring the call stock is we could do a bfs solution using recursion again i'm going to do it iteratively just because i think it'll be more clear to understand how we're piecing this all together but bfs would be the way to go here and so then the question becomes what do we do about the fact that these are now missing again especially if you know if you did the earlier problem part one this would have been our example and then we talked about how you can kind of almost seemingly bounce around by taking care of your children before taking care of yourself kind of thing in this case we can't do that however i would argue that it still won't be all too difficult for this reason if we're solving this problem using bfs with the bfs we'll typically use a queue and in our queue we'll originally load up just one node the root node and we'll then pop it off so we pop it off when we're analyzing it and then we pop on its children if the children exist so we'll have a 2 and we'll have a three well as we're popping these children off i don't it doesn't really matter to us um whether there are or aren't children missing because once i pop the two off i'm going to add the four wow then i'm gonna add the five that is shocking and then when i pop the three off i'm going to add the seven since we can set up a for loop to only run the length of whatever the initial cue size is we can just say that while we're going through that for loop take the note i'm looking at and make the next pointer over to whatever else is in the cube so whatever item comes next in the queue that's it i don't care if that next item falls right here as in kind of the that i don't know what they call this is a parent this is like an aunt or an uncle um no if they have a child or not like if you have a cousin node here it doesn't matter because whatever comes up next in the queue is what's next almost visually speaking when you look at the tree and so if we just if we understand the problem that way where whatever comes next in the queue is what i'm going to point right to and again when we're iterating through the queue with a for loop it will end right here this iteration will end right here because we're initializing it to run with a length of two whatever's in here when we start popping off and if we can follow that logic then essentially we can set up all of our next pointers to kind of keep pointing to whatever comes up next in the queue the code itself may we may have to make a couple of tweaks maybe get just a tiny bit clever on how we're actually going to go um go about setting these pointers and keeping track of them but you know nonetheless it will be a bfs problem we're going to take the items in the queue and every time we see an item being popped off we're going to take the previous item we had and set its next property to be what we just pulled off the queue in terms of edge cases and maybe sort of error checking we may have to do if we're given a null nodal church null or none in python um apart from that i think that what we'll see as we write the code out is things like having just one node in a row or even two will there'll be almost two cases and then the third case will be when we have something like this we've got three or more nodes and then we need to do a bit of skipping and kind of continual tracking of the items that are coming off the cue you can almost think about the queue as a as like a conveyor belt almost um whatever is coming off the conveyor belt we have to keep track of the pointers and make sure we're appending things properly when i say appending i mean attaching to that next pointer and that's about it in terms of the theory i'd argue this problem isn't too theory heavy uh the code will be a touch more involved uh but still overall doable um overall i'm not introducing any sort of new ideology here i'm not breaking for ideologies i'm not breaking like i don't think i'm breaking anyone's brains here by sharing this stuff so um if you have any questions if it doesn't make sense let me know down below i'm happy to elaborate on the explanation as always but i think otherwise we're good to jump into the code and see how we can make this happen move this over and begin with my our standard error checking so i'll say if we're not given a root we're going to return either the root itself or doesn't really matter um so here so if when we do a breath for a search problem we said that we always or i didn't say but we do it typically with the cube so i'm going to initialize the cue and i'm going to use the deck as part of the python collections and within this queue i'm going to append the woo so that's going to be our beginning we're going to have this overall this while loop and then let's just say well while there are items in the keyword we're going to do a whole bunch of stuff and eventually we're going to return the root note okay so i'm not all i'm doing is modifying the pointers in place so at the end of the day i just i gotta pump out whatever was given to me which is again this root note and so this is where a majority of our work is going to lie so since we're going to be um tracking two or more items at a time i'm going to need two pointers okay and this is i think one of those examples where as we walk through the code i think it'll me it make a bit more sense why we set it up in the way we did as opposed to the other way around so if it's a bit confusing or maybe this part is a touch non-intuitive just part is a touch non-intuitive just part is a touch non-intuitive just bear with me and i hope that by the end of the video it will make a bit more sense i'm going to have some sort of curve variable which is going to just point the current node that i'm looking at and i'll initialize that to none i'm also going to do the same thing with a next node and i'll set that to the reason i'm not typing it is next because that's a keyword in python and so to avoid any headaches that may cause ulc i'll refer to current as being my point right now and the next being the potential next one next item that i'm looking at now we actually want to take our cube and like i was mentioning here when we kind of want to break off and say let me pop off the items in this queue that exists you know in it right now i only want to go so far as there are items in there and for that specific length for that one specific level if you will that's how many items i want to pop off so what i'm going to say is that i want to make a loop and i don't really care about the variable name here so we got an underscore so for some underscore in the range of the length of the queue right we're going to start popping these off now there are three scenarios like i mentioned briefly in the kind of the theory in the whiteboarding part where we said um we can either have no kind of items whatsoever so far so i've i haven't looked at a single item on this level yet and in that case that'll be if not curve we don't have any current value we're gonna do some stuff again i'm leaving this cell just for a second to set up the framework otherwise if that's not the case um if we don't have a next variable so maybe we have a current now but we don't have a next so we only have our we have just that one item we don't have the second we haven't connected them um then we're going to do something else and then otherwise uh if both of them exist we're going to do a whole third set of operations and this again i'm just i'm setting the framework up here just so we have the big picture before we dive into the details if we don't have a current so i haven't taken anything off the queue yet i'm going to say that curve is equal to q dot top left because again i want to take from the beginning of the queue and then once i take that off if it has any children i want to add those to the queue so i'm going to say curve.left q dot so i'm going to say curve.left q dot so i'm going to say curve.left q dot append left and then same thing with the right child right and that's it if we haven't done anything if all we have is one item in our inner level so think about uh something like this where we're just looking at the root we pop the root off that's it's the only item you have on the queue that's all we're going to pop off if it's got a left child we'll append that to the cube if it's got a right child we'll append that to the cue right and those aren't mutually exclusive we can do both of them so i think that's okay so far now what about that would kind of take care of our first level notice by default the next pointer for this curve is none and that makes sense right here we want to leave it as not i'm not going to alter it in any way the only time where we want to have a next pointer is if we have two or more items in a level so that's where we're going to look at this scenario here so we found our curve but we don't have a next yet if we don't have a next then i'm going to say that next is equal to q dot pop-left which is the pop-left which is the pop-left which is the preceding item that we have in the queue right now okay now let's think about where we're at right now let's pretend that i'm right here and this is now my curve and this is my next okay i know that i need to go from curve to next that's why i need to set my pointer up so given that's the case i'm going to say cur dot next is equal to next and that's it i've now connected those now i go through the same process of saying if next has any children let's append those on to the queue so i'll see if uh next dot left q left and if next dot right so if it has a right child q dot append next dot right and that's it for the second step so if all we have is two items in a level for example right here i'm going to say i have my car i have my next i'm going to connect right cur.next goes to next to connect right cur.next goes to next to connect right cur.next goes to next it's right here cur.next is equal to it's right here cur.next is equal to it's right here cur.next is equal to next and we've added next children now onto the on to the q so this is imagine our q now this has been popped off we've added four and five which are two's children okay they're right here and we've added seven which is three's child so now we're in the scenario where so we've kind of finished this cue i'm almost walking through the loop here in the open uh this would iterate through two times because when we started this loop all we had was a two and the three and the q this is all we had this loop is now done we jump out of this loop we ask while there's a key which there is there are still items in the queue we now reset our pointers to current next both of them are none we don't have anything all right but what we do have in the queue is the four the five and the seven so if not occur we don't have a curve our curve is going to be four right this is the item we're gonna pop off four is gone and that's going to be our i'll call that cur we finish through that loop we go to the next one we see if we don't have a next which we don't next is going to be five right this is going to be next is going to be five we popped it off we set cur.next equals next off we set cur.next equals next off we set cur.next equals next so we pop that off four dot next equals five perfect all right we're good now we keep on looping and now we get to the seven right this is the final item in our queue here and so we get to the seven and we say if not occur and also we have occur it's four we have an x that's five so now what do we do here okay now we jump into we jump in here we get the seven so what do we want to do here let's think about this we have the seven here and i know i want to connect the five to the seven okay well let's first off make a reference to this seven so i'm gonna say that current now is going to equal q dot pop left so i'm no longer pointing at the four oops that was my old solution i'm no longer pointing at the four and i lost my pen i'm now pointing right here okay so i'm pointing at the seven and i know i need to connect the five to the seven so five is n five is next sorry seven is curve so i'm gonna say next dot next is equal to curve what does this mean five next is seven okay so far so good we're going to do something similar here and now we're going to say for curve so if seven had any children we're going to append those we'll see if uh if kurt dot left and you know maybe i'll just copy this over because the exact same code and maybe there's a cleaner way to modularize this so i'm sorry the code's a bit repetitive um but we i think it's at least understandable this way we so we've appended the left we appended the right and now we have to somehow move this along forward move this forward along move this long forward i'm not sure we need to move this along all right so we're done with the five means nothing to us anymore okay we're now looking at the seven over here so we have a curve okay since we're starting at the beginning here what i would argue is essentially is the following so we say next on x is equal to occur what we want to do is let's pretend now the reason i'm kind of getting into the scenario is what if we did have more children what if there was a you know there was a 4 here this was like an 8 and then we had a 9 right over here for example that is awful and we had a nine okay if we needed to keep on going how would we go about how do we go about humans well we would have to the following i would say let's set the next pointer equal to the current pointer the next pointer we're going to set equal to the current pointer which is going to be right here so actually this is going to be current and it's going to be next what's going to happen now if they're both if the current and the next are both pointing at this at the seven when we come around we're not going to jump into this because we have a curve we're not going to jump to this because we have a next what we're going to do is jump into here and we're going to see that ker is equal to q dot pop left meaning kerr would now be this nine over here next dot next so next remember is the seven still now it's almost confusing because the next is behind the curve so i'm sorry if the naming didn't really make if it makes it a bit confusing but the next is behind the curve right now so i'm going to say next dot next is curve 7 dot next is 9 right because this is now our current this one over here maybe make this more clear this is now next this is curve 7 dot next is nine seven dot next is nine we append nine's children we pin seven children we move the next along repeat added an item that should do the trick i'm gonna run this really quickly to make sure there are no mistakes and submit it and we're good perfect so let me minimize this just so i can show you guys the code in one go here this is the entirety of the code and it's in its fullest we started off by doing error checking then we did a standard breadth first search by setting up a queue and then and looping through these items and keeping two pointers one called current and one called next if we popped up if we were at our first item in the queue we popped it off added its children we were at our second item in the queue we popped it off we set our current pointing to the next item so we set up that initial connection we added its children finally if we had we already had two pointers and we're adding a third or a fourth or fifth node in this level we repeated a very similar process and then we just move the pointers along one more over um and so that'll rinse and repeat and get us all connected at the end of the saw we return the route i hope that was clear i hope this helped if you have any questions as always drop them down below uh like comment share subscribe all that fun stuff any other questions you want me to answer do let me know um any feedback you have i am always looking for feedback so if anything was confusing uh if you want to see less of something please do let me know it goes a long way and i guess yeah that's it i will i'll see you guys in the next video peace
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
5
hey folks this is praveen and today we're gonna see the problem of longest columbic substring so what the problem statement says like there is a string provided and we have to find the longest palindromic string what does that mean so we'll have to check all this offset and in that we'll have to see the highest or the longest substring out of that which is transforming so in this example one we can see babad it will see a b is a paralympic strain with size 3 and then we have aba so the answer is baby or aba but anything could be the answer because this length is free now i will see the second example here we can see the string is c b d here's the output is bb so the reason is if you'll see the b and b uh there's only one sub string which is palindromic and if we have a string with a single character we can return it and if we don't have any sub string with the or which is certifying the parallelogram we can return a single string so that will also configure the parameter so let us try to understand how we're gonna solve this so i'll take this as an example so i'll use two uh pointer let's say left and right so what we're gonna do we're gonna iterate over this string whatever is provided we'll move from left to right first we'll just go over the first string and we'll increment uh the right pointer by one position and left pointer will decrement by one position and we'll check if the values are equal then we'll add it as in the substring parametric sub string if not then we'll move forward to the next string next index and we'll keep doing this till the time will i have to push to the end of the stream so we'll try to run it for this so for the first position left and right would be on the first position and we'll be having left and right equal that is our b value then since we can't go on the left hand side we will implement our we'll again reassign our left and right to the a now left will decrement by one r will increment by one and yeah p is equal to b then in that case we'll again increment r but okay and we can't do so we'll go to the next position which is p here also will reduce our l by one position and increment our r by one position values rc then again we'll increment r by one position and uh l by one position so v is not equal to d so our sub string would be a b e so that's how we can solve it so there is another case in this so this is what we are seeing is the uh one scenario second one is this where we can get the palambromic stream in the even count which is like 2 4 something like that here we are getting the panoramic string in the uh odd account which is like 1 3 5 like that so for this we'll have to handle it in two cases so for even for odd cases we'll start r and l and r with the same position for the even scenario what we'll do we'll start r i will take l and r would be one position like next to the end and then we'll start comparing it so in first scenario we'll compare c with b then the second scenario will come here so i think this is the approach let's try to write the code for this so what we're gonna do we'll gonna iterate over our string for r equal to 0 is less than s dot length and i plus now okay with each character we'll have to like expand it from the link center will reduce left by one and implement right by one position so for that i will write a helpful function let's call it public will return the string from here whatever the string you get which is written panel okay now here we're gonna pass our string we'll pass our left index will pass our right index and i think that should be fine to see let's try to write the code and then see that if we need anything so not this we'll run this loop because what we are doing we are keep incrementing left decrementing left and keep incrementing right and checking with the values so till the till when we're gonna do till the time left is greater than and equal to zero and right is less than s dot length okay so we are checking the boundary condition and if s dot care at right okay so we are checking first we are inside the boundary like we are not crossing the length of the string the boundary condition we are checking and second thing we are checking for then what we can do uh we can actually create a value here or variable here just call it result which might need to empty strain now result equal to uh and start service string left and right plus one so we are getting the substrate between the left and right now we'll decrement left by one increment right by one right and once we are out of this loop we will be having our result with the longest column room between this left and right uh okay now let's call this from here now here also as i explained we'll be having two type of palindromic history one is hard right second one is type of event so we create the variable for that and we'll be having one written like the final answer that is our filing room let's call it initialize it outside and i'll create one temp to store the temp results from the uh return calendar function all right so first we'll call part so as i explained and call it the function which we created and s will pass as an input to the function then i and left also i and the right also i so we are passing uh the same value for the left and the right then for e1 what we have to do we'll do the same we'll call the same thing but for the right will pass one value next to the left right now we'll check whether the right or whether even or the odd whichever sub string we are getting valence obviously whichever is greater will consider that as an answer on that step so type equal to if odd dot length let's say if it is greater than the even problem that means the odds of string is the greater one so what we are going to do we are going to return the odd in that case it should be portion of ordinary operator otherwise ge right so in that way in this time variable we'll get the uh like the uh the longest of the between the card and the unit now we'll have this final result stored in this so what we're gonna do we'll do the same check here palindrome equal to we'll check if parameter dot length if it is greater than the temp whatever the current uh sub string we are getting with its length then we consider falling from itself as an answer otherwise the time will be our new balance so long as the string is column and in that way like when we are done with this entire loop at the last we'll be having our uh longest parameter string in this variable so if i have written it correctly this code should work let me try to submit it yeah it is working so that's how we can solve the longest palindromic problem please do like and subscribe to the channel if this video is helpful thank you
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
911
hey what's up guys chung here and so this time uh let's take a look at this problem uh number 911 online election it's a medium problem so uh you're given like two basically uh two parameters right the first one is a person's at least all the persons and the second one is the times so the ice element of a person means that at the time i this person i got voted by one and now it asks you to implement like this q method which will be uh giving you a visa like the input as a time here basically try it asking you to return what's the current what's the leading person at this that this time here which is the t okay um oh and in case there's a tie the most recent votes among thai candidates wins okay so some examples here like uh you're given like this person's array right so basically they're like seven votes and here are the times right like each person got the times at the votes happened okay yeah so you know since it tells you that the one of the constraints that the time is strictly increasing right so i think this is like strong hint right so every time when you have a t here right you just need to search the answer okay i mean another way is like it's like what is like for each of the t here right for each of the time here we just loop through all the persons and the time under and the votes right at the time of this t which is smaller or equal than this right and then at so for each of the q the curve q here we loop through all the volts before this t and then we calculate the most of all the voted person right but that would be like time consuming right because so for each of the queue the car here right there's like uh it's like 10 sorry 10 000 right so how many times after yeah they're gonna be ten thousand the cost of the out of the queue and each of the time we do uh we'll loop through all the persons right that's gonna be ten thousand times five thousand yeah which will be most likely tlu at least very slow okay so another way or not a better way is the uh we pre-calculated basically is the uh we pre-calculated basically is the uh we pre-calculated basically for each of the time here right we pre-calculated uh at we pre-calculated uh at we pre-calculated uh at each of the times here what who is the leading person okay and then we store them into a into like uh a hash table and every time we have a t here right since the time to remember is strictly increasing we can simply use the binary search to find the find which is as binaries use the t as a key to binary search the times that's uh we need to use to find our answer since we have already processed uh for each time right we uh who is the leading person we simply return that value okay yeah that's pretty much it is okay so for coatings right uh so the first one is the self leadings right so i'm gonna create the leadings right like the uh like a hash table right that so that's the first things we want to use to uh to search basically that's going to be our hash table and the second one is the uh now let's populate that hash table okay basically we're gonna have like a and n equals to the length of person so how do we populate this hash table right at each point at like at each time okay basically uh in range and here we just need to maintain like a current max vote okay right and the person is the person's i right and then the uh time is times i okay so um yeah so besides that we also need like a variable to maintain to keep counting basically counter right the counter of the votes for each person which will be the votes it's going to be a hash table right default dictionary the default is integer okay now um so this one is going to key and the value okay so now let's say we have a well actually you know what actually this uh the leadings here we don't even need to store a dictionary right because the with all we need to do is since the sequence right at each times will be aligned with the time sequence here so all we need to do is we just need to store which person is the leading person at this time right basically uh a simple list will be enough okay and basically if not right south basically if the there's empty here right we simply do what we just uh self dot leading okay append depend the current person right because of and also the current max vote is one right so that's elsewhat else the uh yeah actually we don't even need this time here okay but i'll leave it here maybe we can just also remove this one okay so now the uh else if right as if the uh yeah sorry self doubt votes uh the key is a person right and then plot plus one okay else if uh if the self dot votes if the current person's vote is equal greater than the current max volt okay so why we do a equal here right so because it says if there's a tie basically if there's a tie then the most recent vault wins basically if there's already like two votes another person one have two votes okay two votes now at the same position at this round right let's say the person two after increasing one we also have two votes so at this point time here the most the leading person should be p2 not p1 that's why we do uh do a greater or equal than this okay self dot leadings append uh pan p okay yeah because this is the new person and we also need to update the current max okay uh it's going to be a self dot votes dot p right we also need to update that else so the last one is the uh the current people doesn't it's not the leading person okay which means what which means the uh the last person is a is the leading person okay so what's the last person so the last person is the append uh self leading dot minus one okay basically so it means that if the current one is does not have it does not have the maximum the most votes then at this time here the previous one the basically the so whatever was the leading person it will still be the leading person at this time that's why we use the last one the last element okay yeah and of course there's no point to update the current vote okay yeah so after that i mean we have uh we have the leading persons at each of the times here okay yeah so that's that and now we can implement this queue here right basically what we do this right we do a binary search at the time here but how do we do the binary search let's say we have 1 2 no let's say we have 1 5 10 and 15 okay so let's say the time is 3. so what's the first time of three here right and the time we need is we're looking for is one is this one so that you so that if we use a bite bisect if we use a bisect and then bisect uh bisect left let's see if we can use the left okay if we use the bisector left the source is okay so the binary search we also need to uh save this times so the sources is the times itself okay if we search the times with the t here right if we do a by bisect by uh bisect left then if we search three it will give us one the index will be one right the index but instead we need zero okay that's why we need to do a minus one but how is the left correct one no right what if the search is like uh a one what if we are searching five okay since we're doing a bisect uh left minus one right if uh if we're since we're doing a minus one here if we're doing the left here uh when we search five so it means that if it's the same one if the same numbers it will give us the index on the left side which will be uh which will be one right basically it will insert at this position right so this is alway also b1 but it but we what we really need is we're hoping is to give us 2 right so that the 2 minus 1 will give us the 5 the index of 5 which is 1. that's why instead of left here we need to use right so which means when we're searching the same index same value of this of the time same times here we just need to get uh the index plus one so that when we do a minus one we can get the correct answer here okay basically that's the index right so we simply need to just return the self-leading just return the self-leading just return the self-leading right the leadings of the index because we are we have the same length of this the leadings at each time here as long as we find the times we need we just need to use this index to find the leading persons at this moment okay so i think this should just work uh okay yeah run it cool submit cool yeah it's pretty uh straightforward like medium problem so the only thing here you guys need to like to pick to notice that is just to use a binary search right and so to be able to do a binary search the key is the time but and we also we and we need to pro since it doesn't ask it didn't ask you the time right it asks you to return the person the leading person at this time so that's why besides the binary search we also need to construct right the data basically the data at each time so that we can just simply search that cool i think that's pretty much what it is i want to talk about for this problem yeah thank you so much for watching the videos guys stay tuned see you guys soon bye
Online Election
profitable-schemes
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Array,Dynamic Programming
Hard
null
1,787
hello everyone let's take a look at this record problems it's the last problem in the weekly context and it's a very hard problem i also didn't figure out during this context let's take a look at this problem so the problem is uh we are given an a number and an integer k we need to find the minimum change we can make such that each segment like the xr of each segment will be zero okay so um so each segment the excel of each segment is 0 which means the excel of nums i and num one num zero num one num to the num k minus one same as num one extra num two xor until num k so num zero is num k actually which means times i is the most number i plus k for example here three four seven same as one two three six three okay this observation so when you determine first k element as long as the first k element determine the whole array did i determine for each element we know they can be choose choosing from zero to 1025 okay so we need a dp and solution here dpij means the minimum elements we need to change to make the xor of first i elements equal to three so dpk 0 is the answer we want to get okay let's take a look at this implementation first i initialize this dp array since the constraint mentioned that the size of these nums can be at most 2000 so i initialized it 2001 here and initialized dp0 to zero finally i just written dpk 0. okay here i'm maintaining this frequency vector it's for faster calculation later for example for index one when we have four like one and four if we are changing them to four we know the frequency of 4 is 2 and total number here is 3 so streams minus 2 is the total num noms we need can change for that particular index okay since we are going to build a dp table so in the output for loop we just iterate k times next we pre-calculate the total next we pre-calculate the total next we pre-calculate the total means for example by iso or total like index 0 index 3 index 6 total 3 ok next we get the previous um minimum change at first the previous minimum change is zero okay now we need to build uh for example one is one wind to build dp one zero tp1 one tp1 to dp12 and tp1 and 1024 okay for each state we can initialize dpi plus one target to total plus previous minimum change uh think about it assuming i'm calculating um dpq10 you know dp210 must come from a previous state for example dp1 and dp15 that let's say the previously minimum change is dp15 since i can change any number between 0 to the like 174 so it includes obvious uh combination so there must be a number that x or so set number can get my target so in the worst case i just changed all the numbers so dpi plus one target yes total plus previous minimum change it seems it's the worst case okay next we just iterate um so like we just try some good cases for example here one let's say one is one we know we have four one four if we change all numbers to one we only need two chains if we change our numbers to four we only need one change so at first we pick four so previous target yes tip xor target the current target we want to calculate if previous target is greater than once of 24 just you can earn it okay now um we calculate the dpi plus one target dpi plus one time is the minimum of dpi plus one target or like dpi previous target plus my current changes my current range is the total number which is three minus the frequency of my peak number okay so in each iteration we calculate one state then we can just final answer okay so this basically the solution of this problem and it's actually a very hard and deep problem thanks
Make the XOR of All Segments Equal to Zero
sum-of-absolute-differences-in-a-sorted-array
You are given an array `nums`​​​ and an integer `k`​​​​​. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`. Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k`​​​​​​ is equal to zero. **Example 1:** **Input:** nums = \[1,2,0,3,0\], k = 1 **Output:** 3 **Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\]. **Example 2:** **Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3 **Output:** 3 **Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\]. **Example 3:** **Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3 **Output:** 3 **Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\]. **Constraints:** * `1 <= k <= nums.length <= 2000` * `​​​​​​0 <= nums[i] < 210`
Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly.
Array,Math,Prefix Sum
Medium
null
502
hey everybody this is Larry this is stage 23 of delete code day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm uh I will not be doing an extra Farm today just because I'm tired I not gonna lie I didn't sleep that well yesterday I'm going to try to cook something really quick afterwards and then try to go to bed early but yeah and we have a hard one so maybe it'll take a while anyway so yeah 502 IPO suppose Nico is soon in order to sell a good price you know increase fudge as capital before IPO is that how that works basically can finish at most K distinct project before the IPO help the code designs the best way to maximize the total Capital finishing at most K distinct projects okay so um this seems like a an optimization problem or maybe a sorting problem um to be honest at this point I'm thinking Heap but let's kind of redone so basically you have end projects the I project has a profit of whatever and then a minimum Capital needed to start it okay initially you have W Capital when you finish a project you obtain is per profit and then uh and then your profit will be added to your total Capital I'm just going to make sure that I understand this um that okay let's actually read an example because I because you have this Capital thing but you don't spend it I just want to make sure that I understand that because that doesn't seem to the okay one uh the profit is one okay with Capital One you can start project index one or project is next two you choose two but you don't okay so yeah so you choose this one but you don't spend the capital okay so I mean this is being a sorting problem um with uh with a heap so both I guess the idea here is just to kind of pause it as I mean the idea is to just be really greedy and really the way that you want to be greedy as maybe intuitive though that's it just because it's intuitive doesn't mean it's right but I think this one you can kind of prove it because there's no decisions that have any point per se right basically of all the things that you can spend on you get the one that's most profitable added to Capital and then you and after that you do the next one that's the most profitable right and it just keep on going there's no optimal solution or there's no more optimal solution because that is it what is K and W I don't even know K is the number of projects but it is w oh initially W okay all right so I think yeah that's pretty much the idea um and this is shouldn't be that bad but let's uh yeah basically yeah uh these like mixed away things are always a little bit weird to me but that's okay um yeah okay so basically let's just say you have projects Maybe uh and let's just make it a list of sip profits capital of it and then now we want to sort the projects we're going to sort projects by the capital needed right projects uh sword key is equal to Lambda let's say about the thing then capital is x sub uh one and this will give us uh maybe P for project I don't know and this will give us capital in increasing order so yeah I think I've done it in one line and the reason why I do want to do in one line is that because I want to show off is because I want to change this a little bit um to use a deck or a q but in Python is going to be attacked right okay so then now we have these projects and then now we can do it one at a time right so basically now um so okay so final capital okay so um this is a current capital it couldn't be your current capital as you go to w right um and then once again we have Heap which just allows so what we want here is a Max Heap that allows us to just get the maximum possible every step right so maybe that's quite profitable maybe is equal to a heap right uh and then now we just want this Loop of while okay so we is K always uh I just want to make sure okay hmm that's weird that okay I guess it's at most okay I was gonna say this is a little bit weird that uh yeah Soca I mean we could do K is equal to Min of k um length of projects let's make this n okay and then now we can do something like this right so we choose K projects um well current is the thing and then now we want to say um maybe profit was a weird one maybe just like selectable maybe right and then now we want to go wild length of uh projects is greater than zero and projects the first item if the first item the capital of it and this is what this is means it's a little bit yucky I need to you to read up on the various upgrade I think that makes it slightly better but anyway uh while this is greater or less than or equal to current because basically this is the capital required and this is the current capital right so while this is the case then we want to put some put into selectable so we're going to push in the Heap we want to push the project that's pretty much it right so projects of zero kind of but not really uh or not directly what we want to do is sort by the profits right oh actually yeah we don't even need the tablet at this point because everything is selectable we know the capital so then we only need the profits so that's this and we want the max of it so that's a hack we'll just do the negative version of it um because in pipeline there's a Min Heap right so okay so then now that's good then here we go um if length I think of the because of the way that we did it this should always um actually I don't know if that's true but anyway if this has at least one item then current we added to Heap that hip pop of selectable um and of course we want to subtract or no the negative version of this because of that's how these things work of uh reverse and then afterwards we return current and I think we should be good Maybe do I have an infinite Loop somewhere oh I'm dumb uh I do have an envelope somewhere of Pop left okay uh let's give a quick Summit apparently I got time to mix it last time what did I do last time I'm just curious about past Larry did and the idea is the same um oh wait no it isn't I do it in a funky way oh I see what I try to do here I try to use one Heap instead of I guess that works it is slightly better I think but um it is slightly better because uh so guys let me go over my solution this time and then we'll go over uh the other one because I think that's slightly better but uh yeah but here uh the complexity this is going to be sorting so this is NL again already um there's a couple of like okay uh in this case what the cup of login operations just because that's how Heap works but each item can only be inserted and popped once so that means that they're at most um foreign there will be um login right so this is almost K log n but it gets dominated by this n log n in terms of space this is linear well attack resorted we have a selectable thing that all linear things uh in aggregate so um yeah and again time of and space and that's what I have for my solution today what did Pastor Larry do so you put a heap this is still going to be n log N I don't think that this is actually I mean it's um oh no I think my original one was wrong maybe I don't know no I don't know this is actually the same code I think I misread it on the skin uh yeah um that's all I have with this one and let me know what you think um yeah let me know if you have any questions please in the comments or on Discord yeah stay good stay healthy it's a good mental health hope you all get through the rest of the week okay I'll see you later and take care bye
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
718
hey everybody this is Larry this is day 20 of the Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm and today's contest and all this uh today's just problem here and today's uh video and all that stuff um yeah let's do it let's get started uh today's problem is 718 maximum length of repeated Subway what does that mean we turned the maximum link of a sub array that appears in both arrays okay so it has to be sub one thing that I'm really bad at to be honest is that I confused Subway and sub sequence a lot so hopefully this one's okay um let's see right uh can you just before so am I confused on a complexity so basically um this end let's say there's N1 and N2 um the offset is just yeah the offset that's only n different possible offsets I guess technically n plus M so two thousand and then you just do a loop through the away so then that's ends that's another thousand so that's only n square right don't miss something maybe that's it I mean that's fine it's just that I was in uh there's also a binary search one where you do um uh you hash you know using um Robin copper or some kind of sliding window hashing um and then just hash where we for some K and then you know your binary search on that k um but I think what I said it's okay right so basically uh let's say N1 is you got the length of nums one and two is you got the length of nums two and then basically for offset um so basically this is assuming that you know you have n one and nums two and then nums two will start or we'll start the numbers two at some offset right so in range of N2 and of course we could do it the other way as well but we would just write two for Loops so yeah so I have some passes you got zero side and then yeah right so then now we compare um yeah for I as in range of N1 if num sub 1 of I is equal to number sub two of I plus offset then you know then well we first start with um counter is equal to zero and this is the case we increment by one else they're not the same so count as equal to zero and then I do you know in this case we'll do best as you go to maximum best counter we might have to optimize but yeah but that should be good I mean we only do one direction for now but you know we can actually I was going to say you could buy another photo but I guess what you can also do is just do uh you know find something like this foreign fight out of numbers one numbers two um and then Max of this or something like that right now this should be mostly right other than maybe minus some typos I would say uh oh I thought I um I did actually remember that I had to fly but then for some reason why I typed it out I forgot but uh okay if I press offset is greater than or two then we break and we could put it into the for loop I always prefer C style for Loops for that reason but anyway guys yeah so that looks good am I confident yeah let's go let's give it a quick submit well last time I did eight seconds so maybe it wrote time out hopefully not but it might because they seem like they've been adding more test cases um oh this one is actually faster because surprise uh 903 day streak so let me know what you think I mean it's not super fast maybe the binary research one is the idea um I'm trying to think whether there's another like fun way of doing it but maybe a binary search is the idea but uh I don't know it doesn't really matter um I mean there should be you know 2 000 times a thousand so it should be two million so I don't know why it takes so long to be honest um but it is what it is I suppose what I did it last time yeah I guess I did the same thing last wait what did I do here I guess I did the same thing last time actually mostly I don't know why I have so many weird things actually but like overlap and stuff I guess I just put things in a different thing but yeah either way so n Plus or n square or something like this uh just two thousand times a thousand let me know what you think I guess yeah the binary search way is the way to go um yeah let me know what you think there might also be a thing where you know we can take advantage of the 100 but maybe the binary search one is the one so the idea about binary search is that you hash every lookup of Link okay and then yeah if you can find on the other one then you could try to go for something bigger and that's what you binary search on but oops what did I click on yeah that's all I have with this one though so let me know what you think this is N squared time uh oh one space so space wise is pretty okay so yeah anyway stay good stay healthy to good mental health a quick short one for once and I'm gonna go to an early sleep bye-bye
Maximum Length of Repeated Subarray
maximum-length-of-repeated-subarray
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_. **Example 1:** **Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\] **Output:** 3 **Explanation:** The repeated subarray with maximum length is \[3,2,1\]. **Example 2:** **Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\] **Output:** 5 **Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\]. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 100`
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
Medium
209,2051
326
hello welcome to my channel so today let's look at the recorder 3 2 6 power 3. given an integer n return true if the eta is a power tree otherwise it return force so um example if n is 27 then it's uh three cube so it's uh should i return true if n is zero it should return false if n is nice uh three square is still returned true if n is 45 it's a multiple tree but it's not a power tree so we return force so also if it's if it is a one it's actually return true because it's a power zero power of three so the constraint n is uh the entire integer range so and actually it's also possible it's negative and the follow-up and the follow-up and the follow-up it asks could you solve it without loop or recursion so uh so for this question i'm going to give two solutions the first one is using recursion and the second one is uh is the follow-up que uh we will not use any follow-up que uh we will not use any follow-up que uh we will not use any loops or recursion so let's look at the first one so recursion we need to have a base case so for this question well n equal to one actually it is a base case uh you need to return true right and if n is a um if n is a another one but the and more the three is not a zero joint definitely will return first because n is not a multiple of three so it cannot be power three so then we actually can go to the recursion path uh so the third recursion we can actually just return function and divided by three so uh so for a number to be power 3 for example if 27 is the power of 3 is 27 power 3. we can actually convert it to a problem is 27 divided by 3 which is 9 power 3. so this two question actually is a equivalent that's why we can use a recursion this way so let's uh start coding this uh also the uh the time complexity so the time complexity of this uh question is uh using recursion is login and uh using the space and time is both for the o log n because we are at every time we divide it by three so we can only divide it by three log n times also the because it's using recursions uh it will have need to use the stack uh to so the step depth is a maximum log n so okay let's uh let's start coding the question so if n is smaller than or equal to zero we will need to return false so now let's do the base case if n is equal to one we can return true and uh else so if n is not equal to one but the end mode three is not zero then we return force then in the end of the function we just do the is the power of three then we do and divide it by 3 which is also which should be uh integer because n um and will be multiple of 3 if you go to this step so now let's try okay i'll see if let's try those examples if it's cracked okay so it passed so okay this is the recursion now we can do the second with this without using recursion so it's math so what we need to do is the way we can find the find the maximum or power of 3 in the integer range so we call the s that thank you for actually all the numbers uh we can for all the numbers we can just check if the number is uh of if we can uh have a mode as zero if we divide of s by n so if it's a zero then that actually will return true if is not zero then we will return first so how do we find the maximum power of three so we actually can start with the integer like the limit we can call limit which is the integer dot max value which is uh in java it will give you the maximum possible integer so we use this integer to uh we firstly do a log on that integer and then um we do a wrong round then we can do the uh power of three using that integer then we get the max power 3. so let me ask coder this and then you will maybe have better idea so let's remove this okay yeah so integer limit equal to then i can do um like x called uh i don't know i can use the math.log i don't know i can use the math.log i don't know i can use the math.log lim divided by but math.logo3 but math.logo3 but math.logo3 so this one is uh actually it's like a log of 3 we do a log 3 on the limit so then we need to run this uh i don't know we can just do an integer this will run the run down a floor yeah so then we got the x so we can actually get together s as i mentioned earlier so math s is a math on the uh we can do a power of x dot uh a the x then the rest is uh already i just copied that so if s is if n is a divisor of s then we return true okay otherwise the return first math okay so it's a double and i need to convert it to integer okay right here we actually missed the case that n is uh after we still need that condition if uh we cannot have n if n is smaller than or equal to zero we actually can just directly return the force so if n is zero then make it this one illegal so now it should uh okay yeah also just mention the time complexity because this mass this is the mass so the time and spread uh space both uh o1 time complexity uh so okay let's okay so you passed and uh yeah so this is today's uh video so if you like the video please uh subscribe or click like button so thank you for watching see you next time
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
389
Hello guys I am Lalita Agarwal welcome tu jo owner on coding channel confectionate same you made but you also let no start today this lead code problem aaj ki lead code problem kya bol rahi hai achcha before going towards d problem na 1 main decision par dosh Those who have understood the problem well and want to try it themselves, see that the question is literally a very easy question. There can be many methods to solve this question. Whatever method you want, you can apply it here. There is no constant Jivan on it and the constant Jivin means its length is 1000, its power is 1000 and the length of T is 1000 plus, meaning the length of S is plus one, so ₹ 101 meaning the length of S is plus one, so ₹ 101 meaning the length of S is plus one, so ₹ 101 is its length. So max is literally very easy and consistent, so you can use whatever method you want with it, you can put Android map in it here, you can also solve it by shorting, you can also solve it by batman inflation. You can also solve it by doing sums, there can be many methods, first of all you will understand this question and after that you will solve it with the help of sorting formula because there are literally many options and there is no problem in any of them. If it is not the case, then we will do it in easy way only. Okay, now what was the life here, life was just like this, which is the string in front of us, okay, by adding something on the string with S, we will make the devil string with S. My trick is that I have done some add on and have made a string with T, just do n't say my question here, it is quality, and whatever add on is, what is it, I have to return it, I said, okay, so A is A. In this also there was Bullia, it is a matter of touch, B is said, Bibi is said, it is okay, C is said, Yes, C is also there, Di is said, Yes, brother, DB is there, so is it child, what is child, is it my answer, that is last, AG is my answer is If there is only one, then what happened here, it is not necessary that it was in the elastic, it is not necessary that it will be in the last, it can be in the middle also, it can be in the first also, it can be on the story also. Said, okay, understand. I said, yes, look, here it comes, this string was empty, okay, the one with S had its initial spring and in it, A was said, every point of time has to be done, anyway, this will never happen, I said, okay now. Here we see our approach, we did not do anything in our approach, first of all we created a variable N in which our length of S is ok, inside S we will add on, ok do n't forget this, ok then our What did Sorting do? Sorted both the strings of both. Why did you sort both the strings of both? Because look here, by default, it was short, so it became very easy to find it in the sort. I found the cheese very easily, if this shot would not have happened, it would have been so. There is some life here that the string with its S is A Di C B is okay and the string with its T is something like this C B and A Di and this is okay. Now here you have many more methods to find both of them, when you can do it very comfortably, you can make a note, after that nothing will be done and there will be no need of sorting for shopping, if you are in the order map. Make all the records, do GP, do CG, do BP too, then come here, then we would mine everyone's frequency, whoever's frequency went back, it also became our answer. It could be a mother that these If you take the exact value of all and in the end, you subtract them all and then maybe one, you sum the value of all these and in the last you subtract the value of all of them. If you want to see your starting point, then do it as soon as you start. What will this become? Now it is okay on the CD. As soon as we shorten it, what will it become: A, B, C, D and A. Now it is what will it become: A, B, C, D and A. Now it is what will it become: A, B, C, D and A. Now it is very easy to cut our own here, A to A cat given, B to B cat given, C to C cat given, 180 K. From di to di's diya and apna aa gaya and tell me the answer. Okay, so apna has done the same. Here, I have shortened both of them. After sorting both of them, the look of my simple four has started. What are the people of four saying about six? I go you run from zero to ijjain n letting kya run from s ki side to chota and keep checking your there and point of time pe ki kya jo ki of s is not equal to pk i if any point of Time is up, it means you have found your character, just return it and if I have traversed it completely and still haven't found it, then your first or last character will be the same, then you will return the answer, ok. I hope you have understood the last character well, still if there is any doubt then unbox only is fine, tell me then off login or off people, whatever is the biggest, it will be fine and if we talk about your space then Off One Apna Space Ko Hum Log City Uske Kar Rahe Thank You
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
1,624
hello everyone this is Sher and today we are diving into the Leo daily challenge for December 31st as the final challenge of 20 23rd we're not holding back let's tackle it together right away first let's understand the problem we are giving a string s and we need to find the length of the longest sub string between two equal characters the substring should not include these characters themselves if no such substring exists we return minus one let's understand the problem statement using a cartoon analogy in this question we consider the first occurrence the leftmost character as a person looking to the right waiting to find other person of the same kind looking back forward to the left side once we find two people looking at each other they form a substr string including all the characters in between in the first example we are given the input string as a we Mark the first a at index zero as the person pointing to the right and the a at index one pointing back to the left they together form a substring consisting zero character between them therefore the longest substring for character a is zero since we only have a in the input array we return zero as the answerer let's look at another example where input string consists of several different characters here we have c b z x and y in input string however we only have one character of each kind and thus none of them can form a substring take character c as an example here we Mark the first occurrence of C as the person pointing to the right and there is no another person pointing back because we don't have a second C therefore the longest of string length for each character in c b z x and y is minus1 therefore we take the maximum length out of them which is minus one here we can make our first observation for each character the longest substring length equals to the result of rightmost index minus leftmost index minus one then we take the max value as the longest substring lens to return let's analyze one last test case before we talk about Solutions in this test case we have again multiple different characters in the input string and let's start by looking at character a we iterate from left to right we first find our leftmost a at index zero then when we iterate up to index 3 we find another a since this is the n first a we discover we mark it as a person pointing back to the left which means we find a substring the substring formed by a at index zero and index 3 has a length of two however when we iterate to index six and find yet another a this a becomes the new rightmost a and thus can lead to a longer subring which has a lens of 6 - 0 longer subring which has a lens of 6 - 0 longer subring which has a lens of 6 - 0 - 1 = to 5 here we notice that once - 1 = to 5 here we notice that once - 1 = to 5 here we notice that once a new rightmost character is found we don't need to store the old rightmost character indexes we discover along our iteration therefore we can have a second observation for each character we only need to remember the left most occurrence position since we can update new longest substring lens along our iteration from left to right this observation is important because it saves us a lot space complexity as we won't store any unnecessary data with these two observations we can now construct our solution first we do the initializations we initialize a hash map to store our first occurrence of each character we then initialize the answer variable called Max lengths 2 minus one so that we can handle the edge cases where no two characters are the same secondly we iterate the string and update our variable alongside our iterations for each character in iteration if the character is not in our hashmap we add it to the hash map with this current index otherwise if the current character is already stored in our hash map we calculate the new substring length and potentially update our answer variable finally we return the answer variable maxed length as the answer the time complexity of our solution will be linear because we iterate over each character of s only once and at each iteration we perform constant work the space complexity will be constant because as the input only consist of lowercase English letters we only need to store one first occurrence index for at most 26 characters notice that we cannot achieve constant based complexity with without the second observation we will see this in action in the code later let's first quickly go through a solution that CA linear space complexity we first use default dict method to create a dictionary where an empty list will be initialized as the default value for each key we also initialize the answer variable we then iterate through the array and record all indexes of each character to calculate the substring lengths we update the max lengths and aaable if a longer substring is formed finally we return the max Lings as the answer let's see how we can save space with the second observation here we only store the very first occurrence index of each character in the hashmap once we find a character which is already stored in the first occurrent hashmap we calculate the substring lengths on the Fly and app dat the max things variable without storing anything thus we achieve constant space complexity this is the end of today's challenge we practice the use of hashmap and do space optimization based on our observations I hope you enjoy the video and as we close out the Year I wish you all a fantastic start to the new year happy coding and happy New Year
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
208
Ajay Ko Hello viewers welcome back to my channel doing great history subscribe To My Channel Please eclipse subscribe week don't playlist ka various categories such problems true religious programming subscribe half-half problem deposit from description subscribe half-half problem deposit from description subscribe half-half problem deposit from description video problem vids tomorrow morning example governance try tricycle Unmute raha suicide note in more return gift veer the robot veer will not give you all subscribe pandu looked so let's give idea before getting into like what is triangle 261 so let's try to understand the native with right subscribe this All The Amazing SUBSCRIBE OUR CHANNEL SUBSCRIBE SEARCH AND SUBSCRIBE TO LUT THE ARE SO AGOSH PRAKTYA VIRVAR KO SUBSCRIBE LIQUID SAMBHAV HAI A TO 58 RIGHT 200 FEET ALL DISTRICTS WERE TOLD THEM THAT WE CAN ACHIEVE DANDRUFF PLATFORM TO THE AUR NAKHWAH MABIR WA AND SUNA SUBSCRIBE OUR VIDEO Search Operation President A And Peace Also From Family Soft Lips To Understand How Much Time It Will Take To Search And How Much Time It Won't Be An Incident subscribe The Elements Already The In The One More And More So During Subscribe Plus One Some Log In Plus Minus Plus log in the temple run * log after inflation at that temple run * log after inflation at that temple run * log after inflation at that time from per just for insulting news printer amazing channel ko subscribe and subscribe number off hello friends my search during this time plus one string bread 100 the same quantity will be plus one side And Similarly States Will Have To Go With All The Subscribe And Subscribe The A Simple Technique Shweta In Health Channel Subscribe Now To Receive New Updates With And Not All Rights Reserved For A Log Of Taking More Complicated Love Of Langurs Secretary And Subscribe Must A Verification Subscribe Now To Improve Dash Apni Se Ek Rifle Board Swar Infection Searching And Starts With Screamid We Want To Go To Technique Called The Prize This Fool Video subscribe and subscribe the link for detail view Video * Gender * link for detail view Video * Gender * link for detail view Video * Gender * Video Share Subscribe Now Video by This Problem Subscribe Share And Video Boys New Year Duet Song Tune Stand This Problem Value Video I Have Created Equal Uie To Give The Complete Description And Understanding And Tried To Give And Send Them With A Single Tap Ki Sona Getting Into Subscribe Our Video Soft For Extra Oil Short Tricks The Amazing Subscribe Kar Lu Subscribe Complete The Subscribe Know No Know What Will Not Look At This Place There To Denote And Would Solve Width Is Particular 9828 1415 66 Withdrawal Soft Notes You Are Seeing You Are You All Subscribe Like Behave The Set Up Sid Mein Sid Love On Aa 100 Basically When You Are Creative World Setting Award Will Know How To Live With To Do Subscribe Share and subscribe the Not Tree To All Who Want To Speak Even Dash Open Please World End In This Just For The Validity The Dish Singh The Characters With Attributes It Will Have To Subscribe 159 A Plate Meter Technique Problem In The Back 222 Special Guest Left For - Movements That Special Guest Left For - Movements That Special Guest Left For - Movements That You Will Be Able To Let And Apply APL Why Do Subscribe To Any Point Where Is The Point You Agri then to sq mt mode atom aaj ke is youtube made to destroy defect word specific 653 mind only showing the jo points warehouse data fake and if point fennel 5 grams in these cases points 28.7 with vidya 125 you have all the three 28.7 with vidya 125 you have all the three 28.7 with vidya 125 you have all the three for internal quality worthington More One Morning Duty World In Witch Distic Sexual Via Madrasah Where One To Do It Product Code To A Good Night Remind Please Do And Avoid Loot Lo That Solid Light Jumping Record And Suna Assigned Black Class Trying And Vwe And Android Sudhir World End That and when we in these conscience want set the world end to forms and time positive Video subscribe our Channel subscribe and subscribe And subscribe The Amazing subscribe and subscribe the size of this on a basis vision problem I am now not liquid so very nice all points 1202 subscribe to the 96699 a the insult suvichar was with one word sorry eid par giver khandhe non it is not withdrawn its not subscribed not to 99 that i will go through the world emperor idol gotra-pravar length and c ific peel gotra-pravar length and c ific peel gotra-pravar length and c ific peel Director Not Mean Way Se - subscribe like subscribe comment and subscribe the Video then subscribe to initial hui hai ball central current notes right and where going to the world limited this app is 0 se sunao checking point meaning this point is not solved we will Decide what is that was my password on withdrawal - The Video then subscribe to 8 - k rates of birth samayne between 020 8 - k rates of birth samayne between 020 8 - k rates of birth samayne between 020 668 basically and take off vigor and get from this - 1000 500 basically Thursday to be id from this - 1000 500 basically Thursday to be id from this - 1000 500 basically Thursday to be id 108 and subscribe difficult verify the character of So Citizen Half of Rover's Software Great New Types of Tribes in the Next 100 Years However She Should Not Only the President The President Said This Point to the Point And Neither I Will Be I'd 1st Id Holders to 10th We Real Science Paper * * * 10th We Real Science Paper * * * 10th We Real Science Paper * * * Are Next Is Peya Hai Weight Study Andar Se Paun Inch 9 to subscribe The One That Operation We Were The World And It's True Or Not But Complete The Functions Don't Suna Lagao And Withdraw Subha Very Similar Doing Very Similar To were that the election commission was in try this oil pure current travel abroad and ashwin more 180 points up b id on thursday that out opinion with caste farmers short period election electrolyte think thoughtfully subscribe thank you speak only absolute gold 20202 egg not really 109 points in Do n't See Research Institute Egg Next Place 2151 Speed ​​12.48 Destroy Obstacles Difficult 3330 Speed ​​12.48 Destroy Obstacles Difficult 3330 Speed ​​12.48 Destroy Obstacles Difficult 3330 900 to 1000 Torn Subscribe Thank You All Subscribe To That And Girls And Devoted And Sot To Check Weather Difficulties But It's True Or Not To Plow Half of what happened was your pattern death note cut or searching for app word verification marking 1.28 not for app word verification marking 1.28 not for app word verification marking 1.28 not effective work in the middle of wave fight election will be spoiled published in award and captain web search reference just didn't dare and offices local Bodies torn through then return middle aged person subscribe and subscribe the Channel subscribe The Channel return gift from Dash Lu subscribe in a reader an athlete top electronic with date fix rate subscribe per student subscribe button to make you for watching my video and subscribe thank you So interest all here forward to improve and create one Adhere to start with sop for this particular Gautam will be going through A 's members body and actor George 's members body and actor George 's members body and actor George Sukmal Jain how much rate 12% plus one log in Sukmal Jain how much rate 12% plus one log in Sukmal Jain how much rate 12% plus one log in plus one should desist only the Number of elements in The Video then subscribe to the Page if you liked The Video then subscribe to the Page है लक्की पॉलर्ड ने क्या द टीम कम पाले पॉलर्ड ने क्या द टीम कम पाले पॉलर्ड ने क्या द टीम कम पाले अद्भ एंड बे डे कर दो है न शो है है है What is न शो है है है What is न शो है है है What is the space contact a request for This Right Leg Ko Bank Parichay Ameer Wa Saunf Insult 51535 Where Trying To Create A Node Where Is The Name Of A Place Where To And Complete Try For All The Favorite Suhawai Nirakhyau 606 Subscribe 945600 Subscribe To A View Of The Great Only Thirteen Pirates Of the number of vinod cigarette is active little dhar distic number of characters that source at mid length hai co tight subs wear look net speed kam sakti thi so is the average length subscribe it person setting only thing e av attacking dance Online More 108 Ambulance With Thanks To Create Shyam Different From 999 Sure Thanks For The Request Of Regular Use Fuel Subscribe And Subscribe The Video Then Subscribe To Main To Kam Stand Specific Alarm And Functions Per First And Misunderstood Used Only In The Choice Of A Great Song Play Again Beloved My Mother Always Be That Easy-to-Understand Agreeable Questions Easy-to-Understand Agreeable Questions Easy-to-Understand Agreeable Questions Posed by a Mother Comment Section Below the Video A Posted to This Tricks Opposite Read Some People Jagged Outward Author Khayal Daljinder Darshan 100MB Posting From This Video on Words with Java Code and Direct request you to find different for different subscribe To My Channel Please subscribe and Share Friends please like you will be notified about all my videos for watching problem
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
1,846
so hello people so today we'll be solving need Cod equation 1846 that is maximum element after decreasing and rearranging and in this we are given a integer ARR of positive integers ARR perform some operations which can be zero also on array so that it satisfies the condition that the first value of the element in AR must be one and the absolute difference between any two adjacent elements must be lesser than or greater than less than or equal to one uh in other words that absolute value of a i and the previous element that is IUS one should be less than or equal to 1 and then and for each I where I will be less than or equal to 1 less than equal to R less than length absolute X will be ABS X is represented as the absolute value of x okay so what we can do we can perform any two oper operations that are we can decrease the number we can decrease any element of RR to the smaller positive integer and we can rearrange the elements of a in any order and we have to return the maximum possible value of any element of the element in the a after performing the necessary conditions after performing necessary operations and that satisfies the conditions okay so now let's move towards the explanation of test cases in the first test case uh we are given that this is our array that is 1 2 to 1 one to one and this can be rearranged as 1 2 then two again and then one because in this case every two consecutive elements have a absolute difference of one or zero only and in this the maximum possible value is two okay and in the other test case that is 100 1 and th000 what we can do is we can rearrange first that is one and then 100 and then th000 okay so after this uh we have just rearranged the elements and after this what we can do we can make 100 as two and we can make th000 as three and three will be our answer because it is the maximum value in the particular array similarly in the case of 1 2 3 4 5 it is already uh the absolute difference of any two consecutive elements is less than is one only so the output is five because the maximum element present in this is five okay so what we can do uh we have to observe a few things in this question so firstly that what we can do we can start by sorting the array so firstly what we'll be doing that we'll be sorting the array and then what we'll be doing I'll be setting that my maximum value can be one okay because we have to start uh that it is given that our question must our uh like after rearranging uh it must start with one the first the value of first element in ARR must be one okay so what we can do we can set the maximum value as one and then I'll be iterating over the array from I = to 1 to I less over the array from I = to 1 to I less over the array from I = to 1 to I less than length of the array and then what I'll be doing uh I'll be setting Max will be equal to minimum of my array I or my Max + one okay so here uh What uh or my Max + one okay so here uh What uh or my Max + one okay so here uh What uh we can observe is that let's say uh and at the end I'll be just returning uh okay uh sorry yeah and at end I'll be just returning the maximum uh return Max okay so I just explain that how this algorithm will work so let's say in the first case we in the test case of this that is 100 1 and th000 okay so firstly what when we sort we get answer as one and then 100 and then th000 okay so after this what we can do we'll be uh when we'll be traversing the AR so first we'll be getting one and after that we'll be checking minimum of AR I that is one for this index and Max plus one that will be two so I'll be setting my Max variable as two then I'll be moving to this index then here I'll be checking with Max + 1 then here I'll be checking with Max + 1 then here I'll be checking with Max + 1 that is 3 and th000 the minimum of 3 and th000 is three so I'll be setting my Max variable as three and so for this particular test case my answer will be three similarly if let's say there is no one present in the array let's say the array is uh 5 3 4 2 this is our array and in this case after sorting it will be look like uh like when we perform the sort operation it will be like 2 3 4 5 and then what I'll be doing I'll be setting my Max will be equal to one then for three I'll be checking with one and two so I okay uh let me just add this to a new white board yeah I have performed the Sorting operation uh and after this that is 2 3 4 5 what I'll be doing I'll be traversing from this index and my Max will be currently equal to one so at this point I'll be checking with 1 3 uh 1 + 1 minimum of 1 + 1 and three that 1 + 1 minimum of 1 + 1 and three that 1 + 1 minimum of 1 + 1 and three that will give me answer as two Min and here my Max variable will be updated as two now while moving to this index so again it will be compared with 4 and 2 + 1 that is three so it will be 4 and 2 + 1 that is three so it will be 4 and 2 + 1 that is three so it will be returning with three now Max variable will be set as three and in this case uh it will beared with 3 + 1 that is it will beared with 3 + 1 that is it will beared with 3 + 1 that is 4 and five so I'll be my minimum will be four so my Max variable will be set as four and this will result that the maximum possible value in this array could be four okay so now let's implement it h firstly aray do sort AR then I'll be setting my Max equal to one and then for an i = to 1 I we not be one and then for an i = to 1 I we not be one and then for an i = to 1 I we not be changing the zero index because it is already given that the first element has to be one so my current maximum will be equal to one only l uh then i++ and here equal to one only l uh then i++ and here equal to one only l uh then i++ and here I'll be doing my Max will be equal to maximum m. Max uh okay math do Max oh math. sorry not Max sorry uh Max + Max sorry uh Max + Max sorry uh Max + one and a r i and after that I'll just return it ma okay so now let's run it and it gets accepted now let's submit it and yeah and it gets accepted okay so this was it for today thank you for watching
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
1,624
Hello and welcome back to our channel today we are going to solve lead code question number 1624 which is about finding the largest substring between two equal characters so without wasting any time let us start to understand this question so first of all in this question we What is it said to the people? We have to find out the substring such that both the characters that is starting character and ending character should be same for example. We first look at example two. What is it saying? In example two, we are given a string. a b c a s a b s a its this character and this character is the same as these characters are the same we have to return the size of substring here okay which is equal to two in this case Similarly if we see the first test case it is saying a and a These two characters are equal but there is no substring present in between, so what is its size, it is zero and if we look at the third example, then there we are given a string in which no characters are equal, so like this In case we have to return -1 then let us see In case we have to return -1 then let us see In case we have to return -1 then let us see how do we implement it using code so we can do it in two ways else iterative beyond which we run two loops one from the start and one from the end and check whether If both are equal, then by substituting them, we can return the position, sorry, we can return the size of the substring, fine, but we are not here to do that, we are going to solve this using map, so if we talk about map. First of all, let us see how this can be solved, so here we can do this, create a map, okay, what can we do with all the characters in it, we can store the index, okay, we can store the index. For example, we take the second example of ABC A so ABC A map, we are storing its index in the keys, so first of all when it will iterate, its first index will be ah 0 1 2 3 so it Will be like 0 1 2 And When What will we do? In this, when the value does not exit in the map, then we have to store it and as soon as the value exits, then the key which was already present in the map will be added to it. Will subt ct the value where it is appearing again fine means like we have created this map we have a pe 0 b pe one c pe two then as soon as we get a at 3 then what it will do is it will go to the map and search ok a It's already there, what is its value, so what do we do? 3 - 0 - 1 As we so what do we do? 3 - 0 - 1 As we so what do we do? 3 - 0 - 1 As we have to return the size so it is important for us to see the subtitle. Okay, so this will give us 0 because we have to get the size, neither micro nor We will have to do this because if we do not subcut the array then the size we will get will be from the starting index but no what do we need the size of elements between this. Okay so that is it and what will we do in this. Again and again we will return the maximum value of whatever size we get. So now let us move on the screen and see how to implement it. Let's code. So first of all what we will do is int n. Let's take s is equal to the size. This is our size. Let's take a variable int maxi e - size. Let's take a variable int maxi e - size. Let's take a variable int maxi e - 1. Okay, because we have to return -1. Okay, because we have to return -1. Okay, because we have to return -1 when we can't find any such sub string. Okay, we can't find the largest sub string. Okay and then after that we will take the map character type and int type let's call it m ok for loop int aa e 0 to aa e a lesson aa p then after that we will find that element in the map Okay if auto At this place, we will store the index of this value. Okay, and if we get it, then we will take an int answer. We will store a variable in it where we have got it now minus the value of the place where we had got it earlier. Its value was stored in SI. Okay, that was the index where we got it earlier. Okay, where did we get it earlier? We stored it in SI. Okay, and we will move it because we need to find out its position. This is position indexing, we mean we have to return its position values ​​right return its position values ​​right return its position values ​​right then after that we will take max, we will take maxi, same process is equal to max of answer and maxi, we will check it as many times as we have got. Meaning, we are checking the distance of all the races wherever we are meeting, so we have to return this maximum distance, so we will keep it and will keep doing this incorrectly and we are returning maximum. I hope this goes right and no one will say anything after seeing my submission because I have made this video for at least the fifth time. Okay, I have n't forgotten something, it doesn't seem like it.
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
962
hey everybody this is larry this is me doing the bonus question hit the like button hit the subscribe button draw me on discord um yeah so as you know i do an extra problem um because i usually have done it let's see if i get one because usually they give me i try to do a random question i haven't done before hence the to-do and haven't done before hence the to-do and haven't done before hence the to-do and then we'll see how that goes hope everyone's having a great week um i've been just planning on going on a turkey trip so definitely if you have been turkey or have been in turkey or you're turkish leave me some tips in the comments or come to discord or instagram whatever you like we'd love to hear from you anyway today's prom is 962 maximum with ramp so a web avengers and i sub j where i is greater than j well i is less than j whoops and okay so vamp is i minus j okay maximum width so five and one the riff is wait it's index five one and five not the numbers one and five okay that makes sense so basically what i want is for every left for every j right we have to find an i such that this is the case but for i we can hmm how do we do it i mean it shouldn't be just binary search in a way because basically you want the left most number that is smaller than this number right is what our repeated query would want um yeah and i think this is one of those um i think it's one of the mono stack problems i think maybe on mono q maybe no mono stack um because the idea here is that you um did and i'm just trying to suss out a little bit but there's some um uh invariant properly where okay so what's this is the number smaller than one no is the numbers more than zero no it's a number smaller than one yeah it's zero okay that's good is the number smaller than nine um then here that's the thing where is that you go all the way to eight maybe that monostack here doesn't make sense actually um but then you still have all these numbers the one doesn't you know the nine doesn't improve anything so then the four but then i think this becomes because all i mean you're almost like a binary search and it's going to be a decreasing sequence because it doesn't make sense because every number that's for example this one well this will never be the answer to any query to the right and that's and i kind of guessed manual stack but maybe i'm wrong but the idea is actually quite close is that the one will never be the right answer because if you choose this one you might as well choose this one right um or yeah so this one would never be the right answer nine will never be the right answer for that way at least it will never be a correct i and then this four for example would never be correct i zero would never be a correct die and then that's it right um and the idea is that well if you have another smaller number so let me write it out here if you have another smaller number let's say you have to say negative five i mean i know that this is positive numbers only are not negative but you know this is just it does it shouldn't matter um you know and here well the negative five is the only one that matters right and then because of that then now we can remove all these numbers because negative five matters because if you get a number later that's negative five or bigger or between negative five and negative z or negative five and zero then it would have you know this number is the answer right um and in that sense this is going to be just monotonically decreasing secrets and it's not the mono stackers don't need to pop but it's the same idea and now you could just do a binary search on it um this is a medium but i find that this is a very hard medium unless i'm missing an obvious solution so hmm yeah so let's do that then so here we go i'm gonna call it um naming stuff is harder so yeah so let's just say prefix then and then for i x and enumerate nums um so basically now we do a binary search what do we search on x right and because we can assume that this is monotonically decreasing then when we binary search we want the number yeah we know and we know that the number that is um this number or bigger will be that number right or like it would have to correct index because by definition if you go if you could go more to the left you would have and it would have been a smaller number so okay uh yeah actually one thing that i did make a mistake on is i didn't look at the constraints because if this is n squared vote then it you know we should have just done an n square maybe uh at least in terms of you know like i mean i guess you don't have to or you know you should still upsell but inferior in the contest that's what i would do um but yeah okay and here i'm gonna write this in a little bit of a weird way just because uh it's easy to binary search from left to right from decreasing from right to left or you do like negative numbers and that's just like you know so i'm gonna do something weird and make it attack this is so that i can add from to the front yeah i don't know if this is a good idea but anyway so yeah so then prefix dot uh or binary search dot left because we want the number that's uh the same and then we just have x and negative 20 or something like this negative one is fine maybe i don't have to go then this is index right if index so yeah so if index is less than length of prefix then we know that oh we have to keep track of the best variable which is uh we want min minimum right so let's just say negative infinity i guess best is equal to zero because that's what we return anyway okay fine um if this is the case then we could get the index which is at prefix of index and then this is we want the second element so yeah so that's the actual i oops i guess maybe i'll just use this as j right and then best is to go to the max of j minus i right and then now if so now we try to figure out where we put this number in and if length of prefix is zero or prefix of negative one the smallest element if this element is bigger than x then we appen or we oh i guess i'm so used to doing it like a normal way but i think we reverted away for this reason so yeah okay so this should be zero then um then we uh append left of x and j right and this is so that it can be used in the future and i think that's pretty much it maybe i have some typos but i think i did ideally uh an idea this should be right i forgot to like i said some typos now hmm why'd i get five okay so one two uh i is zero well this is clearly not right oh hmm maybe i did just a little bit weird let me think about this for a second um the way that we did is a little bit weird with the binary search so that's why i have to double check but of course the index would give me the number that's bigger um okay so we want to bisect right and then minus one i think that's maybe what we want still wrong answer huh so because 2 0 1 2 okay that's right 3 is 1 that's good four is one five is one okay so this one's good and then now the second answer uh why are we getting it wrong so we have these four it doesn't do anything and then this one so this should print a four and then two but then it goes for three instead because because of this thing so this one should be infinity instead i think because we changed it a little bit and then it the bicep left and the bicep right doesn't mean anything anymore because it's a tuple so it matters about the second a little bit more but i think now this is good yeah okay it's a lot of new ones with stuff but i think this is okay so yeah so now let's give it a submit but this is kind of hard to be honest uh i mean it's not hard but it feels like it's a little bit hard for a medium but i don't know if there's an easier one but yeah this is going to be n log n what if there is a i wonder if there's a of n solution but yeah this is going to be n log n time o of n space for the prefix and i did implement this in an awkward way i hope that's okay but um but yeah that's pretty much it let me know what you think i'm so tired for some reason you know i slept all day but uh stay good stay healthy to good mental health i'll see y'all later and take care bye
Maximum Width Ramp
flip-string-to-monotone-increasing
A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`. Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`. **Example 1:** **Input:** nums = \[6,0,8,2,1,5\] **Output:** 4 **Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5. **Example 2:** **Input:** nums = \[9,8,1,0,1,9,4,0,4,1\] **Output:** 7 **Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1. **Constraints:** * `2 <= nums.length <= 5 * 104` * `0 <= nums[i] <= 5 * 104`
null
String,Dynamic Programming
Medium
null
1,403
Hello hello friends today I will discuss question from greed kotputli contest 181 problem number nine updated on a result the record date sum of all its elements system temple run ki and 152 rds ki and I can assume that no plus 619 plus element of video plz subscribe Do How To Worship Can Do But Justice Chaudhary Co Antique Item Elements And Will Take All The Best Culprits Will Find Doing And White Widow Of Elements Of Obscuritism Subscribe To A Story The 500 Intel Co Hospital Half Inch And Birthday Is This Morning Only Hours Great ho gaye hain e will do a total solution for e I am Jain a for finding and 10 top 10 subsequent remedies pimple fluid tools and with that short forms updated on 200 comes forward and anti oxidant Vitamin E that is nice note sorted food It means the best elements for justice and equality of all Dual app's 12th art festival on that name as per the gate some tips qualification kushwah indore ma ki this huge lottery subsequent potato is great blindly you same total subscribe to that witch tells what Is the name of the evening elements which deals pe karna hai ke din jaisa to record exist ke inside ji bega aao that this small one that Panchkula destroyed all the way a constant loot norms in the napkin retention submitted you can see that distance logistics 11.1 The election is on Thank you for watching my video 11.1 The election is on Thank you for watching my video 11.1 The election is on Thank you for watching my video and minute
Minimum Subsequence in Non-Increasing Order
palindrome-partitioning-iii
Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with **minimum size** and if there still exist multiple solutions, return the subsequence with the **maximum total sum** of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be **unique**. Also return the answer sorted in **non-increasing** order. **Example 1:** **Input:** nums = \[4,3,10,9,8\] **Output:** \[10,9\] **Explanation:** The subsequences \[10,9\] and \[10,8\] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence \[10,9\] has the maximum total sum of its elements. **Example 2:** **Input:** nums = \[4,4,7,6,7\] **Output:** \[7,7,6\] **Explanation:** The subsequence \[7,7\] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence \[7,6,7\] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 100`
For each substring calculate the minimum number of steps to make it palindrome and store it in a table. Create a dp(pos, cnt) which means the minimum number of characters changed for the suffix of s starting on pos splitting the suffix on cnt chunks.
String,Dynamic Programming
Hard
1871
6
Welcome back tu de stylish kadhar hope you all are doing well so today we have question complete and one will be waiting which will tell us how many days it can be. Okay so it is possible daily we have to do jikjack conversion in it. Meaning, converting the string zigzag and writing it down means what will be its conversion, like if you look at the example given here, we have a string, okay, in this example, if we see our zigzag. The path is like this, first if we start from here, we will go down, then we will go with this position, you will take it to the right, okay and after that when we reach the top, we will go back down from there. We will come back, it will be like this, meaning in this example, we have three rows being formed, okay, so one row will be the first one, then the second row will be this and the third row will be this, okay, we understood this, but how did they write it down? Liked, if you look, what do I have? Let it be done, zero will come upon it, this one will remain, then whatever will be my next letter, okay, if there is P, then my P will come here, okay then after taking the next rule, what will come after P, I will come to A, so it will come on top. Okay, now what will happen after this, my cry again from here when it has reached the top, again it will come down from here, then again it will go down as one, then again it will be done from the same, okay by doing this some parts will be made, okay we have in the last Whatever will happen will be of this type, then what will be our answer, then how should we write the answer, we have to write this word first, okay, after that we have to write these words, okay, so this is the description of our question. I think you must have understood the question that how what do we have to do so if we look at its solution approach then what can be the solution approach then for human we have like this string given is ok what is the number of row in it We have given number of from is three. Okay, so we can do any type of data structure. Inside it, we can do anything like that. I have given that I have given the array list of the list of characters, I have given that. I have to do that, okay, by doing zero van and tu, three rows will be made, okay, now what will I do, according to this loop, I will apply it, like I know how much to walk in one number of rows, okay, so what would I do? I will put a four loop, okay, it will go till where I am, it will go from I to whatever row number it is, okay, the name is Rohtak, it will go, okay, what will it do after that, whatever position will be inside it, its gate. Will position it, after that I will add this character inside it. Okay, I have added gold. Use it in such a way that it will work in this conversion. Okay, I will add this character inside it. Jack I = will add this character inside it. Jack I = will add this character inside it. Jack I = What will happen to my name which will be 'Ro'? What will happen to my name which will be 'Ro'? What will happen to my name which will be 'Ro'? From there it will run in reverse like it will go till zero, okay by doing this I will give its answer in the last, so let's see it inside our code, how it will be implemented inside the code, so let's write its code, so first of all I will give this here. Let me create a release, which will collect my conversions, okay, erelist, its type will be character, okay, mine will go, sorry [ sorry [ sorry New Era list, okay, so here first I create a lance which That it will tell me at which position of the index the value has to be taken, okay, it will be done, okay, so first there will be a phone loop, which means I will go down, meaning it will come from down to the bottom, okay, then I equal you, my name is Rose. It will go till it will be fine i plus is done ok now what do I have to do like this I have to go from down I have to go in you have to go in the right direction ok so for that I will put another four loops here ok one more For loop will be ours, its starting will also be I = its starting will also be I = its starting will also be I = where will the name run from, okay this will be the first zero here, this will be van, this will be our 2, okay but which will be our p, what will be this, van means how many of our rows. Three are given, if Sam does two mines in three, then we will get this, okay, and how far will it go, as long as our i = 0, and how far will it go, as long as our i = 0, and how far will it go, as long as our i = 0, okay, i - - will be and give, we will okay, i - - will be and give, we will okay, i - - will be and give, we will return to this here, f get i and add inside this. Okay, C, we did not remove C, now we remove C from here, take plus, okay, so what will happen to us is that the photo of the first like will follow this part, okay, the second one will be a loop, so this thing will go or It will go till P, okay, after P, then it will come back and the next one which will be started will go to U. By doing this, it will get the gate, okay, but if we look at the last one, then our four loop is here, even if letters get reduced at some point, it will also be below. If it goes, it will give an error, then we have to fulfill the condition here, we take pe and s dot here, whatever is the length of our string, if it is our length, then only whatever is less, this loop has to run, okay, let's do it from here also. Let's take our aaj dot lan, we will convert it into string and return it, so for that I create a stringbuilder or this will be our stringbuilder sp dot new stringbuilder, okay this is stringbuilder, we will call it length, sorry, size from one. It is in this and I Plus is okay, we will take the character inside this, our code is successfully run, so let's submit it, our code is also successfully submitted, okay, the screen is loading till now, if we look at its time complexity. If we talk about time complexity, what is the time complexity? Look here, we have put one loop here, okay, how many times will it run? Our on time is set to N, what is the number of days, okay, second, we have put a four loop here, how many times will it run? It will run on number of days, it will run on daily basis, okay, its will be on now and its will also be on ours, it will also be on with number of days, but a wire loop is sitting here, how many times will it run on our Om Times M, what will happen to this ring of ours? If we talk about the space complexity of this code, then we have created a list of erelist here, it is okay. What is the size, here is N, okay, how many elements are we adding inside it, we are setting our M element inside it, then what will be our space complexity, that too will be on the cross, okay, something will be formed in it, okay, if Let's generalize like, our touch, what comes out, touch comes, O N cross M, okay, and again, what will come from SPSC, what will come, that also comes from N cross M, okay, so like, can we generalize it a little? Like, to generalize, if we look at this example, here we are doing OM cross N, so can we convert it into OM plus N? Like, I have put a for loop here, otherwise what if? Could it be something like this, we had the old code, so let's convert it into our new code, like we did the four loop here, we will replace it with the direction, okay, so like, I will remove this hard from here. Now here I make it in one ID direction which is my van is ok one will be my current row ok this camera is zero ok understand the question that how will we work in this then we will work in this type of pattern so ours is something like this It will be like, we started from here, okay, the first element, whatever it is, will go to our zero row, so we have kept zero here, okay, next whatever it will be, what will be ours, then it will be first, then it will be second, okay, so after that it will go to your like row. When he came to zero, then the van came, then you came, my current will be raw, what will I do inside it, in the current ROM, I will get plus done to whom is the van, okay, I will get plus done to the van, who will be my direction, okay, let's make a call. For making the look, first keep the error of one character in it. C is fine. How far will it last? As far as our S is, it will last till the number of characters inside it, so let's convert it into character S. You convert it into character. It's done, it's done, convert it into character, okay, if I discuss it in front, I like the one who gets my current, okay, stop the current, I have got the information, what do I have to do in this, I have to add my character, okay, I After adding this, what am I doing after that, I am updating the value inside the current row, okay, current row plus equal tu, my direction which I have set, that direction has been added, okay, now what do I do after this? I have to like this one which cried when I saw it, so it went like this, okay, I reached here till you, now after you, what do I have to do, I have to go back in your direction, okay, when do I have to go in the direction, when my like which number, which Row is the one with numbers, if that minus one is equal, then it becomes equal to the current row, okay, if it is equal to the current row, then what do I have to do in that case, I then have to move in the opposite direction, okay then? Like, when will the time come to change my direction, then it is okay here in Like, here I have put the condition current row, if it is equal, you are equal, which is okay with the name row, then its mines become equal to one. In that case, what do I have to do? I have to change the direction. Okay, I have come to know how the direction will be changed. Like me, if you see, I had this position, zero, this position was one, this position was you and what is this position, van. Okay, so like, this is my current position. Okay, this is the current position. Okay, what do I have to do with it? I have to mine it. Van is okay. It's okay to do -1. I have Van is okay. It's okay to do -1. I have Van is okay. It's okay to do -1. I have reached the position from yesterday. I have reached near P. Then give it. Who will I go to speak? Who will I go to? Like what happened to me here? Van was done okay so after this I went in this I did -1 so what happened reached 0 A okay so did -1 so what happened reached 0 A okay so did -1 so what happened reached 0 A okay so like I here But what do I do to this which is my direction -1 done, now what happens when I have -1 done, now what happens when I have -1 done, now what happens when I have reached near A, okay let's see here, my friend, I have reached near A, now what should I do from A? If I have to go to P and go to I, then in which room will it come, it means that I have to go to the zero one, after that how do I have to go down, okay, I have to go down, which is my direction variable of mains, which will be the direction which is variable. What will happen inside it, what will be its direction, will it become Van, meaning now we will add the Van value inside my current row, okay, so like, let's adopt this also in the code if my current row has come if that. What is equal tu what is zero then what to put back in the case close the direction Okay so this was our code so let's run it and see how what happened inside it so if you inside this Okay, all three have been successfully run, but if you look at one thing inside it, like we have any string, whatever string we have, it is okay, there is no row inside it, still our code will work like that current row. If he finds out, he will find it out, like number of roses, what will happen, he will have zero, if he does zero mines, what will happen, then he will get -1, zero mines, what will happen, then he will get -1, zero mines, what will happen, then he will get -1, then he will get issue in the case, so for this we will have to put a check here, okay. So if my number is daily, then the number is daily, if they give the lace, what are you equal, then it will be returned from here in the case, okay, why this condition is imposed, the check is imposed because we have kept it here. Okay, if it is the current row, then there are any values ​​inside the current row, then there are any values ​​inside the current row, then there are any values ​​inside the current row, like ours, it will start from zero, okay, what is the number of days, do we have van or zero, okay, if they have zero, then it is in the case. What will happen -1 If we do all -1 in 0 - 0, what will happen -1 If we do all -1 in 0 - 0, what will happen -1 If we do all -1 in 0 - 0, what will happen -1, he will come to check on it. If there -1, he will come to check on it. If there -1, he will come to check on it. If there is -1 here, then he will give an error is -1 here, then he will give an error is -1 here, then he will give an error to himself, he also handled the thing as his own. Okay, so again his. When we run this, when we open it, this code has also been submitted. Like, if we talk about time complexity and space complexity, then we had this old loop, like this was on, it is okay in the old times, here which There was a loop, it was happening in Om Cross N, but what will happen at this time, this will be our Om, so I, the total time complexity will become something Om plus N, okay, so this will be our today's code, if you like our video. If you liked the video then like the video. If not then subscribe the channel because such videos keep coming and then see you with another video. Till then bye
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
545
Hello hi friends welcome back cover sleep today we are going to solve lift problem 878 boundary of binary tree this problem was previously found by Google and Amazon as you can see and here 100 before but after looking into the description of just want to mention that my Channel Focus On Helping People Who Are Preparing For Coding And Java Interview All So If You Are Preparing For Coding And Java Interview Please Subscribe My Channel Na Interval Of Social Problems As Well As Frequently Asked Questions Were Raised By Big Companies Like Apple Amazon Google Facebook Microsoft And so many rate companies subscribe The Channel so let's go through click on the description to INR history written values ​​of its boundary in values ​​of its boundary in values ​​of its boundary in anti-clockwise direction on starting from root anti-clockwise direction on starting from root anti-clockwise direction on starting from root printed in Delhi roots loot boundary leaves and write than tree in order without duplicate notes so Common morning is that return of description year but basically water saving is the aa for example it's just one small example clear 21 A final tree which gives one to earth will have to returns the boundary harmony now the boundary leave returns basically 600 800 to 1000 this is The Boundary Office Binary Tree Craft So It Is Anti Clockwise Which Will Start From Root And Go To The Left First And Go From Like Leaves Like This And Even Go To Right Side Again Like A Specific Short Notice Board The Problems With It Give The Link Below you can go through the description in more details on this is not the problems assuring a to will take one with example like one bad read and I will explore new ways to address this problem and solve this problem please important problem which causes after bugle Amazon 100 Let's Go Through the You Know Approach Kavya-Kunj Approach to Solve This You Know Approach Kavya-Kunj Approach to Solve This You Know Approach Kavya-Kunj Approach to Solve This Problem Solved Will Always Be with Us in Three Parts Porn Sites One Part of This Problem Is Finding Lift Note Spirit and Boundaries for Example in This Case Loop 90 Tight Suggestion Lift Notes And After That Like Finding The Leaves 100 Finding NewsClickIn Yagya To Parts Process Right Because You Will Take Like This Loot Sub Tree Of This Root 100 And Will Find The Notes In Lips Then Tree Which Will Include This Not The Time Highlighting Share And This Will Bay Included Going from Direction Will Bay from Lift Toura Flash Lights 500 to 1000 Doctor Dead Again Will Have Part 2 for Finding Leaves Off Right Side of the Root Basically It's Overall The Terms Leaves Means More Share The Leaves Right for Right Side of The Right Side Subscribe And Again The Order Of The Rings Rui Maintenance Going From Left To Right Solid Will Go Lyxegy [ Lyxegy [ Lyxegy All The Best Updates Will Discuss Roop Observe And Third Front Will Be Finding The Right Side Element Lights Of Right Side Element Tubelight Decided to right side border basically are you can see this tree fennel and 1020 This is the way we are going to approach problem in three different parts will implement free functions one on it lift boundaries for bride boundary and one function will implement for the right side and Will reduce the function for lips string and write summary of hundred show the teacher approach poetic solve problems or latest like looking in which of this point in more detail and removing this again and they can reduce decide 100 so you can see some facts you Can See And Here For This Will Be Adding This Fund Into Our Result List Vikas Posting Hui Always 700 Hai Aadha Mintu Se First Hui Always And Drut End Din Hui Hata Start Giving Lift Direction Minutes After That Will Go To Sleep Direction Will First Name Wedding Life Boundary Elements of Welfare Divyang Left Side Clear and You Will Attain Here Right 1510 Hui Idea So After Hundred Fifty and After That You Have Taken It's Own This is the Sequence From It And So You Can See Wherever I Find No Where You Left of 30 The Little different tho its loot will win this will not be added to our left side boundary show latest look into the implementation for this left side everything for the function name is travel travels loot where passing through water left and where passing result list is the List But They Are Going To Return And The Top Five List For Indian Students Look At The Travels Boundary Function Click Sofa It Is Recursive Function So Will Have Valid That Middle Side Fruit Is Equal To One Will Return 20020 Case And What Will U Is Front Not Left Is Not Equal To Nights Basically Gift Delayed Left Side And Will Be Added Node In To Our Result List And You Will Go On Left Side Of The Node For Example Servi When You Go From Us Jahar 15Sau Absolutely 250 Tips De Raka Entertained And will go to taylor swift example is that is not left side wheel chair for right side is website in that case hui edward and will go on tour right side of the length of the note basically for example what is meant to say is this effigy of som Battery parties are not wearing this tree it's not here this part day after visiting 5828 so let's all Not Reduce Left Side Words Not Dare Shop In That Case Will Go On Right Side Dirty Politics Singh End User Can You Will Call Recursively On Right Side Andar Left Side Ego In The Middle Andar Left Side The Travels Just Want To Function And IF Oo Were Born on the right side will call you function inside the right side of the not correct swades and recursive function to find out the left boundary elements so let me just revert back now that sui have discussed already nadu and verified website element right 0 to no where to Find out the left no will take place loot saptari this loot will take and have to find the best all the lymph nodes going from left to right said this award function that is implemented and function is called as process lucent software will pass through not here end Again verily stretched end and basis basic such place same day birthday inverted sweet another wife wear's in doing slider in all driver st soldier school witch function reciprocatingly and left side den whole chilli 1 inch hui wrist par leaf modify your wrist Ali Snowden hui added into Your Earliest Years Otherwise Will Go On To The Right Side Saw This Kind Of Inorder Traversal Drought Which And Share Checking If It Is Life 102 For Example Now Fit Will Go All The Way Which Will Start From 0 To Reduce Chief Left Side Phase Begusarai From Various Benefits of Delhi Will Come Back Again From 258 And Again 2708 Vilas Us Loud 0.5 Inch Writing In Hair 100 Out Of 500 That NDA Double Tried So The Enemy Is The Lymph Nodes In The Left Side Of The Road With Too Many To Go On The Right Side to Find the Lift Notes Inside Right Side Members The Rights of Three and Power Lee Roads Will Find Out Bizarre Lift Se Time Highlighting Here How to Find This One Should Be Used in the Same Function Knowledge But What We Will Do Festival Hui Personal Rights Right The Roof Water It Will Pass Through Get The Right Side Leaves Right A So Will Know What War Want To Right Side So Will Go From Year To Year Liksesagi All Come From Suv More Than 150 Worli Strike Right Down The Year Sona Aerolite Day Se Ro That After The Kid Will Again Got Back Like This Developed Good Application Works And Little Again Phase Pendant 28.20 28.20 28.20 De Villiers Medicine 1100 And Mrs Is So This Is How You Will Find The Right Side Left Side So I Will Be Done With Right Side Listen Nau Have To Find Out Sorry Or Right Sandalwood Sunavai How To Find The Right Side Primary Element Is Forces Above That Implemented One Another Function Contest Reverse Right Boundary Right And Will Pass Form Dried 108 Similar To Leave But Nau Have To Find Out Right Side Boundary Right Shop In This Fight Wave 205 Roots Year Ender List A Result The Are So This Day Best Website Notice Request Owner Will Return Otherwise This Reverse Check If Not Right Is Not Equal To Nand Will First Travels The Right Boundary Right Clear Force Will Again Call Record Shiv Function Right Side Right For Example Plate Just Saw Basically Gift Were Going From This Hundred And Will Go To That And In Which You Will Go To Again Right Central To You Can Go To Right Side And Again Will Go To Right Side 2019 Left Notes For This One will not be held in to-do Notes For This One will not be held in to-do Notes For This One will not be held in to-do list now we will come back from this point it will come back clear and will 8410 that is liberalization and craft dad and inform forces will go back to the previous call rate to them a little drawer implementing right clear so Let's You Can See Your Calling For The Travels Rightly Pointed And Were Passing The Right Side Clear Saugandh The Call Will Come Back Again The Will Go To The Right Side Like Tags And After The Last Call Me Two Remedies To The Results Sexual 280 First Taste Ands In 210 That Is The Question Works And He Is There Is No Right Side These Days They Have To Inside Left Side And Check Again Hui Call Dysfunction Online Website Should Be Aware Of Implementing This Recursive Function And Theory In Implementing A Like Were Pouring In From In Function The Travels Right Boundary So Let's Speak Louder Recap Of What We've Implemented Some Very First Defined Ali Stuffing Teacher Day To You Are Going To Satna To Get The Boundary Elements And Fruits Dhanush And A Middle East Tune Otherwise Will First And Rude And You Will go under left side right left side primary element will look after that you will get left side leaves basically it and you will go on right side lips and now you will have right side boundary elements and right side elements have implemented secretary a date first element For it will come for that pintu burden less one wicket you have been created to enter and vitamin C the results year first 100 latest one to example that they have been discussing this example effigy twist see the results hui hai woh scene example so let's go ahead And Give Yours Now You Can See This Data Is An Answer Write Cancel 10 Subscribe Share And Subscribe Our Result So Let's Get Rid Of 80 Exams Looking At You Can Be Sorry 0 Bullet 500 To 1000 Actions Will Get Correct Result What Will Discuss Now Dry ginger and solution is working so latest Eurovision try example also just to make and that you know if you are trying examples for which can submit there that needle attack distant view of getting correct result you can see and here right 12478 912 4789 sure your getting correct Result Solved They Are Confident Question Submit Solution is So Let's Submit Saunth and Solution God Accepted by Liquid End User When You Can Solve Boundaries of Binary Tree Problem Which Caused by Google and Amazon Saunf Events and the Share Yudh Link of the Problem You Can Take a Look More Inside Description Site Explain You In White Detail How Implement Solution You Have Divided Into Three Parts Animal Man Calculating The Left Side Of The Street Light Powder Of The Tree The New Year Calculating Adb Left Side Lymph Nodes Right Side Effects And Right Side Boundary and Deaths Were Preparing for Answers Graduate Level Two Year Feeling Tower List in the Way Debt Boundary Elements of Birds and Were Returning and for So This is What Approach 125 Share Yudh Ko Dal Song and Migrant Workmen Act on That Also If You're Preparing For java j2ee examination hall interviews and unit telephonic interview sadan please go through my channel playlist sunao i have not good to example shoulder explained in details along with java code and you know the details when this bandhan song brings you can take a look at how To java code is also implemented have at least solution playlist de this address and can stop morgan harold examples from list code as well as land code which were previously bought by big companies like amazon apple facebook google microsoft and so many rate companies gurudev mute will give Good and different variety of problems like dynamic programming for your research different live stock select list the are list link is related problems related interview problems priority queue related interview problems all kind of different problems of these will give you really a good a supporter of what is Been Asking Them So If You Find A Solution Helpful If You Like This After Your Life You Like This Video Please Hit Like And Subscribe And Your Subscription Is Really Important To Years Papers Where Is The Video Can Reach To More People You Are Preparing For The Interviews And Job Interview Saryu Nadi Can Also Watch This Video And Get Benefited Please Subscribe And Thanks For Watching The Video
Boundary of Binary Tree
boundary-of-binary-tree
The **boundary** of a binary tree is the concatenation of the **root**, the **left boundary**, the **leaves** ordered from left-to-right, and the **reverse order** of the **right boundary**. The **left boundary** is the set of nodes defined by the following: * The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is **empty**. * If a node in the left boundary and has a left child, then the left child is in the left boundary. * If a node is in the left boundary, has **no** left child, but has a right child, then the right child is in the left boundary. * The leftmost leaf is **not** in the left boundary. The **right boundary** is similar to the **left boundary**, except it is the right side of the root's right subtree. Again, the leaf is **not** part of the **right boundary**, and the **right boundary** is empty if the root does not have a right child. The **leaves** are nodes that do not have any children. For this problem, the root is **not** a leaf. Given the `root` of a binary tree, return _the values of its **boundary**_. **Example 1:** **Input:** root = \[1,null,2,3,4\] **Output:** \[1,3,4,2\] **Explanation:** - The left boundary is empty because the root does not have a left child. - The right boundary follows the path starting from the root's right child 2 -> 4. 4 is a leaf, so the right boundary is \[2\]. - The leaves from left to right are \[3,4\]. Concatenating everything results in \[1\] + \[\] + \[3,4\] + \[2\] = \[1,3,4,2\]. **Example 2:** **Input:** root = \[1,2,3,4,5,6,null,null,null,7,8,9,10\] **Output:** \[1,2,4,7,8,9,10,6,3\] **Explanation:** - The left boundary follows the path starting from the root's left child 2 -> 4. 4 is a leaf, so the left boundary is \[2\]. - The right boundary follows the path starting from the root's right child 3 -> 6 -> 10. 10 is a leaf, so the right boundary is \[3,6\], and in reverse order is \[6,3\]. - The leaves from left to right are \[4,7,8,9,10\]. Concatenating everything results in \[1\] + \[2\] + \[4,7,8,9,10\] + \[6,3\] = \[1,2,4,7,8,9,10,6,3\]. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
199
138
Hello Guys Welcome To Reconsider Subscribe Point Question Adhadhundh Video subscribe and subscribe the Channel Please subscribe that team The Old and New Note Mapping Bhi Prevent Multiple Officer SIM Not Stopped And Two And Tried To Pray Jammu To Three And That Subscribe The Channel Ko Subscribe Do subscribe the channel thank you know subscribe button in the current 12 next point one dabangai a to update the next point to subscribe aap ko a vintageg the value of the new not seen its an update next point to loot dot next point subscribe to the Page if you liked The Video then subscribe to the Page Click A Simply Interview With No Golden Petal To Idi Of The Interview Appointed subscribe and subscribe the Video then subscribe to Quinton Day When Will Place In Between December 1872 Point Is Point To Subscribe Not Presenting A Pointer In Like Remember Not Updating Point To Do The Rate Of Interest Point Collect Subscribe Here And M.Sc Because Every New Day Here And M.Sc Because Every New Day Here And M.Sc Because Every New Day Scorpio Is Next Point Half Hour Nine Gaund They Need To Give Temporary Idy Subscribe To The Maidens Continuously Till The Time Will Not Nal Bill Paid to the Video then subscribe to the Page if you liked The Video then subscribe to during this time but when the value of Fuel Daughter Not A Part Of Beloved Daughter Subscribe Property Will Be No Point In Too M.Sc Property Will Be No Point In Too M.Sc Property Will Be No Point In Too M.Sc Botany Next 9 Point To 9 Subscribe Button Speaker And Subscribe To Button Speaker And Subscribe To Button Speaker And Subscribe To A Strange Successfully Reverse Submit Judgment Subscribe Time Complexity Of Subscribe For More Video Subscribe Other Videos Have Arrived
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
500
Hello Rishta Bhi Toot Question Buffets Keyboard Road Problem Hai This Channel Subscribe Now To Receive The Award To Attend It Can Give Voice Keyboard Typing Fast Tips Business And Contains Trees And Plants These Things Are Helpful And Built In The Reports * Helpful And Built In The Reports * Helpful And Built In The Reports * Services Hello Alarms Patel And piece in the last few words which only sea line 16 inch balrampur substance August at 10:58 16 inch balrampur substance August at 10:58 16 inch balrampur substance August at 10:58 am ki sari hua the html ko hum second balls alaska Tags page 9 Tags page 10 minutes two wickets at temple two runs straight research serial 200 will Computer Question 's Bilsy Apps Android Satta But E First Saw 's Bilsy Apps Android Satta But E First Saw 's Bilsy Apps Android Satta But E First Saw And Follow The First To Leave It Is The Cost Of A S G K Saugandh Details In Alaska Adi Se Control Social Media Report Will Have Alaska Adjusting Cement's Distributor Green Is President S Well S All Sorts of but I will do subscribe to that shesha to sister electronic and see what will be to in a aaj bhi aloo medium and now problem baby boss feel bhi three set so limiting set one should have all the elements of this first test -tube Bird's Pain and Distension Set test -tube Bird's Pain and Distension Set test -tube Bird's Pain and Distension Set to Because of All Elements of All Characters of Control and Death a Ritual Hadoti Characters of Physiotherapy Keyboard Swear Set 123 Will Have Respect Period Thirty Letters Quality You Are You Pin and Be Id Will Have All the Fun With all the best all the characters will be present in the lead over all this course will straight Over all the words in a semi t input select hello is last date fixed with tree to avoid the votes will be traded that bigg boss trust is hello so award the first but HPCL again will be creating a hello and state will be F4 Type Certificate Balbir Will Be Taking A Torch Light Various Spheres Of Life Will And Will Finish Lies In Its Difficult You Medical Shop First Will Just Be A Great Hocker Tea Board And Only Characters For This Sweet And Hans Proved To Be Taken In This Proves The petting period board had the festival's trading and recent and chilli one who is the first world that is in libreoffice set here it is set 182 and certificate sensitive will finish release this term idiot take the intent will create positive and Check if all the voice president sp mla who is present in this state president and will be i just getting rewards inter result vector hridaya standing crops in result back it is not often jab rekha hot telugu lo ki and will just what is the next generation of words Which was the area, this is solid foods for 10th, is n't it the enemy? Commented on, I have some size in English, Pimple cosmetic is unwanted, set in that, are doing this post. Share this post on officer row filter element is loot and this point se control limit is, I am only. Adi Se Control Act Director Pro Element A The Court To Help His Point On Through The Best Initializing The Results Tractor Which Will Lead To A Result Of Which Will Tree To All U New Delhi Attacking Hadimba Loot Gaye The Nodal Set The Richest Source For His Present In this present at present president too two to two with oo to vote more characters in you vote will just put into flowers ya seed pods and take off but oo that itni apes party ki special will regret over all the characters in what Will Check The Has Haldi Characters A President 110 It's Okay But It's Not Present Will Just Near Silai Slide Salute To All Central Committee Will Rule And Will Check Difficult To Its Food And They Will Put Products Into The Result Is Not Enjoy Due To Work E Look SUBSCRIBE AT SPECIFIC SUMMIT O HUSSAIN WHY IS A PERCENT IN A CUTTING PICTURE THANK YOU FOR WATCHING A
Keyboard Row
keyboard-row
Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_. In the **American keyboard**: * the first row consists of the characters `"qwertyuiop "`, * the second row consists of the characters `"asdfghjkl "`, and * the third row consists of the characters `"zxcvbnm "`. **Example 1:** **Input:** words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\] **Output:** \[ "Alaska ", "Dad "\] **Example 2:** **Input:** words = \[ "omk "\] **Output:** \[\] **Example 3:** **Input:** words = \[ "adsdf ", "sfd "\] **Output:** \[ "adsdf ", "sfd "\] **Constraints:** * `1 <= words.length <= 20` * `1 <= words[i].length <= 100` * `words[i]` consists of English letters (both lowercase and uppercase).
null
Array,Hash Table,String
Easy
null
1,457
welcome to december's leco challenge today's problem is pseudo-palindromic today's problem is pseudo-palindromic today's problem is pseudo-palindromic paths in a binary tree given a binary tree where node values are digits from 1 to 9 a path in the binary tree is said to be pseudopalindromic if at least one permutation of the node values in the path is a palindrome so in other words the path taken to the leaf all these numbers if we could rearrange them somehow to form a palindrome we call that pseudopalindromic so for example we have a couple paths here in this tree two three one two of them are going to be pseudopolydromic right because we could rearrange these to go like three two three that's a palindrome as well as one two one that's a palindrome however two three one there's no way we could rearrange that into palindrome so that doesn't count and a couple more examples here so we know how to travel traverse a binary tree we do a pre-order traversal pre-order traversal pre-order traversal and just take along the path attaching all the node values along the path and once we reach a leaf we could then check to see if it's a palindrome so the trick here is what would be the function to determine whether the path is a palindrome or not and they kind of give it to you right here in the hints note that the node values of a path form a palindrome if at most one digit has an odd frequency so for example if we had one two one or i should say like one two this is going to be a palindrome because we could rearrange that to uh one two one right same with like one two we could rearrange that to one two one it's only when we have multiple odd digits say like one two three or something like that we can't really rearrange that for a palindrome so what we can do is write a function to count the number of counts for each number and then check to see if at most only one of them is odd and if that's the case then we can say yes this is pseudo palindrome so let's start with that we'll say uh we'll write a function here do it inside of the function and we'll say is pal or i should say pseudopaladin um but you get the idea so we'll pass in a list of numbers what we'll do is create a counter object of this list and now um what i'll do here is say all right for the p value in c dot items uh if the value is odd meaning uh this modular 2 does not equal zero that means it's odd right then we could say we found at least one so we'll have to have some sort of variable here to say let's say like one it was false to keep track of whether we've seen one before or not so if it is odd we'll say all right if one is true then we can return false because it's not a palindrome otherwise if it's the first time we've seen it then we'll set one to equal true otherwise if we can get out of this loop then we can just return true because it is a palindrome and i suppose if we pass an empty list we can just count that as a palindrome here all right so now we have our function um maybe we'll give it a little test let's say print is pal and let's pass in two lists we'll say one two and we'll do one with one two three how about one something bad so this should be true and false oop i think i misspelled that so let's see oh come on oh okay for syntax okay so this should be true false and it is all right great so now all we need to do is write our function for our pre-order is write our function for our pre-order is write our function for our pre-order search and what we'll do is pass in the node all right so what do we do here well uh just like any other search we first have to say okay if um not node then we return and we'll return a zero now if i should say else if we find a position where we say node.left not no doubt left and not node.left not no doubt left and not node.left not no doubt left and not no doubt right that means we're at a leaf so we can check now to see whether this is a palindrome or not and we have to pass in the path that we've taken and this is going to be a list of all the node values we've seen and we'll just calculate that we'll say all right so if is pal of our path plus the node value then we'll return a one otherwise return also zero because we've reached the end of the path but it's now a boundary now finally what do we do here um i suppose really all we need to do is say okay return dfs no dot left and the path plus uh no dot value and same thing here say dfs no dot write path plus node dot value and make that list all right so let's see if this works pass in a route and an empty list and let's see if this returns what's supposed to so it does return two it looks like that's working so let's submit that and there we go accepted yeah so that's it i mean they give it to you really hints there um really the tricky part here is to write the function to determine whether it's pseudopalindromic but otherwise we've seen this before right finding the paths to the very end the leaf there's many ways you can do this iteratively but this seems to work so i'll end it there all right thanks for watching my channel and remember do not trust me i know nothing
Pseudo-Palindromic Paths in a Binary Tree
minimum-difficulty-of-a-job-schedule
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome. _Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes._ **Example 1:** **Input:** root = \[2,3,1,3,1,null,1\] **Output:** 2 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path \[2,3,3\], the green path \[2,1,1\], and the path \[2,3,1\]. Among these paths only red path and green path are pseudo-palindromic paths since the red path \[2,3,3\] can be rearranged in \[3,2,3\] (palindrome) and the green path \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 2:** **Input:** root = \[2,1,1,1,3,null,null,null,null,null,1\] **Output:** 1 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path \[2,1,1\], the path \[2,1,3,1\], and the path \[2,1\]. Among these paths only the green path is pseudo-palindromic since \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 3:** **Input:** root = \[9\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 9`
Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d).
Array,Dynamic Programming
Hard
null
1,624
hey everyone welcome back and let's write some more neat code today so today let's solve the problem largest substring between two equal characters we're given a string s which consists of only lowercase characters A through Z and we want to find the length of the substring between two characters that are equal so the longest substring that we can find like that so imagine we have a string like a b c d e a b c and then B to find a substring first we have to find two copies of the same character suppose these two they're both a what's the length of this substring and when they say length of substring they actually mean only the characters in between them so how many characters are between them well in this case there are four so is this the longest such substring because all we have to do is return the length of the longest substring there are two B's as well so we have a b here and a b here the number of characters between them is five and I think we also have two C's but the number of characters between them is three so obviously the longest is five that's what we would return now the question is how can we find the solution to this problem like how do we find that longest substring the first way that you might try is like a Brute Force approach for example starting at this a keep basically two pointers keep one pointer here and then this pointer will keep shifting through the string until it lands at another a and then we'll take the length between these two but one thing I think this problem actually doesn't clarify or at least doesn't make clear is what if we actually had another a over here does it allow us to consider this but also to consider this even though there's an a between them like does the characters in between have to be nonas in this problem actually this is perfectly valid it doesn't matter if there's an A in between these two there doesn't need to be other characters only it's a little open ended but I think this sentence does uh support that knowing that the approach that I was kind of talking about right now is a Brute Force approach where we'd consider this character and then we'd consider this next character and then we'd consider the next character and keep going that would be an O of N squared approach but is it possible for us to do better is it possible for us to do this problem in a single pass well it would be hard with two pointers wouldn't it if we had one pointer here and we're iterating over these yes we know we've seen a b we know we've seen a d a c but by the time we get to this C for example how do we know that we have already seen a c before we'd have to probably put these characters somewhere in memory but not only that we'd have to also remember at what index did we see the C and it would be at index 0 1 two and of course we would probably know which index we're currently at we can do that with a single index or pointer I so if we can find a way to keep track of all the characters that we've seen before and map them to the index that we've seen we can solve this problem there's one last Edge case though and that is let's say the third occurrence of an a character over here we have actually seen two A's before so when we're here how do we want to calculate the window do we want to calculate it with the last a that we've seen or do we want to calculate it with the first a that we've seen probably the first a so when we take these guys and throw them into the data structure that we're going to use which in my case I'm going to use a hash map because like I said we want to map every character to the index so a would be mapped to zero B would be mapped to one etc when we get to the second occurrence of the a yes we're going to calculate the length of the substring we're going to see okay there's four characters in between them and by the way we would do that with 0 over here I think this is going to be a five we'd say 5 - 0 and then minus five we'd say 5 - 0 and then minus five we'd say 5 - 0 and then minus another one because we're only counting the characters in between them so that's going to be the formula by this point though when we get to the second a we calculate the length of the substring but we don't take this a and throw it in the hash Mount because there's already an a there we only want to keep track of the first occurrence of each character that will allow us to solve this problem optimally and we will do it in bigo of n time in terms of memory complexity you might think it's Big O of n but recall that the input string will only contain lowercase A through Z so that's technically 26 so this is actually constant memory now let's code this up so the first thing I'm going to do is create that hashmap where we are mapping every character to the first index that it occurs at so I'm going to call this map character index it's going to be just an empty hash map initially we also know that we're trying to calculate the max length between characters equal characters so that is going to be our result I'm not going to initialize it to zero because actually they tell us in the problem description that we should return netive -1 if a valid result does return netive -1 if a valid result does return netive -1 if a valid result does not exist so that is what I'm going to initialize it to I'm going to return it here and now the only thing left for us to do is actually calculate it I'm going to do a little shortcut in Python I see in enumerate this string if we were to iterate over this string we could iterate over just the character or we could just get the index by doing a range function and taking the length of this string but we can get both of those in one line if we use enumerate I'm going to do that and now we know that there's a couple cases have we seen this character before is this character in the character index map or is it not in the character index map we know the else case is pretty easy because if it's not the only thing for us to do is just throw it in there put this character and say that this is the first index that it occurs at we can't calculate the length of a substring because we've only seen this character once so far but this case is a bit more interesting if the character already exists here and now we have seen it again that means we can calculate the length between these two characters how do we do it well we take the index of the current character I subtracted by the index of the first time that we saw this character and also subtract one from it to get the number of characters in between them and this is the length between them now we want to maximize our result so we set result equal to the max of itself and what the current length between the characters happens to be this is the entire code let's run it to make sure that it works as you can see on the left yes it does run time doesn't look good but that's pretty random on leak code so I'm not going to pay attention to it if you found this helpful please like And subscribe if you're preparing for coding interviews check out ncode doio thanks for watching and I'll see you soon
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
65
uh today we're gonna be working on lead quote question number 65 valid number uh a valid number can be split up into these components in order a decimal number an integer and optional is that an e or capital e followed by an integer a decimal number can be split up into these components where we can could be positive or negative and you can have more than more one or more digits followed by a dot followed by one or more basically the dot can be at different positions and an integer uh can be split up into these components where it can have a sign character or one or more digits so over here they have been showing all the uh they have been showing all the valid and not valid numbers and so basically we're gonna be programming that i think the exact example zero is a valid one s is equal to false and all the other ones so we're gonna be taking the leverage of javascript language here in order to solve this question um what we're gonna be looking for is the number of s whether there is equal to 0 or if we convert the string to this number and that turns out to be uh if that is zero that means we're good or if it is we're gonna check the boolean value of number of s basically converting that string to a number and then checking whether it was a true or a false other than that we also want to do is we wanna uh trim the string and after trimming we wanna say that if it is not equal to basically if it is not equal to an empty string we want to make sure that is true and then we also want to make sure that this s is not equal to three other things uh infinity positive infinity and negative infinity so we want to check that the s is not equal to infinity it is not equal to negative infinity and it is not equal to positive infinity yep and we're gonna be returning that and let's see if it gets accepted yep and it was accepted for all the test cases
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
858
hey you everyone it's your girl xingchi from lico and today i will bring a little heart problem to you guys and it's 8 to 8 come unique characters of all substring of a given string the name is already super confusing right so let's directly down into the description so we're given um we define a function count unique characters and that returns the number of unique characters on s for example if s equal to liquid then l t c o d are the unique characters and they appear only once in s therefore correct the count unique vectors s is equal to phi so our problem is we are given a string s and we need to return the sum of count unique characters t where t is a substring of s notice that some substrings can be repeated so on this case you have to count the repeated ones too and since the answers can be very large so we should return the answer module ten nine plus seven okay so what the problem really asked us to do let's make click clear and we are given a string so our input is the string s and how to get out of our output basically is so for our input s we could get a lot of substring and for each sub string we just find out if each substring will find out every unique character and then with some we sum up every unique character so basically that is what we should do let's go for an example to make it more clear for example the first one we have abc and how we come always a 10 because abc we can count up a b c and a can contribute like for one and b is a unique character so it's contribute one and c is unique so one a b that's why it's count two because a b is all unique and bc is also two and abc is three because there are three unique characters here and let's go to the second one the second example is we have aba and because both three character so actually the combination is same right the combination is also for this one is a b and a and also a b and b a and a b a right at l is here it's a b and b a and b and uh a also in the aba right so for this one a could be contribute for unique b could contribute and a b both is unique so both contribute b a also uh both you need both view and this b is contribute and this a also contribute and this a b a because there's two a so this duplicate so only b is contribute and wait actually what when we solve this problem actually we every time all the time we'll talk about is a contribute for unique character so normally at the first time we after reading the description actually what we want is we first find out that every substring and then we find each unique character right but the result what really that is important for the result is if here how the unique character contribute here so the result should be all the contribute character for their substring right so let's think another way to find the result because at the beginning our solution is going this way so maybe what we want is for each character in the given string and we're trying to find the how many way it could fall for full uh substring and itself could be uh contribute could be a contr can con contribute character before i dab into more example i want to mention like i got the idea actually is from this person lee215 and after reading the article in the discussion i just feel okay he's so smart and the way that it solves the problem is just very clear and it's one pass and it's with a super good uh time complete and space completely and also i will use the example he list here because it's just really easy to understand so let's look at the problem in another way so let's go through the first example again so we have a aba say this time and this time instead we look at the substring first let's talk about if we get a how many like how many substring that could be and then a could be a unique character inside here and we can see a itself could be a substring and a is a unique character right and also a b is a it is a substring and also abc but how could we count out the idea actually because like here in here because there's no other a after this a also there's no a in front of this a so we can think about like so a substring is a thing that inside uh inside of parentheses and we can figure where to put this parenthesis and where to put this parenthesis to form a substring which contains a unique a right and for this parentheses in this example only one slot that we could put is in just in front of a so it's only one way and for this parentheses we have one two three we have three way to put this so we just multiple three and also do the same thing for the b if b have a parenthesis where i could put this one actually here one plus a one a small two small there's two for open parenthesis and also this one is one two right and for c is similar to a and for c is it have 1 2 3 for the open you have one for the close right and so the result actually is what three plus four plus three right and it is 10 that is what we want and let's double confirm with the second example a aba and for this example for the first a how many way we could put the parentheses for the open parenthesis we have one slot to pull it and for the second one we have one slot here but we can now put this log here because here already have another a right so it's one thumb two and for the b the open parenthesis we could put is one two there's two way and the close also two-way right and for the third a here the open is one two only two way we can now include another eight so two and for the close is one so the total is two plus four plus two and which is a correct and now let's go to a more like complete example if this one x a x this one so from these two example basically we already got the idea so the result should be for each character let's find out how many substring it could form and then it could contribute as a unique character right um but like how to how we uh how we form an algorithm for that how we really calculate the parenthesis in a more complex a complexity example so in this example is longer and it held 3a and i want to see is how please calculate how many substring it could fall for the second a to contribute and our parentheses could be here or here so for the open one it held two way for the second a right and for the close one it is one two three right so it's six way but how we get the distance so there's three things we should well there's a actually three thing we should store to get the result the first thing is to preview is a preview a index and second is a current a index and the third one we should recall is the next a index right so we need help these three steps so we could gather distance by these three stuff and much together and which means like because we got this we got the a string it is pretty straightforward that we need to either do an iteration on the string and if we could go the if we could go this a the second a the number way only one we know the previous one second and the fifth future one that means in this position when we do iteration when we go to this position we only can calculate this one and this one because only like if we go through from the zero to here we only can store the previous index and this index so what they can calculate this one only when we go to the third a when we add the third a position we can calculate for the second right so now we are kind of clear and so let's start coding and before coding i also need to ask a question is so for the first egg actually we need the first a we cannot start we cannot calculate anything because when we meet the first a we only the only thing we should we need we could do is we store the index of the current a because and because we have we need at least three steps to calculate for one or four for one number right and let's start coding so we definitely need to uh a place to store the index and for the 26 for 26 character and what we want to put in this here is we can store two index which is the uh which is a previous one in the previous and the previous of the previous so i will put here is the previous of private index and the previous index so that's it i will put here and at the beginning when we start doing here because here's how no proofs and previous in here and the previous should just the beginning right and we just need to make sure we put something which i put something can calculate for this example if we put a parenthesis for this a and the open for the open parenthesis actually it have one two it have a two way to put the open parenthesis for the first day right so when and the first a the index is a right the index is one not a the first a the index is one so we need to make sure the minus something that should get 2 because 2 is the way put the first parenthesis and what we put is just minor 1. so at the beginning these two values will both to put the minus 1. let's do that so we just do a for loop inked i equal to zero high less than 26 i plus so we use the erase dot view index i and minus one nice awesome and nice uh the next step we just do some preparation we should store result we also need to and what else we uh we also need the yeah we need a mode to encase the numbers to be in overflow yes um now it's time for the iteration i like iteration the index from zero and to n and i plus i wrote this c already um mentioned here so first a we cannot calculate anything so let's start from the second a so when we increase because of the second a we first we'll put the star the current character and we need to con convert this to uh to an integer because what we store in the array is 26 integer so we just do a ask transfer and then we begin to update the result so the result should be right the results plus something and then we should mode the mode to in case it's too big and what we should plus here is just like oh what i mentioned because when we add this a we already get the current position which is i and the previous position which we start here and also the previous preview is here where they prepare everything now just calculation so at this a the result of our calculate calculation is a number away for this a for the previous a so um we just do i this is a distance for the second a to the first a use this to multiple the index one minor index zero and after doing that because we have a plus here so in case it's too big so we need to do mode again nice and after this we should update our current index we should the new previous of the previous should be the before previous right so we put the index c one here and the current index here nice and here's the thing so we'll calculate for this a because we already go through everything actually when we go iteration for the last a what we calculate is a before the last a so there's no like there's no calculation for this a so the result should also have this one and for this a actually is this distance here actually we already stored here and multiple to the length of the substring and my minor the index of the previous a right so we just do one more we should do this for every character so let's do see 26 in c plus result basically we just copy this one and the paste here will change the eye too nice and in the end we return our result let's see oh so we got something try uh okay try let's run the code again yeah i hope the meet yes so that is ideal for this problem and i do love the way to think the way that people solve the problem from a different perspective and i just feel so amazing because every the first time i look through the description i just go through from here and so i when i find that people like think from this way and that feels so like so good and i feel every time we solve the problem we should to find uh if the problem is very difficult maybe it is time to look at a problem from different perspective and i like the problem and i hope i my description is clear and if i meet any mistake or if i describe i'm clear in some part of the code please let me know by comment under the video and i hope you like the video and i will upload more video in the future and yeah that's it for today goodbye
Mirror Reflection
masking-personal-information
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null
String
Medium
null
1,448
Welcome to this new inside code video where we&nbsp; will see the "Count good nodes" problem. So, what&nbsp;&nbsp; does the problem say? It says, given a binary tree&nbsp; root, create a function that returns the number of&nbsp;&nbsp; good nodes. A node N is called good if there are&nbsp; no nodes that are greater than N in the path from&nbsp;&nbsp; root to N. Here is an example, we have this binary&nbsp; tree, and you can see that we have 7 good nodes.&nbsp;&nbsp; An example of a good node is this one, we&nbsp; consider it as good because all the nodes&nbsp;&nbsp; in the path are not greater than 5. And this one&nbsp; is a bad node because in the path we have a node&nbsp;&nbsp; that is greater than 3. The intuitive way to solve&nbsp; this problem is that for each node in the tree, we&nbsp;&nbsp; traverse the path from the root to that node, and&nbsp; if we didn't find any node that is greater than N,&nbsp;&nbsp; it means that we found a good node, so we&nbsp; add 1 to our output. This solution works,&nbsp;&nbsp; but it's quite slow because we always need to re&nbsp; traverse nodes uselessly, we end up with a time&nbsp;&nbsp; complexity of O(nh) where n is the number&nbsp; of nodes in the tree and h is its height.&nbsp;&nbsp; In order to optimize this solution, we will&nbsp; use a variable max_node that will hold the&nbsp;&nbsp; maximum value that we've found in the path from&nbsp; the root to the actual node so far, then by&nbsp;&nbsp; comparing max_node with the value of the actual&nbsp; node, we can know if it's a good one or not.&nbsp;&nbsp; An example is better to understand, let's do&nbsp; this one. The first call goes on the root,&nbsp;&nbsp; and you can see in the call stack that the second&nbsp; parameter is the max node we've seen until now,&nbsp;&nbsp; and we didn't see any node yet, so the&nbsp; initial value of max node is -infinity.&nbsp;&nbsp; In this node, 2 is greater than&nbsp; -infinity, so it's a good node.&nbsp;&nbsp; Now we count the number of good nodes from the&nbsp; left. Here you can see that the max changed,&nbsp;&nbsp; it became 2 because 2 is greater&nbsp; than -infinity, it replaced it.&nbsp;&nbsp; This node has the value 1, and max node is 2, 1&nbsp; is smaller than 2, so it's a bad node. We continue&nbsp;&nbsp; from the left, the max remains 2 is not greater&nbsp; than 3, so this one is a good node. From the left,&nbsp;&nbsp; we have null, it's the base case, so we directly&nbsp; return 0. From the right, same thing, we return&nbsp;&nbsp; 0. Now we got the number of good nodes from both&nbsp; sides, and the actual node is good, so we return&nbsp;&nbsp; 1+0+0, which is 1. Now we go to the right, 2 is&nbsp; not greater than 5, so this one is a good node.&nbsp;&nbsp; From the left, the max became 5, but it's&nbsp; not greater than 6, so we have a good node.&nbsp;&nbsp; Left side, null, right side, null, and the node&nbsp; is good, so we return 1+0+0. Now from the right,&nbsp;&nbsp; null, we return 0. We have 1 from the left, 0 from&nbsp; the right, the node is good, so we return 1+1+0,&nbsp;&nbsp; 2. Now we have 1 from the left, 2 from the&nbsp; right, and the node is bad, so we return 0+1+2,&nbsp;&nbsp; which is 3. You can see that we counted the&nbsp; number of good nodes from the left, we found 3,&nbsp;&nbsp; and now I'll just let the animation count from&nbsp; the right side. We finished the recursive process, and we got 1+3+3, which is 7, the tree contains&nbsp;7 good nodes. Now we can move to the code, but before, please take some seconds to like&nbsp; the video, and to subscribe to the channel.&nbsp;&nbsp; In code, our function takes as&nbsp; parameters a node from the tree,&nbsp;&nbsp; and the variable max_node that starts at minus&nbsp; infinity. The base case is when the node is null,&nbsp;&nbsp; we directly return 0, we have no nodes at&nbsp; all. Else, we first check if the actual&nbsp;&nbsp; node is good, we can know it by checking&nbsp; if max_node is not greater than its value.&nbsp;&nbsp; Then we get the number of good nodes from the&nbsp; left and from the right, but look at the second&nbsp;&nbsp; parameter, we are passing the max between&nbsp; max_node and the value of the actual node.&nbsp;&nbsp; Now that we got it from both sides, we return&nbsp; is_good + left + right. I know that is_good is&nbsp;&nbsp; a boolean, but in this expression, it will be&nbsp; equal to 1 if it's true and 0 if it's false,&nbsp;&nbsp; we did that because we want to add 1 when&nbsp; the actual node is good and 0 when it's not.&nbsp;&nbsp; You can see that this type of solution follows&nbsp; what I told in "How to solve almost every binary&nbsp;&nbsp; tree problem" video, I told you that in the&nbsp; recursive case, we call the function on the&nbsp;&nbsp; left subtree, we call the function on the right subtree,&nbsp; and we join the results, and it's exactly&nbsp;&nbsp; what we did here. For the time complexity,&nbsp; here we are just traversing the tree once,&nbsp;&nbsp; so the time complexity is O(n) where n is the&nbsp; number of nodes. And for the space complexity, the&nbsp;&nbsp; maximum call stack size is reached when we are at&nbsp; the bottom of the tree, and we are not using extra&nbsp;&nbsp; space in the call, so the space complexity is O(h)&nbsp; where h is the height of the tree. I hope that you&nbsp;&nbsp; enjoyed this video, please comment below what you&nbsp; thought about it, and see you in the next one!
Count Good Nodes in Binary Tree
maximum-69-number
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good**. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path. **Example 2:** **Input:** root = \[3,3,null,4,2\] **Output:** 3 **Explanation:** Node 2 -> (3, 3, 2) is not good, because "3 " is higher than it. **Example 3:** **Input:** root = \[1\] **Output:** 1 **Explanation:** Root is considered as **good**. **Constraints:** * The number of nodes in the binary tree is in the range `[1, 10^5]`. * Each node's value is between `[-10^4, 10^4]`.
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Math,Greedy
Easy
null
515
Hello Hi Everyone Welcome To My Channel It's All The Problem Find Value In History To His Words Meaning 88 Road Yadav 12323 Maximo Subscribe List Of All The Maximum From All Subscribe Le Jis Find Out What Is The Maximum Level Similarly Maximum Volume maximum do this in third level this note Solving this problem by using water subscribe for Girls Problem In The Amazing Problem Solution You Can Contact Details Solution Subscribe First Thursday Life is spent and every time I will give you from all elements Get Updates Reviews and News Temporary Not Value and Mrs. Left and Right Notes of the Nodi subscribe The Channel a President and finally subscribe to Bigg Boss it's over fennel etc Benefits of what you will start from this node and will sign available in this way will update plus one can we Use Disprin More Process For Win32 Labs Subscribe Like Share And Subscribe Famous Decision Equal Turn Of The Same Level In One Processing Speed ​​Will Get In It One Processing Speed ​​Will Get In It One Processing Speed ​​Will Get In It Swift Tracking This Like Share And Subscribe Dictionary The Subscribe Number Value Is The Maximum Level Up To Sexual Solving Problems Subscribe Turn off plane mode and listen Will call records and ads and Will pass through Not and prohibition Se Start from 200 Reference Power House Map Object And What will oo Will return divine values ​​from rest From the Video divine values ​​from rest From the Video divine values ​​from rest From the Video Channel Please subscribe this Video not root end You will have included in this app solitaire game me bath what we will do switch active through this little bit in the process oil node to return from idy entry level update value we get it ready for not difficult minimum distributor cervi is 220 what will Get and we need to take the maximum of the thing Maths of current expression Gautam and will update the value of difficult words please subscribe now to receive new updates problem subscribe video like this button and this time complexity of dissolution and also find And space complexity can that number and subscribe thanks for watching the problem entry
Find Largest Value in Each Tree Row
find-largest-value-in-each-tree-row
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**. **Example 1:** **Input:** root = \[1,3,2,5,3,null,9\] **Output:** \[1,3,9\] **Example 2:** **Input:** root = \[1,2,3\] **Output:** \[1,3\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,275
hey everybody this is larry this is day 20 of the september leco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem still in spain still in san sebastian i did a long hike yesterday really tired my body is very beat i'm not in shape so anyway today problem is so yeah so anyway yeah uh we'll figure it out today's problem is find winner on a tic-tac-toe game okay let's see what tic-tac-toe game okay let's see what tic-tac-toe game okay let's see what that means i usually solve this live so if it's a little bit slow just watching on a faster speed i think i got to say that every time because you will leave a comment otherwise okay so we know it's a tattoo let's put let's hope that these are actual rules of tic-tac-toe but sometimes they say of tic-tac-toe but sometimes they say of tic-tac-toe but sometimes they say stuff like that but not um okay we turn the game to exist or still movements to play okay that should be okay so i was wondering if there's going to be something valid erratic uh thing where um you might have been where you know both are winning or something like that um okay there's just two three cases draw well four you want to kind of draw a win v win or pending okay a is x and b is o okay so i mean this seems pretty straight forward um considering that this is a three by three grid oh they give you the moves instead of the thing okay that's fine too i wonder if there's anything like you know the last one is always the one down next to the game and but okay let's get started but we don't have to turn this out right now okay so let's just get started then yeah support and then now just for x y and moves maybe i have to do a new rate as well to get the turn number which is coming in place um okay so board of x y is going to turn mark two just to get the player that has it um okay and then here now we check whether this time wins so we just have to check how do i want to check oh this me oh man sorry i just woke up usually i'm a little bit more involved in this but uh i walked 10 miles yesterday more than 10 miles maybe i don't even remember something at least 10 miles yesterday so um so i'm gonna repeat okay and you want to see that story follow me on instagram and watch the story because i actually post a lot about it which is maybe not super great but okay let's see um i'm just trying to think about how i want to do it so there are two ways you can do think about it one is that for this space you just check the adjacent things right and of course that means that the other corner what i mean is just like you just check the whole column and the diagonal that this thing is in or maybe two diagonals um and you could do that for sure and then the other way to do is just check the entire board which is slightly more expensive but not really right there's only eight or eight um places to check which is three rows three columns and the two diagonals so it's only like at most you know two three times more work um and then that question means um do we check oh sorry um so then the question is whether you know the game ends right uh or yeah well sorry let me rephrase that so then and the question is because it doesn't really matter either way then which what is it easier to implement right so yeah that's basically the idea um yeah and actually because all the moves are valid i think we don't even have to check this one at a time usually you do or whatever you can actually just check it or at the very end because yeah so then maybe what i said doesn't even matter because you can just check it once at the very end because all the roofs have added right so okay let's check them um if good of let's put in a function if this is good then we turn uh um yeah so if it's good that means the game ended and the game ended then it the answer is a if um minecraft moves mach 2 as you go to zero right is that true no it's either one because that means that yeah okay so let's go to one okay i mean this is ready to be a syntax but that's besides the point that's just five point i think um okay otherwise he do it return was it pending so if no one wins then it's pending if the length of moves is less than nine else then uh draw right because basically you did all the moves that's when you go then now we can just do that with a good implementation here um yeah we could do the three we can do uh yeah i'm just trying to think whether how many fold ups i want to do or just sometimes i would just do all three things um maybe i was or don't all eight possibilities is that easier to write i don't know let's see right and you can add some for loops but it's not that okay fine let's just do folders um let's say uh maybe a combination of two three two i'm not sure that this is any faster yeah okay and then now the other thing is just um yeah a little just like um i'm not actually sure about all about yeah and that's all i have assuming is right if it's wrong then i might have more copy into place okay so this looks good except for this one oh um okay i know why what's wrong is that these things uh it compares to none the three nuns compared to each other correctly so or like you know so it's a little bit weird but okay hmm this is why you test things even if you uh especially if you are me and sloppy sometimes testing is so that you can protect yourself against yourself okay so that looks good um i don't know if there are any other scenarios maybe try to dive you know i don't know these inputs i'm not just inventory diagonal uh i guess actually both inputs are diagonal so maybe we try something even as simple as um just like uh fireball or something like that i'm a little lazy though so if i have a typewriter type of what oh obviously maybe yeah not that way i mean if i have a type of appetite though but logically i think okay yeah cool um yeah i mean i think this one is just a problem of breaking it down into easier and easier pieces and then becomes a strategy of thinking about how you want to implement it um yeah because the thing that i probably overthink a little bit sometimes to be honest it's just about the use of implementation and how to make myself least likely to make a mistake which sometimes needs to be decisions but we'll see okay that's what i have for this one stay good stay healthy to get mental health i'll see you later bye
Find Winner on a Tic Tac Toe Game
validate-binary-tree-nodes
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters are always placed into empty squares, never on filled ones. * The game ends when there are **three** of the same (non-empty) character filling any row, column, or diagonal. * The game also ends if all squares are non-empty. * No more moves can be played if the game is over. Given a 2D integer array `moves` where `moves[i] = [rowi, coli]` indicates that the `ith` move will be played on `grid[rowi][coli]`. return _the winner of the game if it exists_ (`A` or `B`). In case the game ends in a draw return `"Draw "`. If there are still movements to play return `"Pending "`. You can assume that `moves` is valid (i.e., it follows the rules of **Tic-Tac-Toe**), the grid is initially empty, and `A` will play first. **Example 1:** **Input:** moves = \[\[0,0\],\[2,0\],\[1,1\],\[2,1\],\[2,2\]\] **Output:** "A " **Explanation:** A wins, they always play first. **Example 2:** **Input:** moves = \[\[0,0\],\[1,1\],\[0,1\],\[0,2\],\[1,0\],\[2,0\]\] **Output:** "B " **Explanation:** B wins. **Example 3:** **Input:** moves = \[\[0,0\],\[1,1\],\[2,0\],\[1,0\],\[1,2\],\[2,1\],\[0,1\],\[0,2\],\[2,2\]\] **Output:** "Draw " **Explanation:** The game ends in a draw since there are no moves to make. **Constraints:** * `1 <= moves.length <= 9` * `moves[i].length == 2` * `0 <= rowi, coli <= 2` * There are no repeated elements on `moves`. * `moves` follow the rules of tic tac toe.
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Tree,Depth-First Search,Breadth-First Search,Union Find,Graph,Binary Tree
Medium
null
1,185
hello everybody and welcome back to the DCC channel where in this series we try to solve technical interview questions so I don't know which question to Joe so honestly devised again smallest range single number day of the week that sounds kinda interesting I guess 1185 day of the week given eight return the corresponding day of the week for that date the input is given as three integers representing the day the mouth and ear respectively returned answer as one of the following so this is more or less something that I have done recently I guess you're not super easy because I haven't done it in pure fighting so let's see we know okay let's see the constraints the given dates are very date between those years so let's see what we can have in peyten as date time we are working with date time heightened daytime and there is a function that will basically string F time nape we want something that's basically the other way around each time and strip string P time I guess I think that was the one and yes so what do we do with that we could create a date out of basically let's give an example and this would be from date time we have to import date time was it like that it's kind of weird but it's just like that from date time import date time and now we are going to print will be date time and now we're going to use this function and I will have a string and our string would be for example now first of April 2000 and the format would be now if you have to choose a format this will be basically something like was it 4d I guess zero palette and I think there was another one without your padding let's see how do they give us the format and let's see well since it's an int it will definitely not be padded with zeros let's see they have mom zero pilots I guess we'll have to pad it ourselves I don't see anywhere here that's possible well what we could do no we cannot do anything like this okay yeah and there's like there is the use of format but I don't think this is something that we need to do right now so let's see we'll be doing will be doing this one so we'll have something for example zero first zero fourth right because four months will probably be the same thing exactly now they are the month where's the month yes okay and so what we do a slash and then basically month slash and then the year has four so it's basically like this and let's see was that all that was needed okay no keyword arguments just leave it as that and as you can see we have the first of April 2000 so for this given day you can actually just because it's a date/time peyten date/time date/time peyten date/time date/time peyten date/time day of week should be probably an attribute or today big day so basically that weekday I think was all that was needed and let's see so we can go check it right we have the first of April two thousand and two thousand would be twenty years ago come on it's P sometime so April we have the first of April and it is five what we got because I'm assuming we're starting at how's it called some calendars start there was some weird naming I'm pretty sure yes they start from zero where Monday is zero Sunday six so basically at five we just have to put one more and there we have it and what do we get also calendar that's interesting they name okay my date weekly that's cool so we can also import calendar will help us basically print it for us and this will be basically import calendar was it like that now we have calendar day name so it's the name should be a dictionary that will do the work for us so we don't really have to implement the dictionary so let's have our solution we will be importing these two guys and they are more or less supported so I'm assuming this will work and let's see just so we don't get to write the whole algorithm and then be surprised at the end that this will not work I just wanted to see if that importing will work and it seems to be working so now we first have to put that our if our day is less than the tenth then they would be getting a treatment so basically we'll be getting a string of day and we'll be adding a zero string to this day and the whole thing will be well actually we'll keep it as a string right else and I'm not sure yeah why not they would be well no let's see actually I just have to date it's a way simpler way to work with it so we'll have date and we'll have this for the day all right and then we'll put the slash we could work without this I think there is some separator that's needed so we'll have something like this and we could also just yeah just have it like that like this else they it would be and just put date plus and or no can we do something like this why not and we'll have date plus string of day let's separate the actually what I'll do I'll just have this and then we'll have everything else afterwards anyway so now I have the month if month again less than the tenth of the months from the mouse we'll have the date and again more or less we're doing the same thing and like I said don't really copy and paste so I'll just write it so you are appending a zero and then I'm not else I guess we're just gonna be doing anyway like this and we are going to be taking them out as a string and we are going to be putting a separate afterwards and the last thing we need is have the year and now we should be able to have our string let's quickly recap we have an empty string we are seeing okay maybe today's less than the 10 we will be putting will be opening a zero on the front and then we'll be taking the rest of the information separate same treating treatment for month if the month is less than ten we put a zero on the front and then we are placing the muffler separate and then at the end a year and now we only the only thing that we need to do is basically we're going to be the returning calendar week first week day painting the name and here we have date time we have this lovely function that you hate the first time we have to use for something very specific but I guess I got to use it anyway so kind of got over that and now we'll be having our formatting which would be today the man the month and year just like that and of course we want to have weekday from that and they should return us basically what they wanted to say string and let's see if that works and it works let's see what do they have only and that the years are basically kept at nineteen seventy one 2100 I don't see anything there that's problematic let's talk about anything concerning runtime well as you can see we're only doing basically three things or four or five things something like that it's like a constant runtime no matter what's being given here so I'm assuming our run time is constant our space complexity again super easy in this case we're only working in a single string and then a single object is basically constant again so this one again for me it was way simpler maybe it's not as simple I don't know you have to tell me but that I think it's very important to get used to this guy here to this library dysfunction the documentation first time I had to use it I had to go through many of those things and it was kind of confusing it's weird sometimes you need the European standards sometimes you don't and stack over those by friends a lot of the times just so you guys know and yeah that's it very important library just working with dates it's kind of good to kind of understand that okay I can get the weekday directly I don't have to do some crazy math on that and now I know that there is two calendar library that can also help me that's nice okay that was it for me I hope you enjoyed this video hope you learned something and see you next time bye
Day of the Week
find-in-mountain-array
Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the `day`, `month` and `year` respectively. Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`. **Example 1:** **Input:** day = 31, month = 8, year = 2019 **Output:** "Saturday " **Example 2:** **Input:** day = 18, month = 7, year = 1999 **Output:** "Sunday " **Example 3:** **Input:** day = 15, month = 8, year = 1993 **Output:** "Sunday " **Constraints:** * The given dates are valid dates between the years `1971` and `2100`.
Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak. After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak.
Array,Binary Search,Interactive
Hard
882,1766,2205
948
and here I present day 12th of September lead Cod Challenge sincere apologies I was quite occupied with office work just came back from office and here I'm in front of my laptop solving this question up the problem that we have in today is bag of tokens here in this question we are given a game to play and what do we need to identify the largest possible score that you can achieve playing this game there are few rules that are specified so I'll be walking about these rules as well as the algorithm to go about it by the presentation so let's quickly hop onto it you're given a set of tokens and integer format you're also told that you have a power value p with each iteration you can either opt for power down or power up what does power down means you select one token and you lose that much of power along with this your score gets increased by one so this is the equation that I have written the total power Gets resed By The Token that you have selected and your score gets increased by one power up means you select one token and you add it to the total power along with that there's a cost to pay and you have to decrease your score by one so these are the two equations that gets formed new power is equal to old Power Plus the token value that you have selected your score becomes score equals to minus1 what do you need to maximize your overall score just remember two points whenever you are opting out for power down your power is getting reduced and your score is getting increased so which one that will you pick out for you will select the token which has the least value so that your overall power decreases by least amount the second thing that we need to figure out is whenever you're opting for power of operation you will select the token that has the maximum value because your score will be reduced by one unit whatever token you select so which token you will select the one that has maximum value in the array this will give us an advantage that your power become increases by the maximum Delta remember these two points and our work is done we will follow a greedy approach to solve this question how let's walk through one iteration you given an array of tokens as I have previously told the first and the foremost thing that you're going to do is to sort this array up so sorting will give us an advantage that the least values of the tokens will be at the starting point and the maximum values will be at the ending point so let me just call this left and let me just call this right so whenever you are intended towards going for the power up operation then what you will do you'll select elements from the right as for the previous understanding and whenever you are going for power down operation you will select elements or tokens from the left index because these have least value these have maximum value and now let's start the iteration what is the current power value Val that you have the current power value that you have is 200 and your score initial score is zero so the first element that you see happens to be 100 and it's at the left index so what do you basically reduce your power by 100 units so power gets updated to 100 and your score gets increased by one we have basically used the power down operation under left pointer gets incremented to the next index what is the next index is this one and the value that we have is 200 at 200 what do we see that this is way higher than the current power that we have so what we should be doing there's only one way out we have to increase our power and for increasing our power we have to reduce the score so score gets reduced by one unit we are going for power up operation and we basically increase our power by 400 units so 400 + 100 gives you 400 units so 400 + 100 gives you 400 units so 400 + 100 gives you 500 and along with this what we'll be doing we'll be reducing the r pointer because we have consumed this token so R now points to over here the next element that we have happens to be U at 200 we still are we are still at 200 again we check whether Is it feasible to consume this token value yes because our intention is to maximize the overall score the total score uh the total power that we have is 500 the current token value is 200 so we will be consuming this token up that means power down operation power gets reduced to 300 and score gets increased to one let's proceed ahead along with this since we have consumed this token up we will move to the next pointer left now points to over here and what do you see here that the current power value the current token value is 300 the current power that we have is also 300 it's a happy case we can use this token value to consume the current power that we have the total power gets reduced to zero and the score gets updated to two so this is a typical two pointer approach that we have used and we have solved plenty of questions on similar lines this is a typical example of greedy algorithms as you can see uh the left the as since we have consumed 300 token value the left pointer moves towards right over here and this is the abortion condition because here in this case left is greater than right and we break out of the loop the maximum score that we observed in the entire iteration happens to be two and this becomes our result I'll exactly follow the same steps as I've just talked here and let's quickly proceed towards the coding section and conclude the approach the time complexity of this approach is order of n log n because we are sorting the input array and the space complexity of this approach is constant time we are not using anything extra in the first go we basically sort the all the tokens that we have we create two variables Max score and the current score uh we take two pointers left and right while left is less than equal to right we check if power is greater or equal to token at the leftmost index if that is the case we basically consume this token up and we increment the left pointer along with this so what we can do over here we should increment the left pointer to something like this so that makes it more readable uh next we go ahead we update our score value by one and we select the maximum score out of the current score and the max score variable if this condition is not met if the power value is less than the token at the leftmost index what do you basically check if your score is greater than zero if it is that means it's time to consume the token and since you're consuming the token you're adding it to the power value it's time to increase the power you basically reduce the score by one if none of these conditions are met you break out of the entire Loop and return the max score value that you have seen so let's try this up submitted I'm connected to VPN uh probably that's the reason it's bit slower uh but the time complexity of this approach is order of n login as I just told before and the space complexity is constant time with this let's wrap up today I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day here and stay tuned for more updates from coding decoding I'll see you tomorrow with another fresh question but till then goodbye
Bag of Tokens
sort-an-array
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
Medium
null
1,769
hey everybody this is larry this is me going with q2 of the uh weekly contest 229 minimum number of operations to move all boards to each box so this is a kind of a silly problem but i took a long time on this one because i just misread it um the thing i miss well i didn't miss read it but i just didn't really think it through where n is 2 000. so when n is 2 000 n squared is fast enough and that's basically um the short story about this problem it's just that you do a full n square for loop on this um and you know you just keep track of the count you put in the answer so i so the reason why i took a little bit long is because there is an actual linear time solution for this um and i actually i think there's a video i have a writ i solve the linear version time version of this problem as part of a q4 problem at some point um so yeah so maybe i'll put a link to that below so know that there is a linear time solution that i was trying to think about doing it and i was trying setting things up and i was like wait this is q2 why am i doing a linear time solution for that long and then i'm like oh yeah n is 2000 so that i cranked this up pretty quickly after that um it's a little silly problem so i don't know what to say but if do if you want to do up solve this in a linear time thing the idea is just having just keeping track of um pointers and then you have this rolling window type thing and yeah and you can do this in linear time it's really tricky um but you can do it linear time it's just about keeping track of stuff and then maybe use cues if you have to but yeah so my solutions and square time and space because that's the size of the output um that's all i have for this farm it's pretty straightforward um yeah let me know what you think and you can watch me stop it live next this is over out to the live box so you this is awkward uh this is too much math okay so uh we should know this one better okay oh and it's 2000 i am just being dumb and trying to do it linear time i am dumb there is a linear time solution but i am dumb for trying yeah i am dumb for you go uh yeah so thanks for watching everybody hit the like button to subscribe and join me in discord let me know what you think about this prom other problems and i'll see you later bye also take care
Minimum Number of Operations to Move All Balls to Each Box
get-maximum-in-generated-array
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes. Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box. Each `answer[i]` is calculated considering the **initial** state of the boxes. **Example 1:** **Input:** boxes = "110 " **Output:** \[1,1,3\] **Explanation:** The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. **Example 2:** **Input:** boxes = "001011 " **Output:** \[11,8,5,4,3,4\] **Constraints:** * `n == boxes.length` * `1 <= n <= 2000` * `boxes[i]` is either `'0'` or `'1'`.
Try generating the array. Make sure not to fall in the base case of 0.
Array,Dynamic Programming,Simulation
Easy
null
1
so ground 75 if I may introduce it is all about working through leak code problems that have increasing difficulty I guess so they have these different weeks yeah so you have week one which is these guys here you do some valid parenthesis emergency lists and so on and they're all easy and then I guess they could start to get harder and harder right rather than try to work your way through and try to find them on your own you just with this is grind 75. I can ignore all this stuff all I want to do is do a few of these things so I wanted to work my way through that I also created an account on lead code let me drag that tab over so here I am I did solve the twosome one uh just to try it out let's see what I did I've forgot it's been a while since I did it when did I do this a year ago so I was playing with it a year ago I guess and they don't even have my oh solution it would be in Rust right there oh I must have solved it with a different no it says rust there but they don't have my solution oh well it's gone maybe they Purge it after a while all right so we'll resolve this one then since that's the first problem in the uh grind 75. and there's no as far as I can tell there's no login for grind 75. um you just have local storage or it Steve says a cookie or I don't know what it does but we just check them off when we do them as far as I can tell um it's a nice little website other than you know I don't know how you'd be able to transfer it from browser to browser um so maybe I'll figure that out at some point maybe it's in the FAQ but I don't want to do that on stream what I do want to do on stream is try to set up a repo to store all this stuff let's just go to my repo here I'll create a new one new repo which we call it what I figured I would do would be to just create a library and that way what we could do is have um uh the tests basically beat the example so in lead code they give you some examples and they ask you to write the code and so what I could do is I could write a separate library.rs entry for each one of these library.rs entry for each one of these library.rs entry for each one of these guys and then uh put the tests in and we could solve it that way and then we just copy paste the code in here because I don't want to use this as my editor it doesn't have any of the features that I'm used to so solutions for various neat code problems um sure all right so let's clone this over here hit clone Boop Cargo in it oh I didn't want to do that um let's try again cargo is it in it lib can I do it that way yeah there we go okay get status git add dot get diff staged okay so we can just uh git commit rust Library framework all right so the first problem is this two something so how do we get started with that I think the easiest thing to do is in lib RS um we don't need that I think we probably have to do pubmod right should we divide these up I'm just trying to think of how to name each one of these things let's call it leak code 0001 to some and that way each one we can actually sort them by name and this is going to take in a vector of R32 as a return Target so that should be straightforward if I try to build this now it's going to say it doesn't exist so we can just edit it let's see how well this works out for us so this is the function signature let's just copy and paste that in it returns a vect of i-32 so just to get it returns a vect of i-32 so just to get it returns a vect of i-32 so just to get this to compile I'll just say VEC new and now this should build we do have three warnings let's go over here and get bacon going great and if I just run the tests it'll give me this okay perfect so oops oh it did Doc tests too okay um so what we can do is just write a test and then just start working our way through this so test mod and write a test and we'll call it example one and we need to assert that given array of integers nums and an integer Target return the indices of two numbers such as they add up to Target you may assume that each number would have exactly one sorry each input would have exactly one solution and you may not use the same element twice you can return the answer in any order oh okay so that's going to make things a little more complicated because I should be able to Output 0 1 or 1 0 right so we're outputting the indices right so zero is two and one is seven so seven plus two is the target number nine so that all makes sense that's straightforward stuff but if we want to be able to compare them in any order we need to write a vector compare function right off the bat we have an issue I'm going to assume just for now that I'm going to return them in sorted order so I should be able to say to some of vac Bang 2 7 11 and 15. is equal to 9. oh is it equal to vect bang of zero and one right we're passing in nine all right and then that should fail and it does we return an empty array and we expecting zero one perfect so now we just have to write that code and this code I think is pretty straightforward we just Loop over the nums for J and I plus one dot nums if nums of I Plus numbers of J is equal to Target return back bang IJ this way we know that I is always going to be less than J because I starts at J plus one so we know we're returning turning it in sorted order um and if we can't find it let's just return to VEC empty vac can I do this backbang uh oh okay as you size Oops I meant it's either too very good okay and that test works I'm assume this test is going to work too because this is a very straightforward code ex2 is basically this line here but it's three two four and we're going to look for a target of six and the answer is one and two yep both those tests are working okay so that was two examples and then we have a third example of two numbers that are the same uh a X3 to some deck Bang three and we're looking for a target of six and it should be back bang of zero one and that should be our answer okay so all those pass that's good um so we just copy paste this code in here copy paste and we have to indent it just to make it formatted uh and then submit let's see if that works and then anytime there's a wrong answer here we can just add it as a test here and solve it and then copy paste the code back okay so we got the first one done 31 milliseconds faster than 28.52 31 milliseconds faster than 28.52 31 milliseconds faster than 28.52 percent of rust online submissions for Tucson is that good I don't know so we can check this off boom
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
1,207
hey what's up guys Nick Boyd here I detect encoding stuff on Twitch in YouTube getting back in after a couple days so I got to start off easy to just get my brain going here this one's super easy I think it's new to 1207 unique number of occurrences given an array of integers array write a function that returns true if and only if the number of occurrences any of each value in the array is unique so they want we have an array of integers right and we this one's so easy we just want to check each number and if the number of occurrences is unique for each number then we return true otherwise we return false so in this example there are three ones there are two twos and there's one three and those are all unique number of occurrences so we return true pretty self-explanatory in this case there's self-explanatory in this case there's self-explanatory in this case there's one and one two since one and two both occur once that's not a unique number of occurrences so we return false and then you can go through this example on your own it's pretty long so I don't really want to go through it but how do we do this I mean it's pretty intuitive there's no trick here you have to use data you basically just use a hash map too you have to use data to have a linear runtime yeah you use a hash map you count the number of occurrences and then you just use a hash set and you make sure that the unique value size is equal to the map size so you know you put all the counts in a hash map pretty standard right yeah I'm sure you guys are familiar since this is for beginners I would I'll just explain it as if you guys don't understand all this stuff but basically you have a hash map which takes its gonna loop through our array and it's going to take the current number so we're gonna say okay let's declare our hash map we're gonna loop through the array int for int num and array and we're gonna say we're gonna put into the hash map the current number so each number we're looking at so we're going to put one or two or whatever number we're looking at and then we're gonna put the count of the number of times we've seen it this how Mapp is gonna hold you know the values like there's three ones so it's gonna be like this one three there's two twos and then one three in the first example so the hashmap is going to look like this it's going to be the key is going to be the number that we're currently looking at and the value is gonna be the number of times we see it when we live through the array so to fill it up with those values we just do okay num occurrences dot put the current number is the key and then we want the value the count so if it's already in there if it's already in the hashmap we do get that number so we can get the number of occurrences that's already in there but we use this method or default so if it's not already in there we either get the number or we default value zero because we haven't put it in the hashmap yet and then we just add one to whatever that is because if it's in there we get the current countin we add one to it if it's not we default to zero and we add one to it and that was the first time we see it so after this loop we fill up our hash map with the number in the number of times it occurs in the array now we just want to make our hash set of integers we could call it unique Val's and in this hash set we can actually take num occurrences our map and just pass it in the constructor with the value is only so this takes the values of our hash set the counts the individual the number of occurrences for each of these so like two three two and one and it will hash that's only keep unique values if you guys didn't know that so this will only keep you know if there were two ones you know for this for example in this case you know we saw one and two are both occurring one time so it would pass those in those values in they're both one but it'll only keep one of the values it's only unique values that's how hash that's work so if they're all unique then the number Curren is sized so we return them occurrences dot size is equal to unique Val's dot size because if they're all unique then the Valis eyes of the hash set should be the same as the size of the map so that's the whole problem there let me know if you guys have any questions I think pretty self-explanatory definitely for pretty self-explanatory definitely for pretty self-explanatory definitely for beginners so I guess I could see if you guys have any questions but yeah there's no really avoiding this using space in this problem it's just kind of a intuition based thing there's not a trick here but yeah good beginner problem let me know you guys think let me know if you have any questions runtime linear loop through the array space linear so thank you guys for watching I appreciate you guys and I'll see you in the next one
Unique Number of Occurrences
delete-nodes-and-return-forest
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
2175
139
hey guys welcome back to another video and today we're going to be solving the leakout question work break all right so in this question we're given a non-empty string given a non-empty string given a non-empty string s and a dictionary word dict which contains a list of non-empty words contains a list of non-empty words contains a list of non-empty words determine if s can be segmented into space separated sequence of one or more dictionary words okay so this over here is pretty important it has to be one or more dictionary words so in the beginning i thought that you have to use all the dictionary words but no you just have to use at least one okay and note the same word in the dictionary may be reused multiple times in the segmentation uh but the dictionary does not contain uh duplicate words so for example over here our string has a lead code right and uh you can separate this into two words so we have leads over here and we have code over here sorry code over here and both of them do exist inside of our word dictionary over here so that's why we end up returning true similarly over here we have apple pen apple so what happens is we have the word apple then we have the word pen and notice that they're both in our dictionary and we again we have the word apple right so like we said earlier the words can be reused okay so yeah that's going to be true again but over here this is over this over here is going to be false and the reason for that is because we have cats right and cats is in our dictionary or we have just the word cat so if we just go with cat then the next word is going to be sand and if we went with cats our next word would be and they're all in our dictionary over here but the problem is at the ending these two words over here og are going to get left out and not all not always og so let's say we took dog over here then some of the words over here would get a n would get left out right so there's always going to be some words which are not in our dictionary that we see over here so we also need to account for that and that's why this over here is considered to be false so let's see how we can use dynamic programming in order to solve this okay so i'm going to be going on with our same example of lead code over here and this over here is our dictionary so what we're going to do over here is we're going to have an a and what this area represents over here is going to represent whether the word exists from the very beginning up to a certain word what do i mean by that so what this basically means is that and by the way everything's going to start off as false but we will change that as we go around so what i mean by this is this over here is going to represent the 0th index and what this tells us it represents the word which goes up to the zeroth index so in this case the zeroth index has a word l and notice it goes up to but not including that letter so if it goes up to l it means it's just going to be an empty string so this over here is going to be an empty string now this over here the second one we have we're at e right now so this means everything up to e so that is going to include the letter l so this over here has the letter l then this over here is going to go up to this second e so that has l e so i'm pretty sure you get the point so this has a l e and this is going to be l e t then l e t c o and then over here okay and one more thing i added one more uh value over here that's because i didn't have enough from the beginning okay and then over here we're going to have l e t c o d and finally this over here is going to have the entire word lead code now if you notice the length of this area over here is going to be whatever the length of our string is plus one and the reason for that is because while we're doing that what's going to happen is we're going to get the entire word as well right so if we only went up to the length of s so only up to the length of this we would only have gotten up to l e t c o d but if we added one more which is this over here we have the entire word which is lead code now one thing we want to do is before we start on with our further steps is we want to change this over here to true because this over here is an empty string right so that basically already exists so this over here instead of false we're going to say it's true and one more time what this represents is does the word exist so everything up to let's just look at this over here so everything up to this over here gives us the value lead and lead does exist inside of our dictionary so what's going to happen in that case is we're going to change this false to true but before we do that we have a few steps we want to consider one more thing which is everything up to that word already satisfied so those are the two conditions that we want to satisf look at and let's see how we can do that so i'm just directly going to go to this over here since uh over here uh if nothing's really going to be changing but over here we have a word lead so what's going to happen is we're going to be doing two checks the first check we're going to do is we're going to check if everything up to this word is already filled right and only if everything up to this word is already filled only then we can account for this word so to do that what we're going to do is we're going to look at this current index so that's zero one two three four so that's at index four and what is the length of our word lead it has a length of four so what i'm gonna do is we're gonna do four minus four which gives us a value of 0. so we're going to go to our zeroth index which is this over here and we're going to check if it has a value of true and if it does have a value of true that means that everything up to that has been accounted for and in this case this is true so that means that we can go on to our next check now our next check is to see if this word over here exists inside of our dictionary and it does so lead does exist as one of our words so what's going to happen since both of those are true this is going to end up becoming true so instead of false this over here ends up becoming true so now let's just keep going through this nothing's going to change until we go to the very ending over here so now what happens in the very ending so we have the word lead code and that's the entire word so over here we're going to be doing the similar steps so the first thing is we want to check is everything up to this over here satisfied or is everything up to there accounted for as one of the words in our dictionary so to do that we're currently at the fifth sixth seventh eighth index now we're gonna do h minus four since that's the length of code so eight minus four gives us a value of four now we're going to go to the fourth index and it has a value of true so that's one of our conditions and now the second condition is going to be is this word actually does it actually exist inside of our dich name now we actually have the word lead code right so we can do one of two things to this word so this is the word that we currently have we can just start looking from so it has a length of four so we can just go back four spaces so go over here and just check everything from here up to here and see if that exists and it does so that does exist as one of our words but an easier way we can do with python is we can use the ends with function and what that's going to do it's going to check if this word ends with the word code and it does right so lead code ends with code so then in that case that also becomes true so what we're going to do finally over here is we're going to change this over here to true okay so let's just do that real quick so this over here becomes true now how do we actually return our final answer is going to be whatever the last element here is so if this is true our final answer is true if it's false our final answer is false now how exactly does that make sense so what i'm going to do over here is i'm going to change our dictionary so instead of being lead code i'm going to change this word to be lead c so that's going to be a word and the other word is going to be code so let's see how this works so one more thing let's just reset this value over here so this is going to end up becoming false and it's also just going to become false right since we're just resetting everything so falls over here so now what's going to happen is nothing's going to happen once we go to the word lead but once we go to the word lead c over here this is going to end up becoming true now the reason for that is because lead c exists inside of our dictionary so i'll just use the color of red and this over here is now true okay so similarly now let's go to our very ending and we have the word lead code now over here we have two chats the first thing is does code exist well code does exist as one of our words but before that we need to check if everything up to that is actually satisfied for and in order to do that what we want to do is we're gonna do h minus four right since four is the length of our code and we're gonna go to our fourth index which is this over here now this value over here is false so what that basically means is that everything up to the c over here has not been accounted for and that means that we do not have a valid answer yet so what's going to happen is this over here is not going to change and it's going to end up staying with the value of false so this over here is going to be false and we're going to end up returning false and that makes sense because the c over here has already been accounted for inside of the word lead c and in order to make this true if you didn't want to make it true instead of using the word lead code you could use the word l e t c and then code again now if you did it on this over here this would end up giving us a value of true so hopefully all of that did make sense i tried to go through most of the cases and now let's see how we can actually implement this using code so let's start off by defining our dynamic programming area so this is gonna be a list and it's gonna have a value of false and what is the length of it going to be so it's gonna be the same length of s plus one and i explained why we're doing plus one because we also want to get the word the entire word by itself as well okay so one more thing we did earlier is that the first instance of this is actually true so in order to do that what i'm going to do is i'm just going to remove the plus one and i'm going to make the first instance of this true so what this is doing is the first instance is true and everything after that up to the length of s is going to be false so that over there is our dynamic programming area so now we're going to go inside of a for loop so we're going to be getting the index of our string s now what exactly are we going to be getting so for this we're going to do range and we're going to start off at the first index and the reason for that is because the zeroth index has already been accounted for so that's where we're starting from the first index and we're going to go up to the length of s plus one and the reason for that is because this over here has a length of s plus one okay so now that we have this what we're going to do is now we're going to iterate through each of the words inside of our word dictionary so for word and word dict okay the reason we're going through each of our words is we want to compare and see if any of our current words is actually inside of our dictionary okay and now we're gonna do the two checks that we had so first let's do the first check so over here we're gonna check if everything up to this word has already been accounted for so in order to do that we're going to go to our dynamic programming area we're going to go to our current index and we're going to subtract that by the length of our word and in this case if it does come as true that means that everything up to that current word has been accounted for inside of our dictionary so we currently have this and after this we have a second check so over here we're going to check if everything up to the certain index actually is one of our words in the dictionary so to do that in python we can just use the ends with function so we're going to go to our string go to everything up to our index and we're going to use ends with and what are we checking it for we're checking it for the word and if both of these come as true then what we're going to do is we're going to go to our dynamic programming area go to the current sorry index that we're on and we're going to make that value true and that's going to be it so at the very ending of this if the last value inside of our dynamic program area is true then in that case we're just going to end up returning uh whatever that is so return dp negative 1 and negative 1 just gives us the very last value if it's true or else it's false so let's submit this and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
1,723
so today we are going to show off problem or find minimum time to finish all the job you have given an array where job I is the amount of time it's take to complete the Ayah job and you have to given K worker you have to assign the job to the cable curve such that it will take the minimum time and you have to return the maximum working time for example you have given three job here and you have three worker here so Suppose there is three worker and you can assign the job in such a way that it will finish in a minimum time so the optimal answer would be like you can assign the first job to this one second to this one and third to this one so it is optimal way and from this you can return the maximum which would be three another example would be this one so here you have exactly two worker and what is the best way to divide them uh it would be like worker one would do this job like one two eight this one two eight and second worker would do four and seven so both would be the 11 and you have written the maximum it would be 11. so you have to assign the job in such a way that is optimal and from that you have to return the maximum or you can divide the question in such a way like you have given an array and you have divide the array into K sub array such that the difference between them is minimum so let's try to find out how we can do this so the logic behind this I can say you suppose you have given this array and there is K worker so what you can do our task is to divide the this array to this sub array such that the minimum difference between the difference is minimum so we can make the array of size K which would be this one and what we can do we can just add particular index number to the from 0 to the K I can say from 0 to K so from here we will have only two sides so we will have only two options left out so for the first option I can say we will Plus one would be here another option would be like a plus 2 at this position so it will be at 3 similarly we will get 4 here so we'll get 7 from here and when we plus 7 at this position so we'll get 14 similarly we will get 18 so we'll get 22. and when the ayat is the like our eye position in this one and then when we again call our function so our if would be five and when ith would be equal to the length of the array so what we can do we can calculate the maximum from the array and the maximum would be I can say maximum would be 22. so by default we can take a global variable which is minimum this is the name of minimum and it is value plus infinity so when we calculate the maximum value from here like this one I is equal to 22 so what we can do we can take like this one minimum is equal to math dot minimum I can say it is equal to minimum and I can say the maximum is the value of the maximum value of the whole sub array so it is the maximum so when we reach here so our minimum value would be updated by 22. again we will go at here the maximum value of this array would be 14 so again we will update this to the 14 again we will come at this position so the maximum value would be 15 but it is not smaller than minimum so the value will remain same and the question is here why we calculate maximum volume when we reach I is equal to 5 so that we will let to know that we will consider all the element in our sub array we calculate the minimum value only if our ith is equal to the equal to array dot length and it is over I can say it is overaring so it is confirmed that we considered all the element in our case of array so we will come we will calculate for this position only so now we will calculate for this one the maximum would be I can say again 15 so it will be not updated again we will come at this position and we will say that we have 11 the maximum and it is exactly our answer so we can update this one by the 11 and it is our final answer we will check again it will be the 1919 is the note it is not best so we will and change this variable so it is on 11 and one optimal approach I can say when you come at this position you can say we can add this position to this one but this is unnecessary work why because if you do the same work it is basically a mirror of this work like you can just mirror all the sub array so you will get the all the same thing which is this one so like here is the three is there here 3 is there and if you draw 2 will be there it is like 1 and 2 so it is also that I can say the same work would be there so it is a necessary work so how you can check this one if your ith value is greater than 0 suppose you have your if value equal to 0 this one and when you I a value equal to 1 I can say 1 so it is greater than 0 so you will check is both the value same initially I can say your sub array would be like this one so if both the value I can say equal to same so you will just continue the loop and how code look like I will also so this is a code in a Java you can understand I will tell you the logic behind this you can code in any language so what actually we do uh this is our function I can say we will make an array of K8 size so we will pass this one into this one and our J would be initially from this position which would be I can say 0 and we will pass the same array which is this one so we'll see this what exactly the base case would be this but first of all we can see this logic behind this so what we can do we will starting from this position and we will continue to the whole size so and what we can do this is the same condition which I already told you to reduce the unnecessary work and what exactly we do here we do this some I plus job J this is we do here one three seven and again we will call the same function with the J plus one and from here we backtrack like it is 22 here so we will subtract 7 from 8 from here and it will be 14 and again we will call it from here so it is for the backtracking approach and when our J is equal to job dot length what we can do we will choose the minimum from the maximum and minimum and this is a function which will calculate the maximum from the array so whenever J is equal to I can say when our J is equal to at this position so we will calculate the maximum from the array and for every call we will calculate the maximum and there is this condition also which is try to reduce the time complexity how suppose you have your maximum element would be 11 and it would be assigned to a minimum variable which is I can say your minimum variable would be 11 and when you search the value when you backtrack from here then you will certainly maybe you get such cases like 15 would be there and I can say you can assume any number like 7 would be there just assume this one so when it will return the 15 maximum so we will know that it is not our best case why because we already get the 11 this is the best case so we did not need to calculate furthermore so that's why we are backtracked from this position if our maximum is greater than minimum so we'll backtrack from here and we will only update our minimum only if our J is equal to job dot length only at this condition only at the last so that all the elements would be considered in our array I hope you understand this
Find Minimum Time to Finish All Jobs
maximum-number-of-achievable-transfer-requests
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Array,Backtracking,Bit Manipulation,Enumeration
Hard
null