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 |
---|---|---|---|---|---|---|---|---|
783 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum distance between BST nodes so we're given the root of a binary search tree and that's the first observation that you should make this is not just a regular binary tree it is a binary search tree which has the sorted property where for every node every value in the left subtree is going to be less than that given node well the values are going to be less than that given node and every value in the right subtree is going to have values that are greater than that given node and this property is recursive so it's going to be true for every subtree as well all we want to do with this binary search tree is return the minimum difference between any two nodes in the tree that basically means we have to pick two nodes in the tree take the difference between them in this case the difference between 6 and 2 is going to be 4 and then return that difference and we want to minimize this difference so maybe we can find an even smaller minimum between four and six so six minus 4 is going to be 2. what is going to give us the smallest minimum it's going to be between 1 and 2 which is going to equal one or we could even say three and two gives us that difference which will be 1 or we could even say three and four gives us that difference which will be also one but how exactly can we find this minimum difference well we could do it the way I'm kind of doing it right now which is for every two nodes compare them and then find the difference and we'd end up doing that for every pair of nodes in the graph how many nodes are in the graph let's say n How many pairs are there going to be well that's going to be N squared one node is going to be matched with every other node so this would be the worst case time complexity if we compared every pair of nodes remember this is a binary search street is there anything we can use to our advantage first of all what if we had a sordid array like this one two three four six the values are sorted how would we find the smallest difference between any two values well first of all if we're comparing one and two and the difference happens to be one why would we ever compare one with three or four or six we should compare values that are close together if we want to minimize the difference so for a sorted array we would only compare values that are adjacent to each other find the difference between these two that's going to give us one find the difference between these two that's also going to give us one find the difference between these two that's one the difference between these two that is two among all these values we want to return the minimum which is going to be one so we can do the same idea on a tree on a binary search tree because with binary search trees we can iterate through the values in sorted order it's called in order traversal on a binary search tree so that's exactly what we would do we would just iterate through the values in order to compare two nodes we have to keep track of what our previous node that we visited was so we'll have a variable initially this will be set to null but we'll keep track of the previous node so the first node that we end up actually visiting we're going to Traverse all the way down to the left and we're going to visit this one then it's going to be set to our previous node we can't compare it with anything just yet but then in our inorder traversal we're going to pop back up because we can't go any further down when we get to the one so we're going to pop back up to the two by this point one will be our previous node so our current node will be two we're going to take the difference 2 minus one this is going to be one so that's our minimum difference so far then we're going to visit this three our previous value is going to instead now be equal to two we're going to take the difference 3 minus 2 it's 1 so it stays the same then we're going to end up visiting the four we're going to pop all the way back up because this is an order traversal with in order traversal for a tree we end up doing the entire left subtree then visit that node and then do the right sub tree just like we did with this sub tree here but now we're at four so we take four minus the previous value which is now going to be equal to 3 so 4 minus three that's also going to give us one and then finally the last node in the tree is going to be six we're going to take six minus four that's going to be two that's definitely not smaller than our current minimum over here so overall minimum that we're going to return is going to be one and you can see we just had to iterate through the tree once we had to visit every node once so the overall time complexity here is O of n we don't have to compare every pair of nodes only adjacent pairs so now let's go ahead and code this up like I said we're going to keep track of our a couple variables one is the previous node and one is going to be the result we have initially I'm going to set the previous node to null and I'm going to set the result equal to a really large number in this case in Python you can usually do flow of Infinity but since we're trying to minimize the result it makes sense to set it equal to a very large number now let's actually do our depth first search and I'm going to Define it inside of our outer function because then we don't have to pass these guys in these will essentially be considered Global variables within the DFS it's a pretty good trick to use with these recursive problems when we need to update some other outside variable but the main base case with an inorder traversal is going to be if the node is null so if the node is null we're just going to return immediately otherwise let's set up our in order traversal template we're going to run DFS on the left subtree we're going to run DFS on the right substrate but in between that we're going to process the current node what do we mean by process well we want to minimize the difference so if our previous node is non-null we can possibly update the non-null we can possibly update the non-null we can possibly update the result we want to minimize it we're going to set it equal to the minimum of either itself or the current value the current difference which we can get by taking the current node's value and subtracting from it the previous node's value we can only do this if the result is non-null though after we're done with is non-null though after we're done with is non-null though after we're done with that we are going to call DFS on the right subtree but shouldn't we update the previous pointer before we call DFS on the right subtree what will be the previous node well it's going to be the current node so we set previous equal to the current node before we call DFS here and we expect that after calling DFS on the left subtree the previous pointer will be updated so then we can do this and that's pretty much it oh there's one last thing and you definitely don't want to forget this is to declare these variables non-local since they are not objects we non-local since they are not objects we non-local since they are not objects we have to do this in Python otherwise they'll be considered local variables to this function and we'll get like using this without assigning it that type of error so we want to declare these as non-local if we want to use them within non-local if we want to use them within non-local if we want to use them within this function if we want to modify them especially like reassigning the result and previous we have to do this lastly we have to actually call our DFS we'll do that out here calling it on the root node and then we're going to go ahead and return the result that was computed within this function now let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free neatcode.io it has a ton of free neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Minimum Distance Between BST Nodes
|
search-in-a-binary-search-tree
|
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
| null |
Tree,Binary Search Tree,Binary Tree
|
Easy
|
270,784
|
241 |
Hello gas welcome back to my channel different way so add paranthesis and its difficulty level is medium before starting it is a one minute message for all of you because I have also started my YouTube channel so what is it you guys can connect one To make it easier than others, what little I have done is that I have created a Telegram channel, the link of which you will find in the description box and whoever is our new subscriber, you can connect there, it can have two benefits, one for you, whatever I will create videos on regular basis. If you guys face any problem then you can ask me directly in telegram. You can also discuss in this. Apart from this, if you connect with others, then you will not be hacker when any project is done. If all these things are available, then you can connect with each other and participate in some particle compression by taking history. Many times it happens that such a percentage of people are not able to meet in the group. In college, this can help you in two ways. Apart from this, I thought of a new thing, the lit code comes on daily basis challenges, they are not that efficient to strengthen the DSP, so now what am I going to do, the questions come in the logic in lit code, I am going to create videos of them one by one. I hope you guys try to solve the questions in the video that comes within a day or two, which will be beneficial for you will understand the recession topic well, you will get an idea of where revision can be done idea of where revision can be done idea of where revision can be done and which revision will help the future ones. If you get help in solving them in the topics then the questions will be so strong and your DSA will be so strong. Okay, so now without wasting time let's start this but if you like the video then start joining also. That it will be easy for us to have an expression will be given which will have three signs, we have to do addition, subtraction, multiplication, we have to add parentheses to it and we have to velvet the entire expression, after velveting it, the final answer will come, we will put it in a vector. If you are doing stroke in sleeplessness then you have to return it. Now one more important thing is that there should be three symbols, okay and when we read Preeti, paranthesis comes at the top, whatever expression is written inside the paranthesis, that is the most. First there will be velvet, now the expression that will be given to us is its length, it will be given 20, like I do after the second expression which I have 2 * 3 - 4 multiply 5, so now I have 2 * 3 - 4 multiply 5, so now I have 2 * 3 - 4 multiply 5, so now I have to add the number of parents in this expression. To evaluate in a different way, what can I do? First of all, I can solve you and three at one place, then I can mine from it and then what can I do later, multiply by multiply or When I take three and four and first multiply them by one and then by five, different answers are going to come. Whatever number of different possibilities are there to generate the expression, we have to calculate it and get the answer. Stroke has to be returned in the vector. Now the question comes that what topic can we apply here? The first thing which is the basic role of Recon is that we should have 24. Now see that here we have the choice. We don't have this, in what reference is 24, what is this we have in reference, where should we apply the parents of our 24, should we velvet 2 and 3 first or velvet our 3 - 4 3 first or velvet our 3 - 4 3 first or velvet our 3 - 4 first or 4 and 5 First if we multiply then we have 24A and according to 24 if we do 2*3 then and according to 24 if we do 2*3 then and according to 24 if we do 2*3 then we have another small choice whether we want to mine the sports first or before that I evaluate 45 and then mine it. If the number of theses comes to us here then we have a possibility that we can apply for revision but then the question comes that if there is a choice here then how will we apply for revision then this repetition is not happening, maybe something like this. If we try to figure out, then first of all let's see which one, like I have done, I have generated three in the context of operators, which means wherever there are operators, there will be a root and its expression is open left and right. If we look at the particular thing, then all the possible treatments that can be generated, the expression given to us, I have maintained the radius of all of them. Now let us see, first of all, what is the meaning of this trick. We have woman, it means that first of all we have 4 * 5, the that first of all we have 4 * 5, the that first of all we have 4 * 5, the result which will be A, how much will be A, after that 3 - 20 and after that A will be after that 3 - 20 and after that A will be after that 3 - 20 and after that A will be -17, after this it will be multiplied -17, after this it will be multiplied -17, after this it will be multiplied by you, so its answer is A. 34 of mines will go, this is the first in that we have the given here -34 first in that we have the given here -34 first in that we have the given here -34 Now let's see the second expression which is on the leaf side, it has to be velveted first 3 - side, it has to be velveted first 3 - side, it has to be velveted first 3 - 4 first, how much of it will go -1 then 4 first, how much of it will go -1 then 4 first, how much of it will go -1 then which -1 will be returned from here Then you have to which -1 will be returned from here Then you have to which -1 will be returned from here Then you have to multiply it by five, how much will it get -5 and then how much will it get -5 and then how much will it get -5 and then multiply it by five, how much will it get from here, the thing of minus is 10, somewhere here, first of all you have to multiply three, from here comes six, then here. How much will we get from 4 * comes six, then here. How much will we get from 4 * comes six, then here. How much will we get from 4 * 5 and when we will subtract these two, how much will we get? The answer is 14 such sims. We have to see in the remaining two fridges. What will be our simple equation? While doing the driver, we will get the value of the left tree from it. We have to find out the value of the right tree and if that operator is multiply then multiply both, if that operator is addition then add, if that is subtraction then subtract both the values then whatever two things we have observed both the values then whatever two things we have observed both the values then whatever two things we have observed from here. Through this pattern, the first thing is that operation is being applied because what we have is 24 here and if vikarshan is being applied then recjan what will we do whenever we have what will open will come operator whenever we have operator. Here we have to do this, we have to evaluate its left sub tree and its right sub tree and after that what we have to check is that if it is an operator of multiplication then multiply it, if it is of plus then add it and it is of subtraction. So let me subtract both of them. Now one more thing, what will we do, our question which we have to return is the final answer, we have to do that in the form of vector interior, so what we will have is the operator multiplication like here, okay, so what we do. We can do this by first turning it left and then adding value to the right sub-trick only. Return then adding value to the right sub-trick only. Return then adding value to the right sub-trick only. Return its answer from here and you can apply it to us. If it is a big expression then it can be stored somewhere which is from one of our particular points. There can be a repeat, if there is a repeat here, then there we will see the development towards the DP. You have to try whether there are chances of DP somewhere or not. DP is in a way an optimized version of the development. If your vikarshan will be strong. So your DP will also be strong. First of all we code it, in the context of the two conditions I have told you here, after that we will go towards BP, in this we move towards the coding part as we had decided that our code We are going to keep it in two steps, one is to apply it, second is to velvet the left sub tree and right sub tree, we have to calculate it according to the operator and store it in a vector. First of all, we create a vector to answer our questions. And we will return it, then what are we going to do, before that we are going to travel for evaluation, I give my expression from zero to expression, I give a speaker, here, we will have a length in a speech, we are going to do something with it and I am going to increment it, I am storing it from the current, so it will go to me after coming up with the expression, then what was decided was that whenever the operator comes, only then we have to proceed with our calculation, so first of all I have to check whether my The current nearby is equal or equal is addition. If any one of these is equal then I will have to evaluate my answer in the form of left and right. If I have to correct left sub, in this for left. We have to call expression dot sub sdr its value will be in the plus van if we do not pass the second parameter then this string automatically refers to the sub string till the end part when I have the calculation I have to do these I have to put a loop for left, for right and then what I have to do is to check whether the current operator I have is equal to the multiplication. If it is equal to the multiplication then what do I have to do by storing it. I have to give their multiplication part, if the current value was equal to mine, whose addition was cakewal, then what do I have to do in this, here I have to push my addition part of both of these and after the third saving, what is the subtraction, so push me the subtraction. I will have to subtract the value of both of these. Now when I have so little, I have to put one more condition. As a base condition, if we have only 22 given in the expression, that means no operator is given and the expression is 22, then I have to do 22. If I have to give it in the result itself, then I put a condition that if the value of the answer I have is empty, then what do I have to store in the answer? There is an inbuilt function in it. Again, what we did in this is that we had to pass the index here. And one more thing is that if we have taken two things here, then instead of 'i' I have 'in' taken two things here, then instead of 'i' I have 'in' and in the right sub tree also 'ind' which is the index of and in the right sub tree also 'ind' which is the index of and in the right sub tree also 'ind' which is the index of our increment indicator, is there any error or not? Also, if it is repeating in a particular branch, then after removing the repetition, we create the map again and create an unloaded map. First, what will happen is that I will have a string and second, it will be stored in the form of vector from which I have created DP. Name has been given, now I have to reduce it by one, where before doing if, I have to check the string which is being evaluated from the tree on my left, so first of all, I am storing my stream in this expression. Before the sub level I am calculating this index and the thing I am doing is already calculate the string for the right sub tree so what I did here is at the sub level and in the plus one and evaluate it from here. Done, now what I have to do is to check here whether it is already stored or not, we have calculated both the strings, then we have to find through the find function in DP whether the level van is already present or not. No, if it is not equal to end, it means that it is already present and I have to store the same value directly on the left, that is, if I pass it, then it will go by the name of STR WAN, if it is not already present. What I have to do is I have to compute and here I have to pass a special I have to do the STR is the names of the vans I have to do this thing I have to do for the right sub tree I have to check whether it is already present or not which is the string that is going to be calculated in this. So if it is not equal to the end of DP, it means that it is already present and I have to pass it to the right, then I have to evaluate it, the right is there in it, apart from this, I have to check all the things here including the success. It's done, okay, apart from this, if you want to join Telegram, then you will get the link in the description box. Regarding the code, it is okay regarding technology. Apart from that, if you found this video helpful, then please like it and share it with your friends and subscribe to the channel. Please subscribe and thank you friends for watching this video.
|
Different Ways to Add Parentheses
|
different-ways-to-add-parentheses
|
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`.
**Example 1:**
**Input:** expression = "2-1-1 "
**Output:** \[0,2\]
**Explanation:**
((2-1)-1) = 0
(2-(1-1)) = 2
**Example 2:**
**Input:** expression = "2\*3-4\*5 "
**Output:** \[-34,-14,-10,-10,10\]
**Explanation:**
(2\*(3-(4\*5))) = -34
((2\*3)-(4\*5)) = -14
((2\*(3-4))\*5) = -10
(2\*((3-4)\*5)) = -10
(((2\*3)-4)\*5) = 10
**Constraints:**
* `1 <= expression.length <= 20`
* `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`.
* All the integer values in the input expression are in the range `[0, 99]`.
| null |
Math,String,Dynamic Programming,Recursion,Memoization
|
Medium
|
95,224,282,2147,2328
|
119 |
hey so welcome back and here's another lead code problem so today we're doing one called Pascal's triangle so all that we're given here is a two-dimensional we're given here is a two-dimensional we're given here is a two-dimensional Matrix that kind of resembles more of a staircase I know they represent it as a triangle but I just find it more intuitive looking like it uh this way so what you have here is basically the first and last columns are always ones and so the base cases here it's kind of the whole array itself like for uh row index0 and row index of one here we see that we're just basically outputting ones it's not until you get at least three columns here that the middle values have non one values here like so all right and so basically the challenge here is kind of coming up with these middle columns here right so it's pretty intuitive to kind of have the ones at the end but in order to come up with the middle values you have to use kind of a formula here that you should be expected to come up with and so it's basically going to be the current row uh for the I column is going to have a value of basically the previous row at index I plus the previous row at IUS one so what that looks like here is basically when we're calculating this two you're going to look at the cell above it and the cell behind it or if you're calculating this value three here you're basically looking at the cell above it as well as the cell behind it all right and so that's kind of what's going on here if you want to actually use a two-dimensional array you can see here two-dimensional array you can see here two-dimensional array you can see here that this is kind of using onedimensional arrays current and previous using a 2d array would be something like this so array 2D is basically going to be equal to um array basically this is the current column I so array 2D basically the previous or the last row that we've populated um at index I plus array 2D we look at the previous row and then IUS one and so we're basically just going to be appending this result here okay and so essentially what we're going to look at here is the first the top one so this is going to be kind of a recursive approach in order for us to kind of come up with the previous row and then the second one here this is going to be using kind of an iterative approach here and so this is often preferred because you don't have the same kind of application stack errors that you might get using recursion so it's often used so you come up with the recursive more naive approach and then do iterative this is kind of similar to dynamic programming we're not really doing any time or space savings here so there's not really any optimization there it's just typically you'd want to do this approach in an interview setting all right but if you're doing just competitive programming uh just given this uh constraints here really 33 rows uh isn't uh much here so both of these would work in a competition setting all right and so from here let's go ahead and come up with the recursive approach and so all that we want to do is basically say that okay our current row initially is going to be all ones just to simplify the first and last columns having cell values of ones here and so basically row index plus one just because python is zero index and so we're expecting to return this current row at the end here uh but with each time we want to get the previous row and so to abstract that away we can just say okay let's just go ahead and call the recursive call to basically the previous row of it basically with this size right because it's a staircase um design or two-dimensional array you always want two-dimensional array you always want two-dimensional array you always want the row index minus one all right and so from here just to handle kind of a base case or an edge case here it's basically going to be that okay if the row index is less than 2 we just have those two base cases where all the columns will be one in that case and so because of that we can basically just return this current row here all right and so let's go ahead and add that like so oh so this is just the base case but from here we're going to want to go ahead and calculate the middle columns okay and so to do that what we're going to do is just iterate in the range of basically one just because we know that the First Column is always going to be one so we kind of skip over it to do the next index to basically uh the row index um just like so all right and so that will basically parse or cut off the last column as well so we just want to say okay the current row at index I and this is just the formula that we came up with uh before is basically going to be the previous row at I plus the previous row at IUS one all right so let's go ahead and run that looks good try submitting and success so that basically runs in uh o of k s just because where K is the row index and we're basically doing um a for Loop for every single uh row index here um and then the space complexity is going to be o of K because well we're going to have a application stack of at least row index many so R is row index all right so that's just basically accounting for this application stack from these recursive calls here okay so let's go ahead and implement the iterative solution now so we're just going to delete this now this is the iterative approach and so we're going to have basically our response here and so we're going to return this at the end and so from here what you can imagine is that what we want to do is we're going to iterate um and we want to have two for Loops here so this is going to be like a embedded for Loop and the inner one is going to actually be iterating over the column so for I in the range and because it's a St case uh the number of columns is going to change and so what you want here is basically the number of columns and so to get that we're going to say okay we're going to get the number of columns and that's going to increase um in the range of basically our row index plus one because python is uh zero index based all right and so from here the number of columns also we want to say is+ one and columns also we want to say is+ one and columns also we want to say is+ one and so from here we're going to want to get the current row which we're also going to be building from this kind of iterative approach and that's why these are initially empty it's CU we're in an iterative way you're kind of building it as you go while the recursive solution you're just kind of uh you already have the result and you're just calling upon uh the one that you already pre-computed okay and so from here we're pre-computed okay and so from here we're pre-computed okay and so from here we're basically going to be at the end of this uh just depending this new current row to our 2D array here and just because we previously I use array 2D when I showed you the formula we'll just actually replace this uh here okay and so with that um what you can imagine here is at this point we're going to say okay so um we actually want to put this here actually sorry and then this here so this is basically Computing The Columns in the current row and so from here we're going to say okay if I is zero or I is the let me think here the number of columns then in that case we're just going to be pending one because that's the uh first and last column here and so we have something like this so we want to say okay current. append one otherwise it's a case where we're Computing the middle column so this is the last or first columns this is actually the middle columns here and so to compute this we just have to say all right so then the current we're just going to be appending array 2D at -1 and then it's e appending array 2D at -1 and then it's e appending array 2D at -1 and then it's e column plus array 2D at1 and then it's I -1 at1 and then it's I -1 at1 and then it's I -1 column like so all right and so let's go ahead and try running this here oh um oh I do know that we want to return the last row not the entire 2D array looks good let's try submitting and success so basically once again I've this second approach also runs in O of K square and then o of K uh where this is the space complexity and this is the time complexity so the reason why this is k^ squ is basically reason why this is k^ squ is basically reason why this is k^ squ is basically the two for Loops here where K is the uh row index or the number of uh rows in kind of that staircase or pyramid however you want to think about it and then it's O of K because uh of our two-dimensional array that we're two-dimensional array that we're two-dimensional array that we're basically building up here all right and so um I think that's about it um what I'm just kind of realizing here is actually I think this is for space complexity it's actually o of K2 and so that's because of the staircase here really in the worst case uh you could argue that um it's two-dimensional in nature and so I guess two-dimensional in nature and so I guess two-dimensional in nature and so I guess it would be o of squ not o k because it's not just a one-dimensional ray it's not just a one-dimensional ray it's not just a one-dimensional ray it's actually a two-dimensional one all right actually a two-dimensional one all right actually a two-dimensional one all right so yeah I hope that helped a little bit um feel free to add a comment below just suggesting any feedback that you have for me um as well as maybe to clarify something uh for someone else but yeah let me know what you want to see next and feel free to follow for more all right thanks for watching
|
Pascal's Triangle II
|
pascals-triangle-ii
|
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** rowIndex = 3
**Output:** \[1,3,3,1\]
**Example 2:**
**Input:** rowIndex = 0
**Output:** \[1\]
**Example 3:**
**Input:** rowIndex = 1
**Output:** \[1,1\]
**Constraints:**
* `0 <= rowIndex <= 33`
**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
| null |
Array,Dynamic Programming
|
Easy
|
118,2324
|
49 |
take a look at a legal problem called group anagrams so given an array of strains and then group the anagrams together you can return the answer in any order an enneagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all the original letters exactly once so you can see that we have an example let's say we have in this case let's say we have eat right basically eat is a anagram of p right because we can use exactly same letters and then rearranging them to form a different word right and then we can also form another word eight right we can basically rearrange each or t to eight right so you can see that these are anagrams so we group them together and then what we do is that we return a list of list string right so in this case we have eight each t as one um group and then we put that in one list and then that in this case is one group and then those two words is also one group so you can see that if we rearrange those letters we can be able to form uh form a different word right in this case uh nat can form to ten right but these words where these letters cannot be able to form those words right so in this case we group them into one uh one list and then if there's a situation where we have an empty or in this case a strain that's basically have no letters so we can just uh group them together by itself right um so in this case the constraints that each strings can only contains just lowercase english words and you can see that there could be a situation where we have string is empty like this right um so how can we solve this problem um so to solve this problem all we can do this is we can be able to sort this string right so to know if this is an energon of this right or those two are in this case are the same group of enneagram we can be able to sort the string right into alphabetical order right so in this case if i sort eat in this case i can do it this way right i can be able to sort this strain right here into aet right and i can also sort t into aet right and i can also sort eight into aet because they're all in alphabetical order now so what i can do is that i can be able to create a table right and basically get each and every single of those strings when we sort it right we sort it uh into aet and then we just add those strings onto the table right so in this case we have eat right we have t and we have eight as part of this key right as part of this uh anagram group right so this is what exactly i did so basically you can see here um i have a function right and then in this case i have a table and this is the key this is the list of strings um and then we basically group all the engrams together right and then basically i iterate all the strings that we have in the strain array for each string we basically sort the string to the to get the key right we have a function called generate key we basically convert it into a character array and we sort it we turn it in as a key right in this case we sort of version right so in this case we sort the character array and then we turn the aet as the key so then we check to see if we have it in our table if we do we just basically get it and then add it onto our list if we don't we just create a list add the current string right onto the list and then we basically create that spot or add the current list onto the table right or add the current row onto the table so basically you can see that at the end we're just returning all the um all the values that we have in our table right so basically these are the values right we have a list bunch of list of uh strings so we return that and then at the end you can see that this will give us a time complexity of uh n times k log k right because here you can see we're basically iterating all the strings that we have in the input right and then for each iteration we basically have the sort right in this case k is basically the size of string so we have to sort it and sorting is going to be uh k log k right for this the time complexity so in this case you can see the time complexity is going to be n log n times k times log k right so how can we be able to optimize the time complexity for this one so what we can do instead is we can be able to optimize this part right instead of sorting what we can do is we can actually be able to convert it into array right so in this case we know that if we use a table right in this section the generate key section if we convert that into a table so for example if i want to know if this string is a in this case if we rearrange the characters in the string is this the same as this right or in other words if the enneagram of two words is the same right in this case what we can do is we can be able to use a table right because in this case if i iterate this string and for each and every single string i have a table like for character a it contains one time for character e and contains one time for a character t it contains one time it's also going to be the same for the string t right t has a character contains one time e contains one time a contains one time so we can do is that we can be able to generate a key and we can be able to based on this right so this is what exactly i did so basically the upper section is pretty much the same but what i did here is that i um change the generate key function and you can see that basically i use a table to keep track of all those uh characters like how many characters um number of times each character appear in the string so i iterate the string right and then for each and every single character i increase the number of times appeared right by one and then in this case what we're going to do is that after for example like you can see uh this string right here right it's going to be a compared one time e appeared one time t up here one time and then because in this case the table has a size of 26 so other characters like c probably appeared zero times b appears zero times and so on right so we're just going to iterate the table like 26 times right or in this case yeah the table has a size of 26 right so we basically use a string builder and we generate a key right so basically you know we know that um in this case a has an index of zero b has an index of one c has index of two right so we iterate that number of times to generate a key and then we use a uh in this case a symbol right it doesn't have to be this symbol it can be anything um to separate them right because there could be a situation where we have like um where we have a situation where we have example like you know like 11 number 11 times of a right where a times 11 in the string right we could have a string of like a all the way maybe 100 times a thousand times or something and then there's b and then c right so there could be a situation we have that but in our table right it will um we have a maybe like 100 times b 100 times or 10 times or something right so in this case you can see that there's a zero so we need something to separate them otherwise there could be a situation where we have two strings are the same right have the same key right so it's all about how we generate the key for this question and once we generate the key we basically convert the string builder to a string and then at the end we return that and then we're just going to see if this key exists in our table if it does we add it to the to list if uh we'll group them in the list um otherwise we're just going to create it add it to the list and then uh create that row in our table right at the end we're basically just going to return the uh the list of strings okay so basically the time complexity for this one is going to be big o of n log k because in this case we're basically iterating all the strings that we have and then for each and every single string right we basically just doing a um in this case we're basically just going to create a key right generate the key by iterating the entire string but there could also be a situation where k is actually less than 26 so in this case there could be a situation where we have they go of n times k or big o of n times 26 right so whoever is bigger right so in this case this is how we solve this problem uh group anagrams so thank you for watching
|
Group Anagrams
|
group-anagrams
|
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
| null |
Hash Table,String,Sorting
|
Medium
|
242,249
|
135 |
hey guys welcome back to my series of videos of me solving lead code problems from scratch and now we're going to solve 135 candy you know I keep that candy more like okay so what's this it's a hard one cool there are n children standing in the line each child is assigned the rating value given in the integr array ratings you are giving candies to these children subjected to the following requirements each child must have at least one candy children with a higher rate and get more candies than their neighbors return the minimum number of candies you need to have to distribute to the candies to the children okay so candies and their neighbors so I guess we get like a line so okay free kids and the ratings so this one must have more than this one and this one has have more than this one so okay let me think JS paint so what I'm thinking here is that we need to find out like there's a n value and the N value is the least amount of candy given and actually that must be one the least amount of candy given to a person must be one I guess so let me look at this place so yeah we give one to this person gets more than one and this person gets one this person gets more than this person which is two and here this person also gets this person gets one yeah because this doesn't need to have bigger than this one because it's the same okay so let's look at an example so 1 2 3 1 2 let's look at this example I have no idea how to solve this so I guess that we give this person N A number that we don't know yet so first person gets n second person needs to get n + one and the next person he needs to get n + one because two is bigger than one n + one because two is bigger than one n + one because two is bigger than one so he needs to get at least one more than the previous one and then the next one doesn't need to get that to get n+ one so that person can get okay what if we start with just we give one to the first person and then we check the second person is the second person bigger than the first person um it actually is so we need to give it more so we give two if that was the opposite we would need to give more to the person behind so what if we start with n and if this person is smaller than this one needs to be n - one then the next one needs to be if it's equal you can this needs to be + one next person can this needs to be + one next person can this needs to be + one next person is equal so you can go back to n the next person is higher so it needs to be n plus one and then next person is lower so it can be n and the next person is higher so it's n + 1 I guess this would work and N would be the least amount of candy so one 2 but what if we have an example where let's say 2 1 3 so the first person needs to have more than the second now this is actually the same thing n nus one and then n that's good let me find edge cases what if it's constantly growing one 2 3 then it's n + it's n + it's n + 1 and n + 2 if it's going down if it's let's say 3 2 1 we start at n then nus one and then N - 1 - 1 which is n - 2 let's see if this works let me make a directory there uh candy I'm not sure this will be enough there's probably I'll find the edge cases the educators will come to me when I submit free5 candy so solution pass solution uh candy ratings is what is example one2 list so we let's start with a number that is I know I was wondering if we could use a n and then just replace it as an equation thing but I think we could just start with one n = 1 and then we do math around one n = 1 and then we do math around one n = 1 and then we do math around it and so final vales is a list of integers and so for I in for index and Val in enumerate ratings if ratings and I want to go for okay I'm just going to skip the first index equals z continue because I can just start with n starts like this okay so if Val is bigger than index of ratings of index - one ratings of index - one ratings of index - one then final vales if it's bigger than it need to have more candy final vales equals um uh ratings of index - 1 + 1 so it gets at least one it index - 1 + 1 so it gets at least one it index - 1 + 1 so it gets at least one it gets one more candy than the person to the left and then H if else L Val else I think we can go down but my question here is how down we go because let's say we have so 1 2 3 one if that is the case we could just say first one gets n second one gets n plus um no 1 2 3 2 second one gets n + 1 third one gets n 2 second one gets n + 1 third one gets n 2 second one gets n + 1 third one gets n + 1 + 1 which is 2 and the last one goes + 1 + 1 which is 2 and the last one goes + 1 + 1 which is 2 and the last one goes down so it goes down it can just go and be like hey um just uh give me n that's it but if it was to one then the next one would be nus one and then we're going that too far down and we don't want to go so far down we want to go um we would need to go like this so it would match because we cannot get we cannot do this so that's like the tricky part I'm not sure if we could do this we can do this in a linear way as in we just iterate once over everything and that's done um I don't know so there's one way to solve it there's actually one way to solve it that I know that we can solve it with and let's say import pop yeah we have pop pul dot let me just check the documentation on Pulp if you guys don't know what pulp is Pulp is for linear programming and if you don't know what linear programming is it's a way to formalize problems and get uh in the in a linear with linear equations and linear inequations like inequalities like smaller equal bigger equal and then you can get results just from that so uh Loops ination Concepts modeling process formul gosh where's the pul code case study actually transport problem I think this is what I want so from Pulp import all of this and we create a problem which is to minimize problem we want to minimize candy and there's let me just use another one then we need to create variables and we can do for I in range so um let me just look okay so these are the kids for I in range length of kits we create L LP binary so not binary actually well l p integer and that is what's the API for it oh don't one it's not this one so I create an integer variable LP variable and then the name is a candy for kid and then it's I and uh low bound is one because it needs to have at least one candy and category is LP integer that's the category so bars is this andar we have the variables there so for uh for I index in range length of KS now what we do we need to say that the variable it needs to be bigger or higher than the next one so if actually so we're comparing to the right if index + one is smaller than right if index + one is smaller than right if index + one is smaller than length of G we do this um so if kids of index is smaller than kits of index plus one so you can I can just do this now I need to check it if kids index is smaller than kits index + one then uh vars of index needs to be so what was the thing if this one is smaller than this one the one that is to the right needs to get more vs of index + one needs to have more candy index + one needs to have more candy index + one needs to have more candy than vars of index so the result which is the number of candy for kid this one needs have more candy than this one else v um vars of index must be equal or smaller than kids I think this is the only constraint though children with a higher rating get more candies than their neighbors oh it's the same so LF case of index is bigger so if this one has a bigger rating for bars of index must be bigger than bars of index + one that's it and now we do problem. solve and result uh actually it's not result it's status or something oh and then we need to do prob plus equals problem plus equals then it's solve and then we need to check the status but I think the status comes in the result nonetheless and then for each variable I print it and that's it so what's up can maybe defined or defined from St import Imports so kits is one2 let's run this uh this one needs to be bigger or equal so it doesn't support bigger so we can do needs to be bigger or equal than this one + equal than this one + equal than this one + one I think that's like U one like hack around this so bigger equal so if this is two and this is one this is bigger and if we do plus one it's bigger or equal but if both of them are two this becomes free and then that's not true okay so what was the solution output five yeah so 2 1 2 + 1 + 2 = 5 so 2 1 2 + 1 + 2 = 5 so 2 1 2 + 1 + 2 = 5 so here we have our solution um total candy equals zero and then we total candy plus equals the VAR value so let's see let's say this will not work be why won't this work because I don't believe that lead code allows for this so we change kits to ratings we remove the prints and I need result oh yes I do need results I didn't check this thing only allow that start import only allow that much level okay so from Pulp import LP problem LP minimize LP integer LP variable so kids ratings boom result is one assert result equals one and return in of total candy because I think the solution comes as a floating and we need to return it so let's just submit no module name pop okay like in my defense I solved this problem I just don't know how to solve it in the way that they want okay so I'm just going to look at some solutions so size if size small or equal to one me turn size so it's one candy for one kid Zero candy for zero kids create a vector if ratings actually I thought about something like this does this work no really so according to this I hope you guys enjoyed the linear programming thing but according to solution if you iterate once and if it's bigger then you just do ratings of I and is bigger than ratings if ratings of I is bigger than the previous one you just increment one then you in then you do later the backwards Loop and if the next one is bigger than that one the next one will be the maximum between the current one + one and the between the current one + one and the between the current one + one and the next one so let me actually draw this let's see one 2 3 1 5 so we create an array of ones and then I iterate over them and if the next one is oh if the previous one is bigger was it like that if the previous one if this one is bigger than the previous one this one equals the previous one plus one so 1 two three and then we keep one that is two so then we iterate again but we start from the end and at the end we have two I guess and if the next one is bigger right is bigger which is not the case so this will do nothing and if this one is bigger then this one is the maximum value between this one and the previous one oh this one + one or the pre then the next one is the maximum value between the current one + one or the between the current one + one or the between the current one + one or the value that it already has so in this case the this one + one has so in this case the this one + one has so in this case the this one + one will be two or three it will be three and then the next one keep it cuz it's not bigger than this and we get it's not bigger than this so yeah I think this is right so 1 2 3 1 5 is yeah we go down again okay seems to be pretty simple now that we look at this but how does this work so yeah it works on we create we do all the ascending are fine and then we just check because this like drops like crazy yeah it drops to one CU it's a minimum one minimum value and then we just check hey maybe we can't drop that much it all depends on what's left so you it also needs when it's decreasing backwards when it's increasing backwards we need to assert that this one is bigger than this one if it's increasing and this one is bigger than this one if it's increasing but it doesn't break the increasing from the original order okay that makes total sense so let me just code this pretty quick so final values equals 1 * the length of * the length of * the length of ratings so for um index in range length of um ratings I think I can start with range one cuz I'm just comparing to the previous one and if ratings of index is bigger than ratings of index minus one then ratings of index equals ratings of index - ratings of index - ratings of index - 1 + 1 and then oh sorry final values because we check the ratings and then we update the final values so then we do the same thing but backwards so for index in we start at length of ratings minus one and we go all the way to do we go all the way to zero no we don't so we go all the way to the first one the index one so zero is not included minus one because it's a decreasing thing so if ratings of index are bigger than ratings of index PL so let me just look at PS we're doing backwards so we want to check if this one is bigger than this one no we want to check if this one is bigger than this one right yeah so yes we want to check if this one is bigger than this one and if this one is bigger than this one so if index is bigger than index + one that index is bigger than index + one that index is bigger than index + one that index is bigger than index + one final values of index will be the maximum value of final values of index or and or uh final values of index + of index + of index + 1 + 1 and then return sum of final values and in this case it should be five two and yes we want to go to one want to go to zero 212 yeah if this passes oh let me just give an upload cuz that make sense okay I need to give an upload I think it was this one yeah UPF so guys I hope you enjoy this it was a long one but yeah he has two solutions that I presented see you
|
Candy
|
candy
|
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
Return _the minimum number of candies you need to have to distribute the candies to the children_.
**Example 1:**
**Input:** ratings = \[1,0,2\]
**Output:** 5
**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
**Example 2:**
**Input:** ratings = \[1,2,2\]
**Output:** 4
**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
**Constraints:**
* `n == ratings.length`
* `1 <= n <= 2 * 104`
* `0 <= ratings[i] <= 2 * 104`
| null |
Array,Greedy
|
Hard
| null |
48 |
all right so this question is rotate image so you want to rotate the image by 90 degree clockwise so you know you don't need to allocate the memory to rotate so if you don't know the trick here's the trick so let's not look in the rotated image let's look at the original one so the idea is that you want to swap the rle from the starting and ending so this one will swap with this one and then the middle one will swap with middle one and then you know just keep doing this right so this will be pretty straightforward for the swap Rule and once you have the swap rule it will become what 7 8 9 4 five 6 one 2 3 all right so if you notice that like look at it this is a rotated uh image right so let's look at this 741 this is 741 right 852 9 63 963 so the only thing it has to be swap is diagonal value swap the diagonal Val this one with this one so it's basically is Traverse starting from zero Traverse z0 0 one with one Zer 0 two with two Z and 03 if there is a 03 then you swap with uh three Z and then you go on the next one which is going to be one so you swap with this W with this column swap like this and then you get you'll get a final rotated image so let's look at the example two it's a little bit bigger but doesn't matter it's going to be a sens so I'm going to just you know swap my uh rule so it's going to be 15 14 12 16 and 13 6 uh 3 six 3 6 7 2 4 8 10 5 1 9 11 all right now we I need to swall the diagonal so diagonal is going to be this with this right so it's going to be uh 15 doesn't change 14 12 and this is 11 this is 13 uh two I was doing this one two and five right so 15 30 2 and 5 and then 15 14 12 and 16 right this is 16 all right so um how about this one we going to swap with this one right 6741 674 one and this will be what 9 and 10 your a doesn't change right and then this will be the entire you know solution so let's start writing so what you need to do is what swap rule matric swap rule matri swap diagonal matri right then we just Define the swap rule matric so I can say for Loop right for in IAL Z and also Jal to what last value minus one I less than J right I less than J and i++ than J and i++ than J and i++ Jus and I will say temp Ral to what matri I matri IAL to matri J to 10 rule then I will have what public voice swap diagonal in matric so it will become for I for Loop IAL to zero starting with zero I less than matric lens and then i++ and for in J will become starting i++ and for in J will become starting i++ and for in J will become starting with I this is because you always you know starting at this index so it's going to be 0 1 one 22 3 three and so on so it's going to be this 0 one and next one is going two and 3 three right so um yeah keep going and J less than a l make z l and then Plus+ so what we a l make z l and then Plus+ so what we a l make z l and then Plus+ so what we need to do is s 10 going be matri i j matri i Jal matri a j i matri a j equal to 10 if I have no typo it should be okay yeah I don't have typo right all right so the time in space let's look at the Swap this is all of n represent the what the rule in the matri how about this is all of N and this is all of n right so the wor Cas for time is going to be all of M * n space is to going to be all of M * n space is to going to be all of M * n space is going to be constant so if you have any question leave a comment and I see you later bye
|
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
|
678 |
Hello Everyone and Welcome Back to my Channel Algorithm Hk Today I am going to write the code and also explain to you all the algorithm to solve this valid penis string which is there in lead code it is a medium level problem and we are going to Solve it using a Stack Data Structure and Ag Greedy Algorithm But before moving on to the solution please like the video and subscribe to my channel if you haven't already also tell me my improvement points in the comment section datchi in the name of Shri Krishna we people In this question a string will be given S that consists of only three characters that is the left parenthesis or it is also called open parenthesis and then the right parenthesis which is also called closing parenthesis and star is ok return true if S is valid now we What people have to do is to return true if s is valid and if not valid then return false ok now following rules define a valid string any left parens m must have a correspondingly one will come correspondingly ok and star could be treated As a single right parenthesis how can we treat a star? We can consider a single right parenthesis either we can consider a single left parenthesis or we can also consider a MT string. Okay so basically what will the star do in any one This will complete the lack of parens or if everything is going well then we can also treat it like MT string, so whenever this parens is valid and comes with something like this, keywords come in our mind, something or the other is always in our mind. It comes that the stack is going to be used. It is a very famous question. Valid parameters are also there in which we check. There are multiple types of parameters in it. Not only these ones but the round ones, the stack is going to be used. Basically now why greedy algorithm? We are saying this because whenever we get an opening parenthesis or a left parenthesis, we will put it in the stack or if we get a star, we will put that also in the stack, but whenever we get a right parenthesis, what should we do? It used to be there in that case too that by pairing that right parent with a left parent and removing both of them means discarding that yes, it has become a pair, now there is no need to consider it. So, the greedy thing is that whatever left parenthesis or star is coming last, we will pair it with the right parenthium and throw it out. That means whatever current best solution we have is getting with the right parenthesis. To make a pair, we are making it a pair and separating it, so this will take a greedy approach. Okay, so basically what we will do is that we will take two stacks, we will take one left parenthesis to store whatever index is present. And whatever index the star is on, it is okay to store it. Now we are doing this because we will always have to keep track of the fact that if the star is coming after the left parenthesis, then instead of the right parenthesis. can be taken and a valid string can be formed, but if the star is coming first in the left parentheses, then even if it takes the place of the right parentheses, it will not make any difference, it means first the right parentheses and then the left parentheses. We cannot consider the parentheses as a pair, okay according to the rule of thirds, so we have to keep track that the star is always coming after the left parentheses, then only we can treat it as the right parentheses and then move ahead. Otherwise, we cannot do this, so we are taking two stacks. Okay, to understand this, let's do a dry run on the last example. This is string A. Okay, so its zero element is the zeroth index. Beyond that, there is one. Opening that is left parenthesis is present, so what we will do is that we will put its index in the stack which is left parenthic, that is zero, okay, now there is star, next is okay, that is the first index is present, so here we will put star in the stack, okay. Now the closing parenthesis has come, so first of all we will see if any element is present in the left stack. If it is present then we will pop it from the stack. Okay because for the closing parenthesis we will not add anything. Then again the closing parenthesis. Then we will see that there is nothing present on the left, but the star can take the place of the left parent and we will pop that out too. Okay, in the end the left parent will also be deleted, the star will also be taken from the left stack. It will be MT and the star stack will also be MT, that means our entire string is valid, we have created all the pairs and discarded them, okay, so we will return true in this case, okay, now like if there was a case like this. Here the star is coming first ok and then we have an opening pencil ok T is the left pencil so what do we do in that case we would have put the star ok here we have zero and also the left pencil. Putting 'y' but 'one' also the left pencil. Putting 'y' but 'one' also the left pencil. Putting 'y' but 'one' is fine but we see that here when this string is finished, after complete processing, both left stack and star stack are not MT and are not empty, that means we have to see whether any such pair is formed. What can we do so that we can discard it, that is, the left parenthesis comes first and the right parenthesis comes later and their pair is formed. Okay, so what we will do to check this is that we will see which element is present on top of it. The element which is present on the top of the left stack is coming before the one which is present on the top of the star or not. That means is smaller than that. Otherwise we will check that the one which is less than 0 is not that means it is the left one which is coming after the star and even if we replace the star with the right parenthesis then still a pair cannot be formed. Valid pair is ok so that means in this case we will return false. Okay, and to consider the same thing, here we have taken a stack of integers in which we are storing the left parenthesis and the position of the star. Okay, this will be a very simple code. So much complexity of integers will be taken by one. We will name the left one, we will name it star, okay, we will initialize both of them then for int i equal to 0 i lesson s dot length i plus okay, to find the position, if we have an opening pennis at the current position, what will we do left stack If it is a star then what else will we do if it is a star then what will we do if it is a star then its position is ok and if not then what will we do then if we do not have left penis and star If it is not there then what will we do, we have right parenthesis, first we will understand it and then we will check that the stack on our left, if it is not MT then we will pop one element from it, okay and if it is MT then check. What we will do is that if the star is not MT then we will pop it from the star and if both of them are MT then what we will do is return false. Okay, that means Correspondingly is passed and neither can we make it through star. Okay now. After this complete processing, we will see that till the size of the left becomes zero, we will see that if the size of the left has not become zero but the size of the star has become zero, that means our left parent is left and its corresponding star. So we have checked the size one, you will see that the top element is present in the star, which we will see if it is bigger than the star dot peak, if it is bigger than the left dot peak, then that means we will pop the corresponding element and in the left. Okay, and if it is not then it is not big, that means it is small, then the star is coming before it. For the left penis, in that case, we will return false because there is no such pair. And finally, after all this processing, if there is no false return anywhere, that means our string is valid and we have to return true. Let's run it and see that the legal start of expression is coming here. Okay, I have added the new keyword. I had missed it here, now let's run it again and see that here also it has become small. Ok, the sample test cases are being run, let's see after submitting and the code has been successfully submitted. Before leaving, please like the Video And Subscribe To My Channel And Also Tell Me In The Comment Section If I Need To Improve The Content Or Approach Anything It's For The Video Radhe
|
Valid Parenthesis String
|
valid-parenthesis-string
|
Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left parenthesis `'('`.
* Left parenthesis `'('` must go before the corresponding right parenthesis `')'`.
* `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `" "`.
**Example 1:**
**Input:** s = "()"
**Output:** true
**Example 2:**
**Input:** s = "(\*)"
**Output:** true
**Example 3:**
**Input:** s = "(\*))"
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is `'('`, `')'` or `'*'`.
| null |
String,Dynamic Programming,Stack,Greedy
|
Medium
|
763,2221
|
380 |
question 380 insert delete get random at constant time complexity from liquid so the question is asking us to implement a randomized set class so this shows this is a design question and this class it's supposed to insert delete and get random at constant time complexity so when we are talking about constant time complexity for insert and delete the first thing that comes to my mind is either hatch map or set and we can use that to insert a custom time complexity and delete a value from the hash map in constant time complexity as well and the tricky part is going to be the get random that we need to have or um like values from the hashmap in somewhere that we can get a random of uh like value from it when we called this function so this is when we need to decide on how we are going to do that let's jump to the code and see how we can solve this problem as i mentioned uh we can insert and delete or remove in uh constant time complexity from a hatchback so this is a randomized set class that we have here we are going to implement three functions one for insert one for delete and one for random and what we need here for insert and delete is a hash map that we can insert in one and delete in obon as well but we should think ahead of time for the get random as well because uh in the hash map if we use the get random over the keys we need to convert it to a list first and then we can get random which is going to be o n and which is going to be linear time complexity and we don't want that so from the beginning we are going to define at least two which we call it the store and we store every single value that we are going to put in the hash map we are going to put it in the store as well so let's do that so in insert what we are going to do we are going to check if the value does not exist in the hashmap we are going to add the value as the key in the hashmap and the value of this item that is being added to the hashmap is going to be the length of the store and we are going to append that value in the store as well so let's say why we need to use length of the store as the value of this key in the hashmap because this way we can store the index of that value in the list so when we need to call this value we just need to call the index we know the index and we can call that so let's go through this example and see how we can do it at the beginning we need to define the class and after defining the class we are going to have an empty list and dictionary and then we are going to insert vote in the dictionary so for inserting one in the dictionary as i mentioned we are going to insert the value as value of the dictionary and the length of the store as the key as you see the list is empty so the length of the store is going to be zero so we store value one with as a key and zero as the value and we insert one in the list as well now we need to insert two the same thing will happen but this time because the length of the list is not empty and it's one so we are going to have value one as the value of this uh item in the dictionary and the list is going to be one and two and then we insert three and insert 4 and as you see here this is the outcome of the inserting value 1 2 3 4 to the hash map and to the list now we need to remove two from the hashmap and this is where it gets tricky as you see here if we have uh we check if we have value two in the hat in the hash mark which is going to be constant we check and if we have it we need to remove this value from the dictionary and like oh sorry it's two so we need uh to remove this value from the dictionary this one but it's not easy to delete it from here because we need to iterate over the list and find two and then remove it and we don't want that for avoid doing that we know that we have stored the index of the value 2 in the dictionary which is index 1 as you see 2 is located at index 1. what we are going to do we are going uh to and we know that in the list the for removing an item is gonna be uh linear time complexity but we are going to do it in constant and the only option that we have to const then to remove an item from at least in constant time complexity we know it's dot pop this is the function that we can use to remove an item from at least in constant time complexity but pop is going to remove the last item always so we cannot remove four instead of two what we need to do we need to replace these two or switch these two so we have four here and two there doing that it will cause a problem in the hashmap as well because if we put 4 here and 2 there so now 4 index is not 3 anymore and it's going to be 1 and this is where we are going to handle this problem so what we are going to do we are going to get the value that we have at the end of the list this way we are going to get value 4 so we have 4 here now we need to get the index of the value that we are going to remove the index of that value is 1. now we need to update the value of the 4 to the index that we got so now 4 is going to be 1 instead of 3. and then we need to um replace the value that we have here let me do this so now we need to replace the value that we have at index 2 with the last value that we had here so we're going to put 4 here and finally what we need to do it doesn't matter what we have at the end we know we can remove that from the list and also we are going to remove the value from the dictionary as well and we are going to do this all in constant time complexity which is o1 so let's um iterate through this and after removing this we are going to insert two so now you know when we insert two it's not gonna be at the previous location that it was it's gonna have a new index which is going to be three and now we are going to get a random value here which is going to be for example three and the way that we do that is because we have this list here which we have taught about that from the beginning now then the random dot choice time complexity is all one and because we have lists if it wasn't list we had to convert these to a list and then run the that choice over it but because we have a list the time complexity is going to be one and then for deleting we have to go through the same thing as i mentioned we are going to find the value one and then put it at the end and then um we were going to update the index and so on and uh if we are looking for example for um removing value one because we have already removed that like or if we want to insert value one if we have it in the list it is going to return false thank you
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
403 |
welcome to another video so let's start the question but before that let's start with the joke of the day so the job is how to ask for money from your dad example you can hold your mom hostage okay let's start the question so the first question i got the idea to this question last night while i was sleeping so a frog is crossing the river is divided into some number of units and at each one there may be or may not exist a stone that's not can jump on a stone but it must not jump into the water given a list of stones is positioned in units insta sorted ascending model determine if the fog can cross the river by landing out on the last stone initially the flow is on the first one and assume the first term must be one unit if the frog's last term was k units the next term must be either k minus 1 k or k plus 1. so in this example the first example we made to one then it can be made to three then from with a jump of two then with a jump of three the jump can be made to six i'm guessing and with the jump of four the jump can be made to twelve no through six the jump will make up two ah i did something anyway so the first jump will be second stone then it will be the third stone that is one third then two units to the fourth stone that is five and three units to the sixth zone eight then seven stone twelve and eight stone okay so let's take this example 0 1 3 5 6 8 12 17 okay so the first jump will be made to one i thought about making the priority queue which will store the stones value and the jump that was made there so this one will store one this goes in the practically now i can add three places from here that is the last number is one unit so i can make with zero unit one unit and two units so with zero unit i will go to one zero and with one unit i will go to two and two units i will go to three now i go to one but i am already at the stone one so i pop i can pop this out now i go to two now in the priority queue next element is two is there a stone that is uh that existed two i will i trade this again until i reach this 2 now next one is at 3 which is greater than 2 so i can pop this out because 2 will not exist anymore later in the queue in the array then i go to this is equal to three so i can make a jump from here i have the last jump was two units so now i can make two one unit two units and three units so the queue will be added with four five six one two three these are the jumps now this will be removed now i go to four is greater than three so i hydrate it next is five it's not equal to 5 is greater than so i in this so i can remove this now with this 5 i can jump to 5 with 2 units so now from here i will add one with one unit two unit and three units so one is going to be six one seven two or eight three now i can remove this so i go to six three so six three is greater than this then i will iterate it over here oh there exists a six so i can add three more i think three more jumps that will be two three four so that will be eight nine ten now i go to sixth one six one again uh in the next elementary school six one again three will be added uh when three will be added that will be one that will be zero one and two so stick zero will be added six seven one will be added and eight two will be added this is this will be removed now go to seven is greater than this so i trade over there eight is greater than seven i can remove this eight is equal to this so this jump can be made and three more will be added four three and two that will be give me 10 11 12. 2 3 4. also this will be a priority queue so 6 7 will always be removed before we go to 8. so i won't have to worry about them i was thinking of making a particular i don't know if it is necessary or not yes it is kind of necessary so six and seven they will be removed before the going through these the six will actually be here and seven will be here so i think you will kind of get the rest of it eight will be somewhere around here so i will start coding i think this should get me the answer let's hope it's the right way to do this let's start with the code okay first you need a priority queue but let me just drink some water okay so now let's see okay so there will be the position of the frog initially it will be zero okay let's just call it i only okay so now i have the priority queue what else do i need so the first one will be what was the first one so if whenever the queue is empty means that we did not release the last position so i can return false okay so as i was saying yes stones of i is less than let's call this is so s jones of i is less than or i can say while the size okay now i can stay a while i is less than and i equals i think here i can do that okay so now i'll store is so here like this is one will be encountered now i can add other elements so is equal to so if basically if this is equal to that i can add the spq dot push go plus last term minus one now here last time it will be added now last one plus one will be okay basically if this is not equal to that means i reached a element that is greater than that basically like here 5 and if it is 2 then i can remove this element i can simply pop this out oh that is already popped so i don't need that right yes this like i was on three now i go to two so two is already popped out i don't need to do that anything i will simply go to three and three will add other four other three that will be four five six now again we'll go to five four is less than now we don't do anything it is also popped out then we go to five okay we don't need this else okay now the thing is that i need to uh okay i will only be iterated over there the stones of i is equal to curve here i can say if i equals to n at any point that means we have made the jump to there we don't want to go ahead from there i can simply return true this should be size minus one i think zero one two three four five six okay if i at any point is equal to n that means we can return true this basically means the jump has been made to this stone and i can make three more jumps from here okay let's try and run this false okay statement okay last one okay what problem are we facing here again um zero the one 4 i will add 17 3 18 6 and 9 7 45 this should be four plus three less than curve okay oh come on so basically the priority queue does not store from smaller to larger it will store like this three two one so i need to make it minus three or minus two minus one then it will store by uh minus one minus two minus three then i can simply leave it with a negative sign okay very stupid now this will be minus i always forget this yes now the answer is now i am thinking if i need this last something or not maybe i don't need this let's try first submitting it like this then we can remove this if statement if you want i hope they are time limit excluded flies okay so now in this priority queue i am adding multiple elements of the same value like from 2 3 will be added and 1 3 will be added also okay so the next few thing that comes to my mind is basically maintaining a dp but so that okay i can make a dp based on array but the stones is this jumps can be anything i think so if the last number is one then there's a possibility if okay but that four can also one can also be added from three two as you see if i made the jump to three from two units one two three with two units then one four one will also be added and if i made a jump to three from two with one unit then also four one will also be added so okay maybe we can try this i don't know if this is gonna work or not let's see well pq is not empty and pq dot top second equals to last term and pq dot pop dot first equals to basically i am removing the state test same basically like four one was added i will remove that forward uh multiple four one was there over there so i can remove them okay see if it makes it any faster it's still very slow i think so because that whenever ti comes okay so now it's the problem with the code how is it changed or anything i did not add this now wait a second how am i doing oh sorry i kind of oh i made the changes over here i did not uh so they are not reflected on a command okay here while is okay still um is okay come on now again this minus you can all take to try to make the changes over here um ah you um okay so this one is there's no body um how is this running into a tle i have no idea just wanted to go it wasn't now it is the problems are now still running into dna where i is what is the problem here is it this thing okay how is this such a big deal yes okay 26 milliseconds i don't know if that's the right my concern is how am i supposed to use dp like uh already the stones is this much thing so the example jumps can be exponentially very large like it will keep on adding plus one so they could be very large now although it is a kind of a good run time i'll say that i think it's a decent solution so this should be good see you in next video
|
Frog Jump
|
frog-jump
|
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.
If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.
**Example 1:**
**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
**Example 2:**
**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
**Constraints:**
* `2 <= stones.length <= 2000`
* `0 <= stones[i] <= 231 - 1`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order.
| null |
Array,Dynamic Programming
|
Hard
|
1952,2262
|
153 |
hey what's up guys Nick white here I do tech encoding stuff on twitch and YouTube check the description for all my information please support my own you know whatever if you got Amazon Prime I got that twitch I got that patreon you can join the discord you like and subscribe all of you know all that stuff but I know you're here for me to shut up and get into the tutorial and leak code or whatever so let's do that I just made this video but the screen was black for some reason so we're doing it again this is a binary search problem binary search is very important it's you all it's almost a in like all internship interviews I think and then variation problems are like used to weed out candidates and online assessments and stuff it's really common there's a lot of variation problems so this is a variation problem find minimum in rotated sorted array so we're basically we're given a sorted array it gets rotated and then we want to find the minimum element into it so it's not too difficult it's actually pretty easy suppose and arrays sorted in ascending order and rotated some pivot unknown to you beforehand so we have a you know regular array sorted 0 through 7 right 0 1 deserve those zone it gets rotated so that the 7 gets put to the front the 6 gets put to the front 5 4 so it's like four rotations to the right and they all get put to the front and then it comes this and it's still somewhat sorted but you know the you could tell it's only sorted on one half and then it's sorted on the other half but there's this little discrepancy here and just noticing that's basically how you figure out where the minimum is this discrepancy and you just do a regular binary search and you handle a condition where you check for this little issue where the you know in a regular sorted array you'll notice that like every element is greater than the element before it right ones greater than 0 2 is greater than 1 5 is 4 is greater than 2 4 you know it's greater than the element right before it but in when you rotate it everything's greater than the one before it except the minimum which is what we're looking for so if we just check ok is the element we're currently looking at greater than the one before it if it's not then like then we found the minimum right because that's the this is the only time it occurs in the road a sorted array so it's really an easy problem you just do a variation of binary search where you adjust the boundaries I'll explain how you adjust them but yeah here's an example this is rotated it used to be one two three four five now it's three four five one two one is the minimum this is you know same thing minimum is zero it's just the smallest element we're doing this logarithmic time obviously you could just scan through linear but that's gonna give you a F in the interview probably we're doing binary search because that's the only log n time when you see sorted array always think binary search it's binary search that's what we're doing it's all good I mean that's pretty much it all right that's I think I explained it all so if nums dot length is zero then there's nothing in the array so we'll return negative one okay if nums dot length is one there's one thing in the array so we'll return the first element return nums of zero okay great now there we know there's at least two elements in the array so we could start our binary search ain't left is zero into right is an um stop length minus one just like regular binary search numbers dot right two numbs dot length minus one sorry you do your little thing while left is less and right in midpoint is equal to left + and right in midpoint is equal to left + and right in midpoint is equal to left + right - left / - some people just do you right - left / - some people just do you right - left / - some people just do you know right - divided by two or whatever know right - divided by two or whatever know right - divided by two or whatever you do you know or some people just do left flows right / - or whatever you left flows right / - or whatever you left flows right / - or whatever you want to do this is the proper way to do it from what I understand because of energy overflow so that's the only reason you could do length / - you know reason you could do length / - you know reason you could do length / - you know do whatever you want but I'm doing the right way so if you want to be smart to it like me we're gonna be doing a variation so that the boundaries keep adjusting and we're either gonna find it within the loop in which case we'll return otherwise we'll return nums have left at the end because the boundaries will and where we find the element okay so what are our conditions so our conditions are we have an array right oh my god my sketch of everything just went away I had it all in the last video but that I tried to copy and paste but it's gone okay whatever dude okay we have an array and what the main condition is basically I'm not dealing with this and if numbs if the middle L you look for binary search you know when we look at a binary search right we have 0 1 2 3 4 5 6 7 right normally you have a target if we're looking for one right you look at the middle element and then you say okay is this less than is the target one less than the middle element okay then we delete all this and we look on the left side and then we look in the middle you know what I mean you keep deleting half of it each time in this case we're gonna be deleting half the search space each time but since its rotated like this then what we're gonna want to do is we're gonna find where it's not sorted so for example if we look at the middle let's get a better example here like let's do 0 1 and then put 2 over here right if you look in the middle like 6 or 5 and you say ok this side is sorted I want to look on this side you want to look on the unsorted side that's where you're gonna find the MIT the minimum element because there's that discrepancy of now no sorting right here so you look and you could check if it's sorted because you could say okay we have references to the left and right boundaries so we check the left in the middle and we say ok is the left less than the middle is 2 less than 6 ok yes then everything is within them is sorted as well we know that for a fact because it's already sorted it was just rotated so if this if 2 if the start is less than the middle this side sorted so we want to adjust our boundary and look on this side so we delete everything and we look on that side if it was the other way around for example you know it was you know like 7 0 1 you know what I'm saying then we would look at the middle like 2 and we'd say okay is you know we could do the same thing on this side is sit is 6 greater than 2 is the last element greater than the middle okay we know everything's sorted because it was sort of just got rotated and then we know it's on this side so we just look on the left side so it just is you're just changing the boundaries based on what side you want to look on in the condition is okay if the current number we're looking at is less than the number right before it then we found it because the in a sorted array the number that your is a number is never less than the number before it the number is always greater in an ascended sorting array so we just returned the element because that's what we're looking for so we just returned um to the midpoint we found it boom this is the find condition and you want to do also this if midpoint is greater than zero because if midpoint is zero then you go out of bounds because midpoint minus one would be negative one and you don't want to look at numbers of negative one that's out of bounds so that's the only reason for this but you're just looking okay when we find the break then that's where it is okay otherwise we want to adjust our boundaries if nums have left if the first element is less than or equal to numbers of midpoint meaning it's sorted on the left side and it's not sorted on the right side we want to go to the not sorted side to find the pivot the break so if numbers of midpoints is greater than nums of right that's incorrect right that's not sorted on the right side so since you want to go on the right side you make the left go to the midpoint plus one you adjust the left boundary push it in the left it gets cut out you're on the right side otherwise this means that the left wasn't sorted so you want to go on the you want to adjust the right boundary to go towards the left there you go that's it let me know what you guys think I'm sorry I already just did this video and then it went black and then you know I lost all my I gave this little tour boolean int cannot be if numbers admit okay this is stupid sorry I gave this like walkthrough of the code and everything but you know it did I tried to copy and paste it but it didn't copy apparently so let me know yes think maybe it was a bad explanation but I mean really you did like you know what I mean it's not that difficult like you ever you have a sorted array it's rotated it becomes this and then you look for the side that it's not sorted on you keep adjusting the boundaries until you get closer to that and then the you know what I mean like you go on the right side you don't look at this anymore because you know it's already sorted so it has to be on this side and then once you find you just keep checking the elements and once you find an element that is less than the element before clearly that's the minimum because that never happens unless it's the minimum you know that's it couldn't be more straightforward in my opinion so let me know you guys think thank you guys for watching I appreciate you guys I comment below I like you guys and you know I love you and you know you make my dreams come true and you know thank you and good night I'm going to bed thank you for watching bye
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
306 |
my name is eric lee and today i want to talk about recall 306 additive number ltd number is a string whose digits can form additive sequence and what do i mean let's let me give you an example for example one the input is one two three five eight if we record one as the first number and the one as a second number then we will find an interesting things 1 plus 1 is equal to 2 which is the following character and 1 plus 2 is equal to 3 and 2 plus 3 is equal to 5 and 3 plus 5 is equal to 8 and we call it additive sequence so if a string can form a division curve we call it editing number so for this case we will written 2 and for example 2 if we regard the first character as a first number another second and third character as the second number we will find less 1 plus 99 is equal to 100 and 99 plus 100 is equal to 199 then which we know that it is also an additive sequence so how can we solve this problem we will find it if we decide whether is the first number and the second number the following sequence there is only one way to form the following sequence so we just check all the positive variability of the first number as a second number then we can get the solution let me give you an example for the first example we can start from the first bit number we can regard the length one and then the second number we can regard as that's two and we can share all of the possibilities it's the first possibility and for the second one we can share the first number is one and the second number is one two so by this way we can share all of the possibilities but for this example we are very lucky because if we said the first the length of the first number is one we can get one and the length of the second number is one we can also get one and we will finally one plus one is equal to two one by two it should go to three two plus three is equal to 5 3 plus 5 is equal to 8 then we know it is an additive sequence so it is a additive number but for example 2 if we start from the first number its length of the number is 1 and the length of the second number is one we will find late the first number will be one and the second number will be nine however one times nine is equal to ten and if it is not ten so we know that it is not an additive sequence so we can check the second possibility which is the length of the number is one and the length of the second number is two then we can get one and 99 and for this case we can find 1 plus 99 is equal to 100 and 99 plus 100 is equal to 199 so we know say it is an additive sequence so the key idea of the solution is to check all of the possibility of the first number and the second number and then we know that if we check we will set the first number and the second number the following sequence there is one way to form the following sequence so we just check whether the following sequence is equal to the input if it is equal then we return to if not we just check the next possibilities do is to know how to implement this idea and i can implement this idea by this code and for first three lines what i am doing is to enumerate all of the possibility and we can let the num one and num two either of the possibility and lately is a tricky part here because the problem we cannot allow the leading zero however zero itself is okay so we should check whether the length of the number one and number two is equal bigger than one if it's bigger than one it has a leading zero it cannot be an additive frequency so we just check the next possibility and here is the implantation of check the following sequence if we know that if we know num one and none two then the following sequence should be num three so for the remain string it should start with the num3 if we did not start with the number three we should break the while loop and check the next possibility and if we if it start with a number three we just add it into let's say and at the end if j is equal to n we know that the following sequence is equal to the input so we just return 2 and if we can not find any of the possibility can form an additive sequence we just return false the next thing we want to share is whether what is the time complexity of this solution for these two for loop because we want to share all the possibilities it will be unsquare and for this part because we just want to check the further the following sequence is equal to input and the integral with big o n so total time capacity of this solution will be big o n to the power of three because for this problem the next n is 35 sorry let me see here you can see the concern here the max end is certified so it is okay to implement a big o n to the power of 3 method so it is a solution of this problem thank you for watching my video and have a nice day bye
|
Additive Number
|
additive-number
|
An **additive number** is a string whose digits can form an **additive sequence**.
A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given a string containing only digits, return `true` if it is an **additive number** or `false` otherwise.
**Note:** Numbers in the additive sequence **cannot** have leading zeros, so sequence `1, 2, 03` or `1, 02, 3` is invalid.
**Example 1:**
**Input:** "112358 "
**Output:** true
**Explanation:**
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
**Example 2:**
**Input:** "199100199 "
**Output:** true
**Explanation:**
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
**Constraints:**
* `1 <= num.length <= 35`
* `num` consists only of digits.
**Follow up:** How would you handle overflow for very large input integers?
| null |
String,Backtracking
|
Medium
|
872
|
953 |
hey everybody this is Larry this is day two of the February legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's spot where to find an alien dictionary 953 all right so yeah but possibly in a different order the order of the alphabet some presentation of the lower case that is give it a sequence of word and order return truth the given words are stored in that's a graphical order okay um I think the couple of ways you can do this you can one is just sort on this order and then see if it gives you the same thing yeah and then that may be one um that's gonna be unlocked and but I think you can also just look at adjacent things because um ordering in general and these things are going to be transitive right meaning that if a is less than B and B is less than C then a is less than C and so forth right um the transitive property um okay foreign so basically I think that's what we're going to do is that we look at a Json words so maybe word one word two in simple words and then we just see um yeah um basically I want to like um ordering Maybe is able to enumerate order uh for index then c Index wait something like this is this the right um syntax action it's been a while I feel like I'm mixing languages all right let me just run it real quick okay so it's not complaining it's okay so then now we just have to do it one count at a time right so yeah um foreign is equal to word two then we continue I think I want to skip that uh possible case so then now yeah we just look at it one at a time so then we can when you do another sip right for C1 C2 and if ordering of C1 is equal to ordering of C2 we continue maybe I know if ordering of C1 is greater than ordering of C2 then we return Force maybe I don't need this and then we just contain um no I mean I think that's fine otherwise we break right also instead just for slight beginning I don't know that's true okay right and then now that means that this uh thing satisfies I think actually I want to abstract this a little way so if less than or something like this right so then I can kind of be a little bit um queer oh I don't know why I bought it this way but if or maybe greater than if W2 is greater than grade 2 then we'll return Force otherwise we just return true at the end and then we can kind of re-implement this greater than function re-implement this greater than function re-implement this greater than function here say but so the U code then is returned Force and then yeah if and then just returns true because I think we change the definition um yeah okay and then now basically if it gets through the entire thing and it can only happen if this happens in time thing um then we have to check uh then we just return length of if length of word of one is greater than length of where two then this is greater than right because that means that has more characters otherwise this is going to be returning Force um yeah what is this oh no then else returned Force I think that's why I changed it this way so that's a slightly easier thing I guess in this case you don't even need else anymore um yeah if I submit hopefully I don't have any typos it looks good A 10 38 streak um yeah what is the time where it's going to be linear time linear space we look at each character oh do we even have linear space um no I mean I guess we have like off Alpha space Alpha being the size of the alphabet which in this case should be 26 characters I don't know I actually didn't look at the conditions okay um I didn't look at the constraints that hard because everything else is linear each character in words will appear uh will get looked at most twice right with the word before and the word after so yeah um yeah I think that's what I have for this one linear time constant space and yeah um yeah that's what I have with this one I'm going to do an extra Larry problem I don't know uh let me know what you think stay good stay healthy to go mental health I'll see y'all later and take care bye
|
Verifying an Alien Dictionary
|
reverse-only-letters
|
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters.
Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language.
**Example 1:**
**Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz "
**Output:** true
**Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted.
**Example 2:**
**Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz "
**Output:** false
**Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted.
**Example 3:**
**Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz "
**Output:** false
**Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)).
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `order.length == 26`
* All characters in `words[i]` and `order` are English lowercase letters.
|
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
|
Two Pointers,String
|
Easy
| null |
430 |
welcome to July's LICO challenge today's problem is flatten a multi-level problem is flatten a multi-level problem is flatten a multi-level doubly-linked list I'm a little strapped doubly-linked list I'm a little strapped doubly-linked list I'm a little strapped on time today so I'll have to make a quick you're given a doubly-linked list quick you're given a doubly-linked list quick you're given a doubly-linked list in which in addition to next and previous pointers it could also have a child pointer which may or may not point to a separate doubly linked list these child lists may or may not have one or more children of their own so on and so forth and that's going to produce a multi-level data structure our job is to multi-level data structure our job is to multi-level data structure our job is to flatten the list so that it's going to return a single flat doubly linked list here's a good example we are given this multi-level doubly linked list and we multi-level doubly linked list and we multi-level doubly linked list and we want to return just one level of linked list that's going to have the previous and next nodes so what we'll do is go in this order one two three and when we see a child we're going to make the child a next node and this child previous node it's going to be this node so it's going to go one two three seven eight once we saw child we'll add that instead make that the 11-12 that the 11-12 that the 11-12 and then we'll have to add the ones on top again one thing to note is once we have this single level doubly linked list none of these should have children so let's look at the example they give us here and kind of think through how we might go about doing this it was like this so normally when we go through a linked list we just go in the order of what one of us next right so we'll just say okay make have some current pointer that's pointing to this current node go next and if we see a child what we'll do is readjust this node to say point the next node to the child instead and have this child node point to the previous one at that point and then we can just continue on with this and we'll go to a child so on so forth but here's the problem like once we get to the end here how do we know to add now we're going to go back to nine add that and unfortunately if we only have pointers we won't remember that we have to go back to this nine because we've already changed this next to pointing this to this child so we'll have to have some sort of data structure to keep track of that we can use a stack you can do like recursion as well by I think a stack is more intuitive and we can in fact do better we could have just a stack that stores both the next and the child nodes and the order it's what matters like when we're on this note here what we'll do is add the next and then the child node to a stack and on the next loop will pop off whatever is on top so if there's a child on top then we're going to add that to be the next node and that will continue on adding this stack forward so if I have a stack here let's say we're on number one we'll add whatever is next first and since there's no child we don't add a child right so on the next loop what we'll do is say hey add whatever's on top two to this to the next make that the next node and at two we'll say okay add three so this becomes three pop that off but say at three right we'll add first the next node and then the child node and what that happens then is we'll first pop off this child one and we'll say okay this one's gonna be a next one and at seven we'll add the next one to two on top of the stack and we'll just continue on this building our stack as we make our list so just make the next one add the next one first to our stack and then add the child to our stack if there is one and that's gonna allow us to build our list each time we'll have to make sure to wipe out the previous or the nodes child one as well so let's start coding this out what I'll do is we'll first have some sort of dummy pointer that points to nothing and this is gonna allow us to keep track of what are the heads going to be and what we'll do is say we'll have a current pointer and we'll have our stack and a current pointer will just be the dummy and the stack will currently be empty one thing I should keep the track is you know if there is no head just make sure to return nothing so we'll return back the head all right so while we have the current pointer point something here's what we're going to do we're going to first pop off what's on the stack so we'll make sure to add the head to the stack first so we just have this temporary note here and say hey pop off whatever is on the stack and if this temp thing has first next add that to the stack and after that if this temp has a child append that to the stack now here's key here's what's key now we have to adjust our point our next and previous and all that so this current pointers next is going to equal now to the temp that we just popped off and the temps previous is going to be pointing to the current node that we're on and the temps child make sure that points now to nothing and finally we want to move our pointer head so you just make that equal to temp so once that's finished we should have completely readjusted our multi-level to a readjusted our multi-level to a readjusted our multi-level to a single level linked list but just make sure that when we return our head we need to use our dummy right so the dummy's points to the next is going to be point to the head and I believe we actually need to also make sure the dummy next that previous because right now the head is previously put the previous is pointing to the dummy and we don't want that so what make that equal to none so let me see if this works nope okay so oh it's okay no it's not while there's curious while there's a stack okay so I think I missed something up here what no looks okay alright let's go and submit that I don't know why that was taking so long and there okay accepted okay so like I said before there's a lot of ways to do this you can do this recursively my original approach was building a stack but only for the next ones but that like wasn't very intuitive it created all these if statements that I didn't like so this works a lot better it's an old end solution unfortunately you're gonna be using some more space as well but it's not too bad it should be pretty good as far as memory consumption and time complexity goes so thank you I hope that helps thanks for watching my channel and remember do not trust me I know nothing
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
1,770 |
hello guys today I will solve the question 1770 maximum score from performing multiplication operation the question is they will give us two arrays nums and multipliers and we need to return the maximum score by multiplying each digits of multiplier to the digits of the num and we have constant we can take the inputs from the num only other from the start or end like here in this example we need to multiply it digits of multiplier to the numbers to the digits of num but we can either take input from the other from the start or either from the end and after multiplying the digits in the name num we need to remove the digits from the num like if you if we multiply 3 into 3 now we have score 9 but we are left with 1 2 only now we can multiply to the other two or one now we will multiply two is to 2 that is 4 now our score is 13 and we are left with 1 and here we can multiply this one to one and our score will be 14. so we need to return the 40. like this we need to return the maximum score we could do like 3 is to we can multiply 3 into 1 and 2 into 2 4 and 3 1 into 3. in that situation it will be 4 it will be 10 so it is not maximum so we need to return the maximum score so what we can do we can solve this question by recursive right recursion in that situation we will do we will multiply this three either with one and we will solve other parts like multiple we will left with 1 2 and here 2 1 and 3 into 3 and 1 2 if we do three two three one two and two one now maximum of this will be our answer right maximum of this will be our answer multiply 3 into 1 and we have left other we have left others for the recursion and now we have multiplied three into three and left other question for the recursion like the other part for the recursion now we can do one thing for the base case we will make an index integer which will count the multiplier multipliers digits if we will reach that index is equal to multiply as dot size minus 1 will simply return the 0 for the base case now let's solve the question like here it is without DP now I will explain why we need to return we need to use the DP that's why I'm explaining you this solution first here we are simply calling that helper function and we are giving input index which I told you to check the base case nums is input multipliers is up for the multiplying and this is our start and this is our end like if we will take 1 from the now our start it is our start will be not 2 and 3 right if we take 3 our start will be 1 and end will be n minus 1. so that's why we are sending this as an input and if it is a base case if index is a multi uh multi dot size now return the maximum of multi index into nums index start this plus helper index plus one now our index will be plus one because we are moving to the next index and our input will be start Plus 1. because here we have used one so our start will be not 2 right now we will be left with the 2 3 so our start will be two if we multiply 3 into 3 our start will be 1 only our end will be n minus 1. so in that situation we are doing n minus 1 and start with this term so maximum of this will be our answer so we are returning this but here you will get tle time limit X time limit will be exceeded because we are doing some uh we are calling some function again and again like we are checking for same thing multiple times like let me give you an example 2 3 4 5 1 6 7 and it is our multiplier it is our num and multiplier is 1 2 3 4 5. now if we multiply 1 is to 2 and 2 is to 7 2 3 7 3 with the three and four with this four now four five we will left with the five one six right we need to check this now we are multiplying one to the seven 2 to the 2 3 to the 3 and 4 to the fourth now again we are left with the five one six four five only so we are checking this condition again and again so we can use DP for restoring this value we do not need to take input as end because we can calculate how we have this digit as a multiply this as a num now if we have indexed as a 4 we know we have used four digits of these norms and we have a starting position as a 3. starting as a three now we can say one thing we have used three digits from the start now and one is from the end because we have used four digits and three digits from the start because our starting position is at three so we must have used this one from the end so we can calculate and size is 4 minus if our index is 4 and the start position is 3. right so it is 3 so we can say our end is at the three places so like this we do not need to give input at the end so we will optimize it like this now we will calculate we will store DB in DP we need to store the value right now I will explain you why we are taking size as a M plus 1 multiplier Plus 1. here we know it will be M plus 1 but you can get confusion like why we are doing here M plus 1 because our start question is maximum can go to the M plus one size only like if we always multiply with the start position at worst condition we can get M plus 1 as our start position so we are calculating as a m plus 1 DP as M plus 1 and now we are storing that int minimum in the this DP and if our DP index is not equal to int minimum we are returning that value you know how we use this mdq so it is like this now let's run the code thank you
|
Maximum Score from Performing Multiplication Operations
|
minimum-deletions-to-make-character-frequencies-unique
|
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000`
|
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
|
String,Greedy,Sorting
|
Medium
|
1355,2212
|
334 |
hey guys welcome to a new video in today's video we're going to look at Elite code problem and the problem's name is increasing triplet subsequence so in this question we given an integer array called nums and we have to return a Boolean value true or false we have to return true if there exists a triplet of indexes i j and k such that I is less than J and J is less than K the element at I is less than the element at J and the element at K the element at J is less than the element at K if we are not able to find such indices i j k which are following these conditions we have to return false as the output if you able to find you have to return true as the output so coming to this example there exists a subsequence 1 2 and 3 so we return true and in this case it is a descending order so it does not satisfy so we return false in this case the output is true because this is a increasing subsequence of three indices i j and k so this is I and this is J and this is K now let's take a look at these examples and see how we can solve this question so let's take the first example we are given the nums array so I've taken the first example here now we have to check for three indices i j and k so we need to keep track of three values so what we can do is we can keep track of two values first and second and instead of keeping track of the third value we'll use the current iterator since we are going to iterate through the array from left to right I will start from the beginning and it will reach the end so the element pointing at I will be the third number which we are going to compare with these two values so let's create two variables first and second and I'm going to assign it with the integer. max value since we have to find the minimum possible values let us assign them with the maximum possible values initially using integer. max value so there will be 2^ 31 - 1 value so there will be 2^ 31 - 1 value so there will be 2^ 31 - 1 initially so I is equal to 0 we are at 1 we check if the current value nums of I is equal to 1 we check if nums of I is less than first is equal to integer max value 2^ 31 minus 1 this is integer max value 2^ 31 minus 1 this is integer max value 2^ 31 minus 1 this is a large value right so obviously one is less than that so this condition satisfies so you found the first minimum value so update that Value First with one so first will be updated with one and if any of these values get updated once in that iteration we go on to the next iteration so I will move forward as we updated this now I is at one we are at two so nums of I is two so if we check the first condition if nums of I is less than first 2 is less than 1 this condition fails so we go to the second condition we check if nums of I 2 is less than or equal to 2^ 31 - 1 second less than or equal to 2^ 31 - 1 second less than or equal to 2^ 31 - 1 second has the value this right this condition passes so we update second so second will have nums of I is equal to 2 so second is updated to two since we updated one value I will move forward now I is equal to 2 it is pointing at 3 so nums of I is 3 now we check if current element 3 is less than or equal to First 1 no now we check the second condition we check if 3 is less than or equal to 2 no now as I said three is nums of K so nums of I is first 1 nums of 2 is J so this is two and num of three is the current element as these two conditions failed it means we have found our third condition which is satisfying so we can directly return true as the output whenever these two conditions are not updated the third L statement will be returned true because this statement is passing so you can observe the three indexes i j and k here 1 2 and 3 so you can return true as the output so true is returned as the output now let's take a look at the code we'll apply the same steps in a Java program and then later debug using an ID so that you can get a full understanding coming to the function given to us this is the return type Boolean we have to return a true or false this is the function name and this is the input nums given to us like we discussed let us declare two variables first and second and assign both of them to the maximum possible value an integer can hold that is integer. Max value we are assigning integer max value to both these variables because the next time we find any integer inside this input array less than this we can update the first and second variables accordingly so for that we have to iterate through the input nums using a for Loop starting from the zero index until the end so I will start from zero until it reaches the end inside the for Lo first I have to update this first variable so I check using a if statement if the current number we are iterating at I so if nums of I is less than or equal to the first variable we have to update the first variable with this num ofi so first is equal to num ofi next we are using LF statement to update the second variable that is if the current variable at I is less than or equal to the second variable we have to update the second variable to this Numa fi and now in the else block it means that for the current iteration if the if statement failed and if the else if statement failed that means first and second were not updated they remain at its previous values it means the current variable is equal to K which means this condition has been satisfied so that is why these two first and second variables haven't been updated if it would have been updated in the if block or the else if block it wouldn't have reached here it would go back to the for Loop for the next iteration because these are conditional statements if these two conditions failed only this condition statement will be executed so it means this condition passed and here we can return true as the output and outside the for Loop if the true hasn't been returned it means we haven't found such indices inside this nums array so outside this we can return false now let's try to run the code and the test cases are passing let's submit the code and our solution has been accepted so the time complex of this approach is O of n because we're using a for Loop to iterate through the input array nums so n is the length of the nums array and the space complexity is O of one constant space because we not using any extra space to solve this question now let's debug the code with this example and see how we are getting false as output so I've taken the same function as lead Cod and this is the second example and I'm calling this function here this will return a Boolean value and the output of this function will be stored inside this Boolean variable result and I'm printing the result now let's try to debug the code and see how the working is happening I place two bake points now let's debug the code so here you can see nums is 54 321 first and second are initialized with the maximum possible value so the next time we access any value less than that those two variables will be updated so here I is equal to Z so nums of I is nums of 0 which is five we checking if five is less than or equal to first five is less than or equal to this that is why it entered the if statement and first which was initially this value will be updated with five now first is equal to five now as you can see the control from here went back to the next iteration now I is equal to 1 so nums of 1 is four we check if 4 is less than or equal to the updated value which was five 4 is less than or equal to 5 so again first variable will be updated now first will be equal to 4 as you can see now first is four the next iteration I is equal to 2 second is still the max value because control haven't readed here now I is equal to 2 nums of 2 is equal to 3 we check if 3 is less than or equal to 4 yes so now first variable will be updated again to three as you can see first is three now I is equal to 3 nums of three is equal to two so first will be updated to two again so as you can see first is 2 now I is equal to 4 nums of four is equal to 1 first is equal to 2 1 is less than or equal to 2 this condition passes again and first will be updated to one now first is one and second is still this so you can assume first is equal to I second is equal to this J since second value is not updated yet we haven't reached this statement yet so the answer will be false so you return false as the output so false is returned as the output that's it guys thank you for watching and I'll see you in the next video lady
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
17 |
That A Hello Hi Guys Posted In Funny People Come To The Video Tourist Question Is Letter To Minister Phone Number Pitch Set Given String Contents Images From Tonight Inclusive Return All Possible Letter Combinations Sweater Number To Deep Recent Updates To Letters Given Below Not Minutes So Acid And Nurses Parents Teachers From To 9 Subscribe To That Sufi Consider And Example Website Per Digit To Entry Dil Possible Combinations Pet Wicket Are Chief Beads Pe A Plus B Positive Seedhi Possible Latak Maine Is Amazing 210 338 Directly Into The Approach To Solve This Particular Problem That aap us arvind approach scripting are hostels for all names in story dumping us folder teachers from 029 * discovery folder teachers from 029 * discovery folder teachers from 029 * discovery singh10 10 min map with nothing ever wished to mt streams shab dehratu possible approach to solve this particular problem become this using back tracking approach and another one is Using Recursive Producers Considered a Legacy Approach Which Seem Example Given in the Question Sabse Zor Kal Su Visible Approach Recall Manner to the Function Refer Bittu Arguments Nimli Iay Bas Is Location of the Digit and Asked This Question On Main Teri Kasam Likho Call This Function with Zoom 5th to Chief C Recording to the Number of Units Flash Lights Do Some Time Food Wicket Possible Letter Combination Sas Chief Beads Paytm App 500 1000 Swear What Like This Which You Will Get To Know Entry for Example So Initially E Which The Record Function From Amin function measurements per service to three that result under witch safety born andheri ho paya 20 of this entry was yesterday morning enter function first features brother is equal to after when digits are made to citizens not meant for the story the thing of meetings of To a pc in to variable callgirl sintu match to abcd looter bc in to variable value in the travels character per character duvel and healthy life g points 202 shan recorder function with life is one and belief SSC similarly em for BSC is so aju calls smart Looks Like This Way Call F1 Through F12 Ma B.Ed F1 Ko Machine So Let's Call F1 Through F12 Ma B.Ed F1 Ko Machine So Let's Call F1 Through F12 Ma B.Ed F1 Ko Machine So Let's President Of One Earning That Not Give Equal F1 Ko My If Mental Recursive Function And Weather Divine Five Physical To The Lamp Shade Its Citizens Not To Give The Story The Return of Jewelthief Mapping Test Series in Two Variable Costs in the Next Chief of Strings Page Subscribe if you 20 Points 202 Locations and Difficulty the Function with Now Turn Off - 2 End Benefits Function with Now Turn Off - 2 End Benefits Function with Now Turn Off - 2 End Benefits 3D Similarly for School to a Brick Wall with Life IS to End Definition of AP Similar if the point where a loot election scenario calls looked more like this yet again call method is just function from F1 earning is a slave near a condition verify is equal to the land of the digits latest to solve is to the streets end Eggs in result revolution pure cotton journey it twitter chief let's look at certain to call from the main function a mere billu vs beer that election store walls election to the volume of the digit pre-emi it's volume of the digit pre-emi it's volume of the digit pre-emi it's difficult put me tomorrow on doctor dusting dam character Character Doctor Kar Function With Raw Taste To Andheri Alias Spd Similarly When 0.2 To Andheri Alias Spd Similarly When 0.2 To Andheri Alias Spd Similarly When 0.2 Se Z Call With Person Sebi Chief Advisor Point To Family Function With Life Is Ki Saugandh Aa Recessive Calls Absolutely Smooth Like This India Service To The Volume Bbnda Pintu Result And They Should Investors Updated to the following lines Again a bear pintu a third option call from the main function value of its history itself visto the making of the digit free pintu distic in the travels system character of character 1.20 profession absolutely another character of character 1.20 profession absolutely another character of character 1.20 profession absolutely another effective to-do list of ssc Similar effective to-do list of ssc Similar effective to-do list of ssc Similar CD Sold DCF 1.0 It Computer CD Sold DCF 1.0 It Computer CD Sold DCF 1.0 It Computer Developed Finally Updated Content And Chief Beads Pe That Spinally But Slap Initially Creator Vector And Typesetting That A New Delhi British Result Tractor And Weather At A Distance It Or Not My Latest Updates Life Is Equal To 0 4 1 Liter Harijan Factors Which Amity Institute For The Great A Sanam Re Namak Typing And Store Them Of Things Of Digits 029 Pass Loot Siron 100 Test Wicket Police Toe And Distance 98100 In Updated List On The Best Picks From Its To 9 Hua Hai Ajay Ko Hua Hai Ajay ko MP3 hua hai loot kar do main tujh ko ki in the introduction of setting up the dishes call recording function with this new updates reminder combination hai kar do ki MB pa payment is the function of government s its strength in superintendent dr phone Number body and most important documents which side visit english playlist 202 and distic gas switch smt loot hai yar bay upon him officer twitter bypass on difference difficult directly return twitter t that boat this to create a that their this combination will arguments dipping now actor austin Gift pack which scared alarms were Indian soil testing labs and artificial insemination part interactive function first check weather is equal to balance were BJP was one for special updates that Narendra Modi details are equal to that digit in Scotland I am Narendra Visto Justin gas distribution SIM * result And twitter res * result And twitter res * result And twitter res hua hai loot in the written from the function of this is not equal to visit scotland yard continue for their loot volume of mines of 9th character present location aaye digit aaye pintu available call girl kar do aur sunao MP3 and sunao hai Yes digit testing digit late for me toxic diwali now zero profit only but in teacher bollywood hua hai me stress disorder travels directives of distic hair notice here thing share on his land water length and g plus jas ko invite traversing again call in tested function Is my little consternation ki bill smoke romance update s five plus one should be instituted after owning v5s contaminated with change om ji ki ko sunavai karna food vo sisk flying point witch can submit dakuru ki a ko text successfully soft is video help phone do hit the like Button and subscribe To My YouTube Channel for More Upcoming Videos Thank You
|
Letter Combinations of a Phone Number
|
letter-combinations-of-a-phone-number
|
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`.
| null |
Hash Table,String,Backtracking
|
Medium
|
22,39,401
|
309 |
Hello friends today I'm going to solve with code problem number 309 best time to buy and sell stock with cooldown in this problem we are given an array prices where each element represents the price of stock on that day and we need to find the maximum profit that we can achieve and the restrictions given to us is that after we sell our stock we cannot buy on the next day that is we need a cooldown of one day and we cannot engage in multiple transactions simultaneously which means that once we bought our stock we cannot buy another stock until and unless we sell our stock so we need to buy and then sell before buying another stock now let's see how we could solve this problem so um just by intuition what would you do on the first day well basically you'd buy this stock right because you do not have any stock so far so uh what our first step is that at index 0 we try to buy our stock right but we also have another choice that is which we could choose to do nothing as well so um at index 0 our profit is zero and we can either choose to buy or we can choose to do nothing if we choose to buy then our profit will be -1 because we are buying at the price be -1 because we are buying at the price be -1 because we are buying at the price of one and if we choose to do nothing then a profit will remain the same right and on the next day what we could do like we can perform a transaction that is a sale transaction because once we buy we need to sell it before we can buy again right so we can either choose to sell or we can choose to do nothing again so if we choose to sell it then we sell it at the price of two on that day the price is equals to two right so our profit now becomes equals to one and if you choose to do nothing then it becomes minus one that is it Remains the Same Again if we sell it then we need to cool down period of one day so on the third day we just do nothing so on a price three we just do nothing and then uh the profit Remains the Same Again we can now choose to buy on the fourth day and the value is equals to zero so if we bought on that tape then our profit will remain equals to minus equals to one and we could choose to do nothing as well so if we do nothing then the price will remain the same and again we bought on that day now we can choose to sell on the next day and we could choose to do nothing so if we sell the price is equals to two so we choose we sell at Price three so now our profit becomes equals two um 2 plus 1 which is equals to 3 and if you choose to do nothing then the profit will remain the same so what are we doing here if we look at the cases here if we choose to sell then our profit is increasing right that is we are performing an additional operation on our previous profit we are adding the value price of that Index right price and if we are buying that we are reducing the price on our profit we are subtracting the price the buying price so this is what we do so these two uh formula is what we'll use and if we are doing nothing then our profit Remains the Same so profit Remains the Same now another thing to keep in mind is that on every index we have two choices to make right either to sell either to perform a transaction or to do nothing and the transaction is either selling or buying right and only on some special cases we choose to do not think that is when we are selling it so basically we can take this whole thing as one branch rather than one and two different branches we could check take these as one branch so after each cell we just uh jump over two indices so that we have the uh we have the choice to either buy or to do nothing now um this whole approach is that we are moving from top to bottom right we are finding the profit at each index starting from zeroth index 0 1 2 3 4 so on right so this is top to bottom approach but what I'm gonna do is I'm gonna solve this problem in bottom up approach and it's very simple and that can uh lead us to off and time complexity so what we are going to do is we are actually going to use a dynamic programming that is we are going to use memory Json cache that is save our values now let's first begin how am I going to solve it from the bottom up approach so what we do is we start from the end and the very end um my profit here is three right and my profit here is equals to one so what I do I take the okay let me just explain it with the new diagram uh this is a little confusing as well foreign so what we do is we start from the bottom that is index to um let me just tell you the concept the idea behind that part so I need to find the profit right maximum profit at this point and I have two different branches from here I have profit P1 and I have profit P2 right and I want a maximum profit so what will be the maximum profit maximum will be um the maximum value between any of these two right which of these two have the maximum value will be the profit uh at the top so this will be the maximum between P1 and P2 right so this is the idea that we'll be using in our bottom-up approach so what I do is I find the profit at this index and anything beyond that since this is my last index so I start from the last index and my profit so far is zero right and now at this index I could either choose to buy or sell right if I chose to buy at that index then what would my profit be at I am at index 0 uh basically my profit is zero so far and um if I choose 2 pie then my profit will be equals to minus 2 if I chose to sell then my profit will be close to 2 if I chose to do nothing then my profit will be equals to zero right but buying and selling that will depend on the transaction that we perform at this point these two point if I sell at this index that I am I need to buy at this index or just do nothing if I buy at any of these two in this case then I must sell or just do nothing right so basically I have two choices to do nothing or to buy so if uh to buy or sell or do nothing right do not think so um so now what I need is I also need um what should I do should I buy or should I sell well I do not know right because I'm at Index this last point but I can know it if I know what I did previously so what we need to do is we need a Boolean value by we will use a parameter Boolean value to identify what we are going to do here at this Index right so if you are buying at this index then our price will be equal reduced to minus two so that would be -2 and we take the so that would be -2 and we take the so that would be -2 and we take the maximum of these two so it would be zero right so we take this maximum value and then we perform our next previous transaction that is if this transaction was a buy then previous transaction would either be a sale or nothing right because if we sell previous transaction would be just nothing because if we are buying at this point that is we cannot buy at this point because we must might have sold at this point right so yeah so basically that's the idea behind that so now we found the maximum at this index we found the maximum profit at this index which is zero if it if we were to buy right so which is zero um and then we do nothing here so the profit Remains the Same and then again we move on to this index and we could either choose to buy uh choose to sell or do nothing right so if we choose to sell it then what would the price be if we sell at this point then basically our profit is increasing right so plus three it would be plus three right if you choose to do nothing and what should the price be the price would still be the same the profit would still be the same so what's the max 3 is the maximum right so we take the value three this becomes our new profit and now we move to the previous one uh since we sold at the previous so this will be our buy condition or do nothing if we buy then the profit would be equals to 3 minus 2 which is equals to one and if it's do not think then a profit would still be equals to three so doing nothing gives us the max profit right so we do nothing and then we move on to the previous one and then uh can we buy or sell well again buying means minus one and doing nothing means um three so what do we do not think so basically this is the idea um since I started from with an assumption that I am buying at this point but actually we need to sell at this point because looking at the fact looking at this example as well we need to sell at the end right but it was just an assumption because now let's dive into coding so let I'm gonna use dynamic programming n equals to this will be our cache where we will store our values we need the index and we need the pulling value to know if we need to buy or sell at that point of time and if we need we always have to check the base case before we always uh it's always good to check for the base cases if it is the end we return zero if not we have the choices to buy or sell right so we could either choice to buy if else we sell right and we also have the choice to do nothing so we either perform a transaction or we perform no time transaction so no transaction means the profit Remains the Same so I plus 1 and um if you did no transaction which means that we still need to perform this transaction so we'll pass the same value here now what do we need is since we are using DP we also need to check uh if we have found the value at index I for the given transaction if we have already calculated that value then we just don't need to do it again and again so I'm just gonna use DP to check if I have already computed that value if yes then I'm just gonna return it return the value if not then what I'm going to do is I'm going to calculate the value of that DP and the value would be equals to um since it is a buy so the price will reduce right a profit will reduce basically so Price Plus and the DFS function else if it is not apply if it is false this value is false then we are actually selling it and if we sell we need a cool down period right that is after that day we escape one day so that is what we are doing here and um when we are selling our profit increases so we add the selling price to our resulting profit and then what do we do is um so we take now this could also doing nothing could also result in a value maximum value for that Index right so when we need to update our DP so let DP equals to math.max so let DP equals to math.max so let DP equals to math.max imum value of these or the value of DP itself which of them is maximum and then we finally return the value of our TP and then we call our DFS function True Value because we need to buy before we make a cell okay um so I'll just what I'll just do here is minus one times we need the prices not price it's prices yeah and yeah we could instead of doing this whole multiplication thing and then the addition thing what we could do is we could just subtract the prices cool let's submit it great so the time complexity would be off and because for each index uh we are only performing one and the transaction once and if we can counter the index next time we just return the value from our uh cash right um and the space complexities of n as well so yeah
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
1,583 |
hey everybody this is larry this is me going over q2 of the lead code daily con uh sorry delete code contest uh count unhappy friends so this ends up being a data structure lookup problem um but the idea is that and there's a lot of things to read about this problem uh but yeah but while you do that hit the like button hit the subscribe button and join me on discord and also you can watch me solve the third contest afterwards but basically you have all these instructions on what um what you can do and what you can't do um which is that and there's a lot of reading right so if you haven't read this problem fully um or if you have questions about the prom prescription like let me know or description uh leave a comment below but the idea is just storing things in a way that you can do lookups in a very quick time uh given that n is 500 you could actually be a little bit slow-ish actually be a little bit slow-ish actually be a little bit slow-ish but what i end up doing is that i just have reverse lookup tables where um okay so first i put you know put the pairs and uh and i'm gonna go over the code more than i the algorithm because i think the algorithm is pretty data structurally versus like you know because it's all about lookups right um and then i have this preference table uh which is maybe terrible name but it basically maps okay the preference of uh you know this basically allows me to because you're given the way of like in assorted order of like order preference right so instead now i'm going to map these order preference from uh to the index itself so that like okay so it person index likes person a in the index 2 position the variable names are terrible but basically this is a reverse lookup table so that i can look up um so basically let me write a comment uh person index uh likes person a the index two most right so like that's how like the earlier the better so index two is how where it is so i had to debug it because i just had some typos and mistakes but now after you uh construct a reverse lookup table you just do a count of okay for each x and its pointer in pair which we you know we construct here for each x that we look at we go okay uh we look at the entire preference list or for that um for that person and that's the input right so for that and that's the alternate pointer if the pointer is alternate then we break because that means that you know the other invariant has not been true so um or the other way you know the other thing didn't break so that means that we've everyone that we so we're optimally happy with our current partner otherwise we look at this which is that okay if so now alt if this is not true and it hasn't been true yet then the alternate partner is you know you would like to prefer the alternate partner and then the question is does the alternate partner prefer you right and the way you could check that i prefer over their own partner and the way that i have is this preference table where okay uh this one will give you the rank of the alternate uh you know your rank of you and then this will give you uh of the current partner and if the current partner is has a higher rank meaning if they're later in the positioning then that means that you know you're you should be unhappy and that's why there's a campus one um so that's you know like i said it's all data structure and if you have to write lookup tables this should be done in very quickly uh i actually took a lot of time on this contest and you'll see it later because i ran in some issues with internet and also um uh and also i just had a few typos because i was being silly uh and that's where you know you have to name your things a little bit better and to be honest looking at this uh the structure of the code is clean but the wearable names are terrible to be honest uh so i should do a little bit better uh and that will help me down the line um and the complexity is just n squared because this is n squared uh and this lookup is all one um yeah and the space is all of n in case you're curious uh well i guess technically n squared because of this thing but it's linear in the size of the input because the linear is uh the in the size of the input is n squared right for the number of preferences uh cool uh that's all i have for this problem uh watch me solve it live next thank you uh so hmm so this come on i'm going nope two x so oh you oh my god oh my oh that's not great well it looks like this may be unliked i don't know oh let's just do this one anyway points uh okay that's two how many points are there a thousand that whoops um hmm that's not good one is happy that's not two stupid mistake hey everybody uh yeah thanks for watching thanks for you know supporting uh hit the like button hit the subscribe button join me on discord and yeah and check out me solving the rest of the contest somewhere in the link below bye
|
Count Unhappy Friends
|
paint-house-iii
|
You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`.
All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`.
However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but:
* `x` prefers `u` over `y`, and
* `u` prefers `x` over `v`.
Return _the number of unhappy friends_.
**Example 1:**
**Input:** n = 4, preferences = \[\[1, 2, 3\], \[3, 2, 0\], \[3, 1, 0\], \[1, 2, 0\]\], pairs = \[\[0, 1\], \[2, 3\]\]
**Output:** 2
**Explanation:**
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
**Example 2:**
**Input:** n = 2, preferences = \[\[1\], \[0\]\], pairs = \[\[1, 0\]\]
**Output:** 0
**Explanation:** Both friends 0 and 1 are happy.
**Example 3:**
**Input:** n = 4, preferences = \[\[1, 3, 2\], \[2, 3, 0\], \[1, 3, 0\], \[0, 2, 1\]\], pairs = \[\[1, 3\], \[0, 2\]\]
**Output:** 4
**Constraints:**
* `2 <= n <= 500`
* `n` is even.
* `preferences.length == n`
* `preferences[i].length == n - 1`
* `0 <= preferences[i][j] <= n - 1`
* `preferences[i]` does not contain `i`.
* All values in `preferences[i]` are unique.
* `pairs.length == n/2`
* `pairs[i].length == 2`
* `xi != yi`
* `0 <= xi, yi <= n - 1`
* Each person is contained in **exactly one** pair.
|
Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j.
|
Array,Dynamic Programming
|
Hard
| null |
427 |
Peace be upon you, my dear friend. How are you doing? Oh God, you will be fine and in the best condition. God willing, today we will solve it together. If you don’t try the issue, go to the first one before you watch the video. And if you try, let’s be together, in the name of God. He is if you try, let’s be together, in the name of God. He is if you try, let’s be together, in the name of God. He is telling you an issue that has a lot of hope in it. I am... I will try to simplify it issue that has a lot of hope in it. I am... I will try to simplify it issue that has a lot of hope in it. I am... I will try to simplify it as much as I can. It means big and strong, so let us say that he gives us that in and its name, but all the sills that have zeros are one. Okay, so what does this mean? You are supposed to take it to convert it to the Trida. How can he tell you what the issue is? He tells you that yours has everything. Our Nodes look like this. There is something called Pointers, and the rest are all pointers. Or, I mean, okay. Then I have it now. I want to convert it. How do I convert it? I don’t read the Tex, of course, convert it. How do I convert it? I don’t read the Tex, of course, convert it. How do I convert it? I don’t read the Tex, of course, because it is long and bulky. So let’s see how long the first because it is long and bulky. So let’s see how long the first because it is long and bulky. So let’s see how long the first example is. is. is. Or let’s go along to the last example, which is better. Okay, now we know that he is guiding us and the newspaper will remain in the view that he is holding out to me. This is fine. We are all zeros and one, and that whoever wants to turn it so that she can see her note in the form that he had shown it to us above the one that is the figure in front of you, that is the one that is in this form. Okay. Come on. While we will see how we will convert it, the first thing he told you is that you are going to take what is a gift to you and divide it by four. Okay. I mean, you will take this and divide it like this by four. Okay. Then the first thing or your note that is called Okay. What is its name? Because all the cells in it are one thing. It is the first thing. Something like this will still be to your liking. Okay, okay. For example, the rest of the value. My value will still be worth what. It's equal to the existing value. I mean, it's not all neutral. Oh, and we knew that hers was like that. We said it's all neutral. Your value will still be one sweet. Okay. As for the top, it's not available. It's not available. Why aren't they available? Because When you did it, you found that it was all equal, right. Not everyone is alone. It still has a meaning. What arts you do n’t have or a top? You don’t have any of the other ones. I mean, it’s n’t have or a top? You don’t have any of the other ones. I mean, it’s n’t have or a top? You don’t have any of the other ones. I mean, it’s fine. After that, you will go to the top. You will see what this is, the tobright. You will find it in some pictures, and some of what will happen next will be fine. Well, the value does not make any difference to us. It will go to one or anything. It will not make any difference. Okay. I mean, when we find that the value in the case is different, then the value itself will not make any difference to me. Zero or one. Put it as you put it. Okay, okay, nice. What do we have left? We didn’t say that’s it. What does it We didn’t say that’s it. What does it We didn’t say that’s it. What does it mean? It's not there. Or, well, we said, it won't make any difference. It's one or zero. Put it as you put it. Ok, so we have four things. The top-lift saw, so we're going to four things. The top-lift saw, so we're going to say, what's the name of your four? It's nice. Give your top-lift zeros. You're a new note. It means this is the top-lift from the new note. It means this is the top-lift from the new note. It means this is the top-lift from the first one. This is the top-lift from the first one. We put the first one. This is the top-lift from the first one. We put the first one. This is the top-lift from the first one. We put the fiber with a zero. We put them with anything and put them with one connected to it. The first four nodes are sweet, good, sweet, all of them equal, or all of them with a zero. Then put them with one, and the video put them with a zero. Here, it is mandatory to leave, okay, I saw the top, I saw what you have, all of them with zero, so her fiber will remain one of her value. Zero, okay, after that, the one who is all this is a lake, if he has money, the one who is all of this is free of food petro, and the video will remain one. Okay, okay, I finished, oh, I finished, we go back to the top. This is our tube, we finished it all, we did it, and the value and the four are connected to it. So, I finished this, and I finished this. Let's go back to the bottom. Bottom turnip, where is this leftover? Where is she all alone? Oh, then hers is finished. Oh, she's done. Let 's go to the one that is yours. How much is all of it with zeros? Then it's all finished. All mine is fine. So let's say this quickly. It's the same again. Quickly. How do we do it? Okay. You have locusts. You started a 's go to the one that is yours. How much is all of it with zeros? Then it's all finished. All mine is fine. So let's say this quickly. It's the same again. Quickly. How do we do it? Okay. You have locusts. You started a 's go to the one that is yours. How much is all of it with zeros? Then it's all finished. All mine is fine. So let's say this quickly. It's the same again. Quickly. How do we do it? Okay. You have locusts. You started a check. It will be first. Your first step is that you are suspicious. This is your first step. You found it all different because in my life there is a zero and a neutral and then two zeros and then a neutral and two zeros and then two zeros. Okay. So, the first step you found is different. As soon as you find them different, you know your nose is zero and the value puts it in anything. Okay. Then you are like this. This is your beginning. Okay, now you want to get the four if you are unwell, so you divide it by four. Then it is your top-lift. so you divide it by four. Then it is your top-lift. You will see whether it is equal or not. Okay. I found the type to be equal, so what do you do? It is equal to it. Okay. So we finished this part. It is nice to go to the tobright. I found the tobrite to be completely different. After I found it different, I said, “No, wait.” When I find completely different. After I found it different, I said, “No, wait.” When I find completely different. After I found it different, I said, “No, wait.” When I find it different, I put it with a zero, and the value puts it with anything, then I divide it into four, so I divide it into four. I took the noodles that were left for her. I found them all with a zero. I made one, and her value must be equal to the value, so it will remain at zero. So, I finished with me, and I was completely finished with this. What is this, I found all the cells in it will remain at one, and the valley will remain at zero. I found it in a lake, so I will put the one that is petro. It means the same thing. Okay, so I finished all of them. So I will go to the bottom file of this one, so I will make a big check on all of these notes, just as I made a big check on this one. I will go to the next one and find that they are all equal, so the humiliation will remain at one, and her video will remain the same as the verse that was in the song. It will remain a sweet one, my love, I am finished like this. After that, what I found all of them at zero remains one, and the value is zero, and I finished it. Okay, so I finished like this. Okay, so I finished all four, so all my newspapers are finished. Wadi Alama is correct. The whole case is nice. After that, I can do it. If I didn’t understand the issue, I understand. Okay. You can go and convert it alone like this and answer me on this and write a code. If I don’t know what, I will come back. Continue the a code. If I don’t know what, I will come back. Continue the a code. If I don’t know what, I will come back. Continue the video. Pause the video. Come on, okay. We will solve this issue through Tamam. If you don't know, you should be suspicious. It means that you don't know, but if it happens, it means that you don't know how to go. Study the first one and come back. If you noticed while we were doing it, we were repeating the same operations on what we were doing. We were going to see if we should go to the locust that was not on this line. For example, we were going to see if our locusts were equal or not. When they were not equal, we would divide them into four, exactly, and after dividing them into four, we would repeat the same operations on this half, or this quarter, and this quarter. What is the process? What I repeat is to see if it is equal or not. If I find it equal, then this is mine. If it is not equal, I repeat the same process that is dividing it by four. I go and do the same process on this part and I find it equal. This is mine. I arrived. Mine is equal. I reached my equal. I arrived at my bass. I will return. So, I did this part for this quarter, and for this quarter, I will go, and I found it equal, so I arrived and we finished. I will go, and I found it equal, and I arrived and we finished. So, I finished the four quarters. So, I finished every major Fahretran verse for your root. This is a simple issue, it doesn't need anything else. It's very simple. Come on. Let us see her code written. How is this code? The first thing is that he will give you the case itself. It will not give you anything else. So I told him, “We will tell you now.” I will tell you now, what does she do? The first thing I you anything else. So I told him, “We will tell you now.” I will tell you now, what does she do? The first thing I you anything else. So I told him, “We will tell you now.” I will tell you now, what does she do? The first thing I send to her is zero and zero, and the newspaper size and the same newspaper do what she does. I have XY. I have it now. This device is my case for the I will start from the I take the cell that is the The sills that I passed on the same time are all zeros, or the seldies are one and I passed on all of them that are all singles. So, ok, if you find that you encounter any slugs, then ok, if you meet them, then we know that this function is called what it does. You will see that the case I am holding out is equal. No, no, okay. Okay, if you find that the length of the note is equal, then the heteronode of this note will express what. We said that it expresses two things: the value and the value. Well, what is your value? said that it expresses two things: the value and the value. Well, what is your value? This is exactly what he said to you. If you have nodes and you look at her with a node on her tubes, this will express the note. The value is first, and then we agreed that if we find them equal, we will put my value as the one in the equal pod, and we will leave it Okay, ok, that's it, we're done, and the four nodes will no longer be there, so they will be put. Okay, okay, I do n't have any problem so far. Ok, I discovered that there are different things in it. So by dividing it into four here, I want you to focus on me. I divide it into four. Correct. We said that the So, both the One time, I was supposed to divide it by four, so I came here and told him that when you come, you will divide it by four, meaning I will divide it by four, so when I divide it by four, it is supposed to be here, this is a zero and a zero, okay, this is two and zero, and this is four and zero, sweet, four and four, these are my sides, sweet, now. I agreed that we would represent using two or three things: X, or three things: X, Y, and Lens. When my I am looking at his curtain, the first one, which is this, and his lens, which is this one. Okay, okay. As for the top, I thought it would work. How is his curtain, this one, and his lense, is it ok? I gave him the same I finished, I will go to the top. I saw what this is. I gave him what I gave him. The Okay, okay, there's no problem. I gave him his curtain for the verse. Okay. What this is supposed to be the curtain for the old X plus Lens on both, FedEx and Wi-Fi as it is and Wi-Fi as it is. Okay. There's on both, FedEx and Wi-Fi as it is and Wi-Fi as it is. Okay. There's no problem. Okay. We'll go to the last one. This is his curtain. What is the line on both and the lens on both? It is the It's fine. I'll go and repeat the same process. I mean, I'm repeating the same process. So, what did I do first? Let's wipe. The first thing is that I have my own money. It's nice to see if it's the same value or not. If it's the same value all the time, I'll go back and continue until I get my own. It may be like this. I have finished the issue and there is no problem. It is an easy issue, and if you know the issue for you, it will be easy. It is possible, but her text is a bit bulky, but the issue itself is solved. There is nothing easier than it. But if you do not understand, you can repeat the video more than once, even if Anything you can write to me in the comments, I will see you, God willing. I will see you next time, God willing, well. Peace be upon you.
|
Construct Quad Tree
|
construct-quad-tree
|
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree.
Return _the root of the Quad-Tree representing_ `grid`.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
* `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer.
* `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop.
2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo.
3. Recurse for each of the children with the proper sub-grid.
If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree).
**Quad-Tree format:**
You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`.
If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\]
**Explanation:** The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
**Example 2:**
**Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\]
**Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\]
**Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:
**Constraints:**
* `n == grid.length == grid[i].length`
* `n == 2x` where `0 <= x <= 6`
| null | null |
Medium
| null |
392 |
hey there fellow colors welcome back to another engaging episode called Master Quest today we are going to solve this subsequence problem but this time in Python so if you are interested in the solution for this question please check out the link in the description below otherwise let's try to implement this question in Python now let's figure out the problem statement analytical control if s is a subsequence of t or false albums and by definition a subsequence of a string is a new string that is formed from the original string by the linking sum can be none of the characters without receiving the relative position of the remaining characters right so if we got an input like this one s equal to ABC and t equal to this string we should return true because we can remove let's say h g and d and generate an ABC from T right so let's come back to the visual studio code and try to implement this question now let's define the solution class and function signature and then Implement our solution for this problem so let's say class shine definition is self to string parameter here s and t and the return type for this function which is going to be a Boolean right so let's say now I want to check whether s is empty if s is empty then you can remove all the characters from T and make the S and then you can return true right so let's say if not s then return true and if this is not the case then I want to make an iterator from the characters in s so let's say it equal to iterator from s and then Define another you know variable to point to the first character of the um this iterator so let's say current equal to next from iterator and if there is nothing inside this iterator let's return now as the next job I want to Define uh for Loop over the characters in t so let's say for Char in t if the character is equal to current I missed if statement here so let's say if charm is equal to current then let's move the current to the next characters of the iterator so let's say current equal to next it and not and at the end it's good enough to check whether Uh current is none if current is none this means that we could find all the characters of s inside the T right so this should be the solution for our problem but to make sure everything is working correctly let me switch to the browser find the example here and come back to the visual studio code and test it with this example and this is a two-line comment like a and this is a two-line comment like a and this is a two-line comment like a instance of the solution class it's all solution and then let's say print so is subsequence uh for ABC and this one open our terminal and let's say so actually python tree problem it's true why so this should be the card solution to our problem but that's the last job let's submit this solution to the lead code and make sure about our solution so there we go let's hit the submit button and perfect here's the solution for this question thank you everyone foreign
|
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
|
718 |
hello everyone today i will solve the question maximum length of repeated sub array the question type is medium one and the question statement is given two integers array numbers one and nums two return the maximum length of sub array that appears in both arrows this question is like the maximum length subsequence question type and here we need to return the maximum length of the repeated sub array like here three two one and three two one it is the maximum length which is repeated in both the areas right we have also one but it is the length of one is only one and three to one is three so we need to return the three maximum length of the repeated sub-array repeated sub-array repeated sub-array here five because zero 0 5 times is repeated in both the integer array right so how we can solve this question by using dp so first i will explain you the solution in which the time complexity will be n cross m and the space complexity will be n cross m but we will optimize the solution the space complexity will be and you can see n or m which is whichever is lower in size here like in this example three two one four two three one four two here maximum length is one four right one four the maximum length is one four how we can solve this question using dp so we will make up if size is n and its size is m n plus 1 m plus 1 dp array you can say 2d array we will initialize the first i equal to 0 and j equal to 0 with 0 because when there is a node digit no integer the longest sub array will be zero now we will check with this three to these three this three is same right it is equal so we will make it 1 not 3 2 it is not equal so 0 not equal now 1 3 is not equal to 0 1 2 is not equal to 0 1 is equal now we will check for the previous digit is it equals three or two this digits it will decide whether it is equal or not it is zero so it is not equal we will put one you can do one thing you can add in this diagonal value for this whenever it will be equal like here 1 3 is not equal 1 2 is not equal 1 is equal now we will check whether 1 2 is equal or not this is not equal so we will put now 0 now 4 0 this was equal so it will be 1 sorry 1 now 4 is equal now we'll check for the previous one was equal and it was the one so we will add one and it will be one and zero here it will be zero it will be one because one plus one is two now two is equal so we will add this and this will be 3 so we will return 3 but we can optimize it by using 1d array here in 1d array we can do one thing it is three our question is three two one four to right and it is three one four answer should be one now how we can solve this question we will take a for loop it will start from here and the second for loop we start from here let's say i and let's say for this for all this value for all these value it will check from the back of this error now we will have the area of dp you can say 1db one two four five one two three four five now we will check 3 to the integers of this array but we will start from the back 3 2 is not equal right so we will put zero three four not equal we will write zero p one not equal right zero three one not equal right zero and three is equal so we'll put one now what we will do now we will check this two with the with these digits of this sub array but from the back side now 2 is equal now we will what we will do we will check whether the previous digit was equal or not 3 was equal or not was it equal no with these digits was it equal in the previous case no it was 0 so it was not equal right because we compared these two values previous time it was not equal so we will add 1 in this value 0 plus 1 will be 1 right so we'll put 1 here and 2 4 is not equal to 0 2 1 is not equal to 0 not 2 3 is not equal to 0 so it will be 0 again i will check for 1 whether 1 2 is equal no now we will put 0 here 1 4 equal not it will not equal it is not equal so 0 1 so we will check for the previous digit yes it is zero so zero plus one now one equal we will check for the previous so it is zero so one now one three naught equals zero now we will go check for four two equal not so zero four equals we will check for the previous yes previous digit was equal one was equal so we will increase this to two now four one equal not equal so we will make it zero four one is not equal we will make it zero and four three is not equal so we will make it zero now we will check for two is equal so we will check for the previous yes previous digit was equal and it was previous two digits were equal because it was it is two so we will add one more because 2 is equal now 2 will be 3 2 4 is not equal to 0 2 1 is not equal 0 to 3 is not equal to 0 so in the last we will get one value everything will be 0 only one digit will be earned here an integer and that will be the answer and we will also check every time what is the maximum digit we are getting so we will return the maximum now i am explaining this solution so first and one is si and two is si here you can optimize it by using you can make n2 is the smallest number whichever is low you can make it i didn't do it here but you can do dot for optimizing more or you can make any sub array and one plus one or n2 plus one because we need the lower in size if it will be greater there's no problem but for optimization you can take it the lower in size and we will for loop from the start and the second for loop from the end and we will check if it is equal we will check for the previous if we like here it was checking for the previous and else we will make it 0 and we will return the maximum of answer previously answer or this dpj plus one we would return that answer now i will learn the code it is exactly the same code which i saw thank you
|
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
|
62 |
Hello Guys Welcome Back To Decades And This Video Will See The Unique Pass Problem Wishes From List To Day 29th June Challenge So Let's Know Problem Statement In This Problem Organized At Gang Problem Organized At Gang Problem Organized At Gang Raped And Where To Find All Possible 500 Minus One Will Start from the first and will end subscribe and subscribe the Channel must subscribe 9049 subscribe comment only to the handed over to the understand this problem statement this is very simple problem no latest simple ideas for solving this problem well in this latest Given to back to grade novartis presented no money investment 1000 2000 basically possible for tourists from 10 possible number of tourists from this but you can restore star plus and subscribe my channel subscribe must subscribe this open text based 9 meter wrapped khatri best grade- 03 This How We Want To Reach best grade- 03 This How We Want To Reach best grade- 03 This How We Want To Reach From 0 To Come To Know When We Can Which Will Be Nothing But The Edition Of Values From The 2010 Subscribe Total Number Of Units Sold For Next To Nothing But Subscribe 100 Total Number Of Units Subscribe Your Thing But Three Plus 3 Which Will Be Equal To 6 You Can Easily Solve This Problem By Using Requirement So Let's You Are You To Give Cell I Come Okay So What Do You Will Calculate The Number Of Way Tours From The Right From hand side plus number of tourists from the question is nothing but the system from subscribe now to 1200 plus 1020 plus one adhikar samiti very simple equation and implemented by subscribe like and subscribe that gym that minister of bihar talk regret and want to restore the star From This Robot Senth Ek Person Starting From 0868 It Moving Only To Write In The Number Of Cases Latest 2010 Don't Forget To Subscribe 2010 2011 2012 Viewers Welcome To You Will Return From How To Come To The Richest Single Pat 900 * Single Pat 900 * Single Pat 900 * Sir This is the Largest Sale You Will Return 102 You Will Return From Nothing But the You Have Already Calculated To Here But You Will Be Reduced to 100 Years Away From You Will Be Doing So Will Return Value Love You All The Best Previous Bal So What Ever Written From This Write Call It's Wide And Total Time Will Be Replaced With Total Number Of Units In Order To Reduce Raw To Star Soenge In Straight Problem Solve 1212 Beneficial To Insert Additional Visible Space In The Eyes Is A Technique Subscribe Replaced With An Example For The Solution Want To Tell You Want To Travel From This Is Nothing That Traveling From Vistaar To Robot Sufi Want To Travel From Raw To Star The Movements Were Right Hand Side And Do n't Know You Want Toe travel from top toe bottom movements on top of this trap and you will be able to subscribe to the Page if you liked The Video then subscribe to the Page Question OK Now Latest and Different Here Position Not Seen Tourists Robot 2.2 The Number of Units Requested 2051 Robot 2.2 The Number of Units Requested 2051 Robot 2.2 The Number of Units Requested 2051 Number of Units Tourists From Plus The Number of Units Tourists From One Can See From The Researchers What the Researchers Believe From This Position We * No Position We * No Position We * No Problem Know the Tourists But Nothing But The Soul From Doing Man Question Which To The Robot Will Be Nothing But Impossible This And S 150 Grams To In Home In Which Country Is The Robot Boy Richest Single In The Cost Of Movement Will Not Be Allowed To Know From This Thank You Will Have To Know From this point will be top three for this channel subscribe my channel will only be the first to leave one how to validate post column will give answers were only single unique path leading to this report will be feeling the table from this sale will have Two possible choice is show the number of units for oneplus one to three for this will be possible for this channel don't forget to subscribe 9009 avoid your values have don't forget to subscribe 9009 avoid your values have don't forget to subscribe 9009 avoid your values have just 120 days after 10th is going to move to the robot you can also with the rate They But You Should Know You Have Made The Top Left Subscribe Lift Only Top Entry Will Be Recited For Possible Top 100 Number of Units From This Is The Number Of Units From This 108 To The Number Of Units From Top Similarly In Order To Get The Number Of units from to the number of units in impatient one subscribe angry plus 12414 state will be plus one which you will harmoniously similarly for this a little bit reply 6 and the last salute subscribe button ok so the number of units pass from this sexual tourist Rottweiler Sudhir and Time Complexity of Nothing But a Simple Way Give This Channel Subscribe Thursday Must Subscribe Internals Change Will Just Protect The Sum of and Left Forces Have Display Debit The Number of Units Passed From This Avi Nothing But You Can Restore Robbed From Top Toe Bottom Left Movement Only and Only Possible To Avoid You Will Have To All Possible subscribe The Channel and subscribe the Channel - - Channel and subscribe the Channel - - Channel and subscribe the Channel - - Verb - 142 Likes Share and Subscribe
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
739 |
hello everyone welcome to quartus camp we are 13th day of november later challenge and the problem we are going to cover in this video is daily temperatures so it is a medium category problem and the input given here is integer array which denotes temperature at each day and we have to return the number of days you have to wait after the current day to get a warmer temperature if there is no future day for which this is possible then the answer is zero so again the output is in the format of an integer array which is nothing but the number of days we have to wait to get a warmer temperature so let's understand this with an example so here's a given input array and we have to fill in our output array answer that has the number of days we have to wait for a warmer day so let's start from the very first day so the temperature is 73 and the next day is 74. so we have to exactly wait one day to reach a warmer temperature than the current temperature so we are putting in one in the output going forward the next day is 74 which is considered to be the current day and from the current day we have to wait one more day to reach a warmer temperature because 75 is greater than 74. so again we are filling one here same way goes on to 75 from 75 if you go and check the next day it is 71 which is actually less than the current day so further moving to the next day it is 69 which is also less than the 75 and going further it is less than 75 and finally there is 76 which is higher than 75 so you have to exactly wait one two three four days to reach a warmer temperature than the current day so i'm gonna fill four here and same goes with the rest of the days and let us feel 71 is greater than 69 and 69 is less than 72 so 70 at 71 we have to wait two more days to reach a warmer temperature so i'm gonna fill two and from 69 we have to fill one and from 72 the next day is 76 so we have to wait one more day to reach a warmer temperature at this stage so i'm gonna fill one and there is 76 when you see the next number is 73 so 23 is obviously not warmer than 76 and we don't have any more days left to calculate or get a warmer date than 76 in that case in the problem statement they said that if we cannot find a warmer day then the answer is going to be zero and for the last day it is again going to be 0 for any problem the last day is going to be having the value 0 because we cannot find warmer day than that day so yes this is going to be our output how are we going to approach this as usual the first approach would be a brute force approach so here if you want to try the brute force approach you're going to iterate the very first day with every other day until we find a greater number than the current number so once you find the greater number you're gonna update the difference between the two numbers in our output array and break the loop and same goes with all other iterations so what if there is an array which is having a higher value at the first index and goes on decreasing till the last day like some 50 entries so which means it is a worst case scenario for this brute force approach that for a very first value you have to iterate till the last day to get a warmer temperature because all other values are decreasing and same goes with the second value so when you start calculating from the second value you have to go through all the values till the last value to reach a higher value or there cannot be a higher value at all since the array is decreasing in that case your algorithm is going to work and we go of n square time complexity which is not at all optimal solution so how do we approach this in an optimal way so as we are iterating the given array the only thing we have to remember is the number of days which are having lesser temperature than the current day so we need a data structure to store or remember those temperatures so stack comes in handy we are going to use a monotonic stack we have already approached used this kind of stack in our previous problem but this is one of the starter kind of beginner problem that you can start using this monotonic stack for a better understanding so moisturic stack is nothing but which maintains the value in a decreasing or increasing order so by using that we are going to calculate our temperature and the days so let's see how we're going to approach this so we're going to maintain a monotonic decreasing stack to store the values or the temperatures in decreasing order if you're not understanding what is that it's okay we are going to keep this stack as a memory to hold the number of days with lesser temperature so that we can calculate the difference between those days and get rid of those temperatures so let's start by having 73 so now 73 is going to be our first value and we are going to put that into our stack so as we are going to remember the number of days or the difference between the number of days between the temperature we need ah index of each temperature so that it is easier for us to calculate the differences that is the only purpose we are entering our temp index here so 73 is that index one so moving on to our next number 74 so now we are checking whether 74 is higher than 73 or higher than the value at the top of the stack yes 74 is actually higher than the value at the top of the stack which actually means we found a warmer day than the previous day in the stack so we can calculate and put a value in our output array so the first thing we have to do is we are going to pop the value 73 comma 1 from the stack because we found a warmer day and we are going to update the value at our output to 1 because we found a warmer day at index 2 so 2 minus 1 is going to be 1 so now we are going to put our stack value to 74 comma 2 so or you can start from 0 and 1 anything is fine it is just the difference between the number of days so now 74 has entered a stack and next value is 75 our current value is 75 and we are checking whether it is higher than the value at the top of the stack yes it is so which means we found another warmer day than the value at top of the stack so value at top of the stack is at index one so we need to update our index one in our output so our output is gonna have one again because the next value the next warmer value is immediate next value to the current value so we are going to pop this value from our stack and we are going to enter this the next value to our stack which is higher so 75 comma 2 enters our stack now we are going to iterate our next value and check whether it is warm so our next value in the array is going to be 71 so 71 is actually not warmer than 75 so we did not find a warmer day than 75 at index 2 so we are going to store them in our stack until we find next greater value so let us update simply 71 comma 3 because 71 is not a greater value we need our stack to remember this so we are not going to pop any value instead we are going to store that value in our stack so there comes the next value 69 so 69 is also less than what is there in the top of the stack so which means we did not find any other warmer day so we are simply going to update our stack to remember this so 69 at index 4 is not warmer than any other previous days so there goes 72 so 72 if you check top of the stack 72 is actually warmer than 69 so what we need to do we are going to pop the 69 because we found a warmer day than 69 and update 72 at index 5. so the first thing we are going to do is we are going to update the value at index 4 because we popped it and we found a warmer tip so now there you go the index is 0 1 2 3 4 so now at 4 we are going to update the difference that is 5 minus 4 is 1 yes so our stack is still there so if you observe what is there before 72 was 71 is also less than 72 which means we found another warmer day than 71 at index 3 so we are going to pop this value and update the value at index 3 so now our index 3 is going to update it with 5 minus 3 so 5 minus 3 is 2 so our index 3 is going to be updated with 2 so after you check the top of the value is 75 and we going to enter 72 is actually less than 75 we did not find a warmer thing so there goes our iteration and the next value is 76 is actually higher than 72 so what are we going to do we are going to update the value at place 5 with the current value we found so the current value we found is at index 6 and at 5 the difference between 5 and 6 is going to be 1 so we are going to update index 5 with value 1 and pop the value from our stack and update the new value to our stack which is 76 comma 3. so if you observe what was their top at top of the stack is 75 76 is greater than 75 so what are we going to do we are going to update the value at index 2 with the difference between sorry the value of 76 is actually six so the difference between six and two is going to be four so we are going to update our index 2 with 4 and pop the value from our stack so now our stack is left with only 76 at index 6 so then we are going to iterate and check what is the next value which is 73 so 73 is not greater than 76 so we did not find a warmer value than 76 so we are not going to pop that from our stack so 70 3 comma 7 enters our stack so we don't have any other values left and we did iterated everything and the stack is not empty and we are left with two more values to obtain so we did not find any warmer day than this so we are going to simply update zeros in the index six and seven and this is gonna be our output so if you observe the way the elements pop from the stack and insert it will be in a decreasing order so that's why this stack is called decreasing monotonic stack so this is going to work in big o of n time complexity as we are iterating our array only once and we go again space complexity because we are going to use an external stack memory to store the values and its indexes so yes this is it you can solve this problem also in constant space but the idea of that problem is bit tricky but and i don't think that we can come up with that in an interview so this is kind of a intuitive as well as optimal solution so let's go to the code now so yes let's declare the basic values so yes as i said we are going to iterate our given input array and update our stack based on the increasing values so yes we are taking each day's temperature and checking whether the temperature of at the top of the stack is less than the current one so if it is less than the current one which means we found a warmer day so we are going to update our uh answer array with the difference so the difference will be uh the value at the top of the stack which is the index and the index minus what is there in the stack will be our output will be put in the output array so if not we are going to push the value simply to our stack without popping anything and finally we are going to return our answer yes this is it let's run and try sorry messed with the brackets let's run right let's submit yes the solution is accepted and we completed our third day challenge continuously so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
907 |
hey guys i hope you are doing well today we are going to talk about the problem 907 from lead code which is named as sum of sub array minimums uh please note that amazon currently is asking question which is based on some similar logic related to shopping amazon shopping items so let's start we are given an array of an integers which is a rr and we need to find the sum of the minimum b where b ranges over every contiguous sub array of arr since the answer may be large return the answer as modulo 10 power nine plus seven so let's look at the example we are given the array three one two four and we need to make all the sub arrays and then we need to take out the minimum of that sub array so for example three itself is the array of one element then we can have one and two and four each of them individually we can take it as one element and then we can create a contiguous sub array of two elements which is three one or one two or two four okay and then we can make the other variations like uh for the three elements array we have three one two or one two four okay so these are listed over here and for each of these we are going to take out the minimum ones and then we are going to add them so we can see over here that three is the only element over here so it's the minimum so three then one then two then four and out of these two one is minimum so we take one over here then one then two is minimum over here as you can see and then we have one minimum then one minimum and then one minimum so we also have another set that i didn't talk about we have a sub array of four elements which is three one two four and here also the minimum element is one so all of these are summing up to 17. now how can we do this problem so one particular method that we can use is by using the histogram method so we can draw a histogram over here and we can treat all of these elements like a histogram right so let's say we have the element called three and then we have one we have two and then we have four right the pattern over here is that we see that we can use a particular stack over here because we need to figure it out like when we take individually three that is the minimum one but when we take three and one these two elements that means that one will be the one that we will be taking because that's what we are going to consider in our sum right and then we when we are taking one and two then again the minimum one will be taken right so according to this logic um if we are placing the elements in the stack so we can use the stacked data structure over here and we can place these elements inside the stack and pop the elements from the stack based on some particular logic so let's mark the indices first so we have three was starting at zeroth right because we know that this is at the zeroth element and one was starting at the first index right and two has an index of two and four has an index of three and um if we make a logic that because we are always concerned about the one when the bar is lowering down right so that's basically the point where we can identify a minimum point so what we can do that we can make our stack over here and we put start putting the indexes of when we see a decline in the bar makes sense right what we can do this is stack so for example when we have a 3 we are going to place this element so initially let's say because before 3 we do not have anything else over here and let's place it minus 1 as a initial value over here right i will just take this value for now so we have a minus one value already present in the stack and in our original array because we have the increasing array over here until four let's place a last element over here which is zero right because this may not be the value which is the declining one from the previous one like in this case right so in the end we have to consider all of those values we are going to understand this once we uh once we proceed with this problem right so let's try to put a zero into this stack right so now our stack our list will basically become three one two four and then we have a zero element and you will understand why i am placing this basically the reason is so in the end whatever is our last value we need to take a minimum value in the end so we can consider those bars in our logic as well so let's say we have three and we place three in our stack right so we place three numbers tech and this is the value the next one is one which is basically smaller than v so now what we can do is before we place one inside this stack we need to pop off this element right so we take out three and we are going to check the upper and the lower range of the three right we can divide this problem so we will traverse through our array and we can place our elements into the stack um if the element is larger right so initial value there was nothing in the stack or let's say we have -1 in the stack so we let's say we have -1 in the stack so we let's say we have -1 in the stack so we can easily place three over here right and then when we have a smaller value one we are going to take it out from the stack right so now this value becomes 3 and then i will calculate it based on the range in which it lies so it lies between minus 1 and 0 and 1 right so i will multiply it by this with okay so basically this is the value this is the starting index of one or let's say we are trading over this point and this is our i value which is iterating from this particular position now i is at one so v our logic would be that we take out the difference between the two histograms so this will be basically i minus index or the index that we pop index of this particular element and that was three right that was zero three and then multiplied by the index minus the value in the stack the previous value in the stack and that is basically we have minus 1 right so this will be this will basically become this stack of stack minus 1. so this value will now become 1 minus 0 which is 1 and then 0 and minus 1 which is also 1. so the value will be 3 over here now next we actually pop this element so this is no more over here now we have the values 1 so we can now remove this value from over here all right so now we can remove we have already removed this value so now we have we only have one two and four okay so the next value would be one right so we say that one is already over here so we place one over here and then the next one is higher than one so again we can place this value and then the next one is again higher than two so we can also place this value but now the last one and this is the reason why we have appended zero because we need in the last we have to take care of all the items which are present in the stack right so now zero is basically less than 4 right so now we are going to start popping right so this index is basically 4. what we can do over here is that we are going to pop off this element which is 4 multiplied by its range so this will be 4 minus 3 which is 1 and then it will be multiplied by 3 minus 2 so that would be 1 again and this value will become 4 okay so now 4 is also popped right so we can remove this one right now we still have 0 which is less than 2 now so the next range now becomes 4 and 2 was starting at 2 right so now our new range becomes 4 and 2. if we pop off this particular element it will be 2 multiplied by 4 minus 2 multiplied by the upper range which will be 2 minus 1 which is again 1 and this will give us 2 multiplied by 2 which is 4. so we can now remove 2 as well from over here now the next value will be 4 and 1 right so this value will be 4 minus 1 which is 3 multiplied by this is this value 1 and multiplied by the upper range which is 1 n minus 1 right so this will be 2 right 1 minus 1 is 2 so 3 multiplied by 2 is basically 6. now if we add all of these three elements this one let's say sorry this one and this is all it will sum up to 17. if you logically see this we have made the histograms and we have considered all the possible solutions in this way by considering all the possible arrays over here now let's try to code this so as we said we are going to append into this array an element zero in the end and then we are going to define a stack which will be -1 -1 -1 and now we can just traverse in the array and we can check that while if the new element which is coming is less than uh error of stack minus one so basically we are instead of uh there is one modification over here instead i try to uh put these values over here four i will put the indexes over here so index of the four which is basically 3 right and index of 2 which is uh which is 2 index of 1 which is 1 and then index of 3 which is 0 okay so i'm going to play with the indexes rather than the value themselves we will always append the index over here and here we will check we can check the index so this is basically our current value and then we are going to check the index when this is smaller than what was already present in the stack so we are just going to say stack dot pop okay and then we can just define our resulting variable over here and we can say that result plus are our index multiplied by so this particular index right because we are going to take out let's say 1 over here or 4 over here so whatever the value was we are going to let's say this was 4 over here we take this value out right so it will be the it will be a r index multiplied by this particular value the upper range and the lower range this will be i minus index multiplied by index minus stack minus 1 and in the stack minus 1 as you can see i'm using the last previous index right so this will be whatever the index it's holding over here so this is basically the stack of indexes right so i think now we are going to return the result and as it says over here we need to module the answer so that would be result modulo 10 power 9 plus 7 all right so now it works we are going to submit so it works right i think the problem is not very complicated please review the video again if you need to so guys if you have not pressed the like button by now press it now and subscribe to the video so that you don't miss important updates in the upcoming videos so until then good day
|
Sum of Subarray Minimums
|
koko-eating-bananas
|
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`
| null |
Array,Binary Search
|
Medium
|
788,1335,2188
|
990 |
uh let's talk about the satisfiability of equality equation so you are given a string array of equations so they represent a relationship between variable for each string equation i is the length of a four and every single string has two variables and you have to have you have an equal bit operation and an equal bit operation right so you have to assign uh x equal to y but in uh in the meanwhile if you find out y is not equal to x you have to return false so this question you have to use a pretty efficient way algorithm to actually call it so in your code you can minimize uh the mistake a lot right so you can actually use hash man and then when you transverse in the first string right when you say a equal to b you also have to say b equal to a right at the same time and then when you find out okay b is not equal to a and then and in your hash man okay this uh this is the first iteration you put into your hash map right and then when you find out b is not equal to a in the meanwhile in hash man you have equal to a so you have to return first but this is actually taking a lot of effort to code for sure because there are some corner case for sure right so uh there's a better way so uh the most efficient way in my opinion is called union fine so union fund is actually really helpful so if you want to go deeper about the union fight you have to go on other source page to go i mean to dig on it and in this one i'm going to just briefly talk about how i actually how i understand about the union fine be honest right so i'm going to just assign the size of the union prime so how do i assign so uh how many nodes do i have a 26 note be honest because they have 26 lowercase later right so when i try to transverse the entire equation i mean before i traverse the entire equation i'm going to just create 26 note 26 no of the uh 126 note in my union fine and then for every single note i'm going to just point the answer search to myself first right so i know there's no loop uh without the null and then when i call my this note it will return itself right so in the beginning i would just by default doing like this right so how do i actually uh make these two notes connect together so i would have to assign okay this is number one this is number two i'll have to assign it uh my number one be my ancestor of number two right so um so okay this is not the way you actually write it so i said number one be my access of number two right so i'm going to say the parents of two so i'm going to create an array right this is entire thing is array right so i'm going to say parent two is equal to one so when i assign right by another sign i'm going to change another color this pointer is directly 0.81 for sure so pointer is directly 0.81 for sure so pointer is directly 0.81 for sure so this is actually what this is actually the small tree be honest so i can just keep going up when i giving the sensor i want to give the note 2 value right i can keep keeping keep going up to the ancestor and then to find out who is the tree no i mean be honest the root be honest root for this current subtree for sure right so i will have a find another function for fine i'm gonna pass in no one and no two right then i would uh okay actually i don't need no two i can only need no one i can only have no one uh let's be honest because i would just keep calling my parent array to current a para array for my no one so i'll just keep assigning right paren and then parent and then no one so this is going to uh join my grandparent be honest right this is butter uh you can get you can call moderate as well but in this one you go to grandparent right this is parent this is grandparent right and you have to update your no one to your parent so you will keep going up right and when you want to find out the union plan right so when you want to connect together right you have uh you have a union function and you are passing two points right it's going to be no one and no two and then uh when you call this function if they are not equal if at the end if they are not equal then you can actually assign uh my parent t equal to paramount i mean parent two equal to one right and this is pretty much the solution and let me stop call it and then you find out what is the uh what is the problem right here so i'm gonna call union find class right and i have a parent array and i'm gonna call parents right and then i and i don't know the size right and i would have to create a people constructor and i passing the size and then if i know the size i'm going to say new inks and then i'm going to quickly traverse the entire in array and then set the default size to yourself right okay now this is the base case i set the ancestor for every single node two results now uh again i say you need uh you know what you need uh union you need to connect right and then you need to pass into node i'm gonna call no one and no two right and then what else uh whatever fine right you need no one all right uh let's talk for no one so for the null one right we already know the parent array and then uh for this current no like i can actually assets to the parent rate so i can know okay who are actually uh pointed which not right so who is the ancestor of no one right so i can just using the well uh well parent notes parent and note one it's not equal to no one so you can actually keep traversing so this is actually what when parent equal to node one right when parent node one is x equal to no one this is such a default value but when they are not equal you can actually find out your grandparent for sure right so parents at no one it's actually go to uh it's actually your grandparent right grandparent and no one and after this i'm going to just update my note 1 two parents and no one so i can keep going up to the grandparent penguin parent and so on right then later i always have to return no one so this is pretty much it for the fine right and then for the union function i'm going to call the fine and then uh i need to call root 1 for my node 1 right i'm going to find node 1 and then entire same thing for root 2 equal to five not two so uh i will have to find out who is my root one for node one who is my root two for node two if they are not equal i can actually uh change the add change their accessor pointer to the other right so if root one is not equal to nu2 right i'm going to assign my route to uh root equal to uh connect beyond connect together right then i need another function i'm going to call boolean i'm going to say it's connect and then in this one i'm going to pass in two notes right and then i will have to return by using the find function if they are equal i'm going to say if i have no one is s equal to fine you know two right this is pretty much the union fine class you have to do at least it's actually pretty straightforward so if you didn't know like you don't want to go uh too confused uh you don't want to go uh too confused because uh i will probably say you will get confused at this point but think about this when you go on pattern you want to go on grim period right you have to keep updating your known one to your parent so you can keep going up right so that would be it right so all right this is too much talking now so back to the solution class so i have an end so i represent the equation from there and i'm going for union 5 i'm going to call uf equal to new union fine and now passing the size of into my union fine right all right so uh i'm going to try hosting entire streamer right string equation equations and then uh in my equation right i will have one i will have a uh i mean i will have a first variable and i will have second variable and then for the equal sign and not equal sign the main difference is this character right so this is actually what this is actually fixed position so if uh if equation um i'm going to just call a 0 and i need to subtract the a and then b equal to equation at position 1 position three minus a right and then since i'm putting uh putting the inner ring inside the union class i can just go in be honest and then this will actually make me make my work so easy and then i'm going to just what for the first follow i'm going to find out if they are equal right if they are equal so equation dot char at first position if they are actually equal to equal sign right so i'm traversing the equality first i'm not checking the not equal sign first so if they are not equal i'm going to ignore because i'm going to traverse knight for later because probably uh not equal will go first and then people will go second right so this is actually the certain uh this is actually based on your source but we don't want to solve this equation because this will take a normal and then this is not efficient so it's not equal if they are equal i'm going to call it uf dot right i'm passing a comma b i'm going to connect a and b together and this is pretty much the first iteration and again i'm going to traverse again but this time i'm going to say okay if they are not equal and the first index if they are not equal and then if they are not equal then if i find out its connect is connect function uf dot a comma b if they actually connect in the uh in the union find class i'm going to compose and everything else i'm going to return to and here we go i might have a mistake but i don't care let me submit all right okay i don't have it uh all right uh yes i do admit uh i don't have a mistake so this is going to be what uh this is going to be okay i have a mistake right here so uh again i say uh how many sides this is not inside this actually 26 the size of 26 because they are lowercase all right i made a mistake but whatever man this is life all right okay so i passed the test so let's talk about timing space right and this one for this one this is going to be a space all of 26 so it should be the characters for lowercase right and then in this function in this class right this is actually all of n all of 26 right full time and for the space right this is space this is fair this is time and in this one this is actually one uh this is actually log of 26 be honest because you don't need uh you probably don't need um you probably when you traverse for the fine right because when the uh when you go on fine you can just go on your ancestor you don't need to go every single note right only if there are if they are coming every single note together but uh in the meanwhile you update for sure in the meanwhile you update your current node and then this will be i will say all of okay this is i would say all of them all right anyway but this is actually depends on your note all right and this is what this is actually define you'll find so this is time but you can actually go deep i mean go find out your solution for time complexity right over here but this is not the main problem so in this one this is out of n and represent the density equations and this one i union right so union just called the union um uh union function and this will give you the time complexity based on your fine right and then this one is what this one we call it again this is all of them right so uh i have a quick note for my time in space complexity so if you do not agree with me then you will probably have to find out another solution so and c log c represent the end of the lowercase alphabet and space is all of c this is because i use a space of 26 right and i represent the representation of the equation right and then c velocity c loss is actually uh it's actually the case in fine be honest right and then this is pretty much the solution so if you feel this is helpful and leave a like subscribe if you want it so uh if you want to go deeper into union find how you actually build how you actually work the function or the actually something else you can go on other source page to go on it i mean to study so in this one i'm just briefly talk about the union find class so uh this is pretty much it and i will see you next time bye
|
Satisfiability of Equality Equations
|
verifying-an-alien-dictionary
|
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter.
| null |
Array,Hash Table,String
|
Easy
| null |
504 |
Kevin in the jury returned its base seven string representation okay I mean this seems actually great I mean I think for these palms is always at least four kind of for the purpose of twitching and maybe even for interviews you always try to figure out like what's the best way to kind of think about these things and whelming the best thing to do is just use the library I think if you use someone like you turned and you know seven or something like that immediate community string something like that fine work because that is but anyway the idea is that in general there are languages that have built-in languages that have built-in languages that have built-in functionalities or libraries I don't wait oh that's this so yeah so I mean so that's pretty straightforward don't have a typo sorry you have to learn how to use your you survive more so it's a funny test of that's that way didn't number Ten's face seven representation okay no come on the other way hmm yeah okay I mean so oh yeah a lot of these cases you would do the just one a library which is not that interesting for the purpose of kind of actually trying to solve this form and I suspect that if like for example that we're doing is in an interview I mean I think what I would normally do it as a interviewee is to be like yeah I'm yeah first of all what which is why I meant to be flew out to the library function but I also have reasonable expectation that the interviewer will be okay that's great now what it get implemented but because yeah cuz if you don't have people don't implement it and I mean it becomes trivial rather than like even any reasonable like no one learns how much you know about programming with you just what morning libraries I mean it just has a very low ceiling light as to like how much information you get from that so I'm gonna try to actually call this out so it's in between two cases so I also always find these naming to be kind of sometimes and don't talk because a lot of programming problems you know really even given the context right so like let's say you're looking up actual real life project then you have to context to the fun figure out like you know what it's actually gonna be useful so you have more ideas about it but in cases like this it's just a lot of like wizards and finding what you use and like things I don't know but uh okay cool so that's kind of sets it up and then this is just you know with and basically uh for phase seven or we do is just yeah we keep on trying to divide it by 7 and then get the model of God as much as possible so that pretty much good actually and yeah I think just write something about languages that I'm yeah well thanks John well I already took you can't do negative Co so I should be okay I mean there's some stuff about like the standard library usage that I'm not confident about something with just one see where complaints yeah like a string diverse or something but the idea is that because that's fine I'll just do something like this means that first your least significant digits you're always you'll keep on getting your least significant digit okay that's good um okay so it did actually it ended that's a big testing did that should be okay well I mean of course we should then usually just test out stuff to try you the negative 100 oh I got to convert this okay now thanks and lamp yeah and imagine that actually works on the connection but yeah I just forgot wait but this is PI also just easy to understand and allow me did explain because I was just kind of treating the string as a happy away where the least significant digit is first where it should be last in you know your like representation so yeah this yeah I mean I think it doesn't really matter the way except for well if you have a huge number and you know string concatenation and stuff like that might become an issue but I think for less than what a million there should be okay I'm not too worried about it so no that's rather than put actually think sometimes I check this in case yeah okay so I guess maybe okay don't win something I mean it is easy stuff okay so that dad was some yeah hope you to a fancy way divided number to become CEO that's oh yeah you I guess that yeah use every way you can we get that for you optimize this to someone like this I guess so that quiet also salted really play around with that but uh well yeah I think for me and some of that is unfamiliarity with Python stuff in general because I always forget like to be fine one concern I had while I was coding was it was better this actually gives me a full or an integer because some dagger to die I always forget which languages which and some languages safety like a magic conversion somewhere and that's something that we're here about sometimes I was just making sure I get it right but you're definitely right there are definite optimizations here or legmen necessary optimality like minor clean ups that we can do and I think at this phrase with that guy put me I definitely optimized for correctness first and then I would talk if I was an interview now we talk to the anyway and okay now that I got to just you know mostly correct these are the things I would work on including subject you're talking about maybe reverse train which maybe that was not a great that I'm being there may be plenty into a place or then because connect him at the end I am would be were saying about like eating normally was seven and I mean it doesn't it isn't any slower but in stepping cleaner to be for sure right
|
Base 7
|
base-7
|
Given an integer `num`, return _a string of its **base 7** representation_.
**Example 1:**
**Input:** num = 100
**Output:** "202"
**Example 2:**
**Input:** num = -7
**Output:** "-10"
**Constraints:**
* `-107 <= num <= 107`
| null |
Math
|
Easy
| null |
328 |
to work um hi guys this is vaga we are going to do another little question the question in question is number three to eight even linked list pretty straightforward so you're given um a linked list you're supposed to add the odd nudes and um followed by the even nudes note that we're not talking about the value but we're talking about the nodes so in this case we have one two three four five right you're supposed to return one three then five that is the first the third and the fifth and then afterwards you add the second and the fourth note like so right so basically pretty straightforward right same here just take the odds like dick take this and then um take this two three six seven and then add one five four like so and then points to null at the end so pretty that um the idea here is to use pointers and keep track of everything uh it's easier if you can just write it out so we're just going to go through one example on how we could do it um so you can see it visually because you'll understand better when you do it visually so let's get to that this is one two three four five right so it connects to each other and the first thing we want to do is we want to we could put a couple of pointers right that will um start off and at first we'll have um we could have a pointer uh of course the first pointer will be at the very head so we have a head pointer here and um we also have our odd pointer which will be here and our even pointer will be set to be the next one so we put um the node for the fast so we put our even point uh here and um we could also have a pointer for the even list right we could put here even or we just put list like so right so the next thing we need to do is we would have maybe a while loop that will check that maybe we'll check a certain condition and then we move the odd pointer here for example which is on the first one we move it to the one after the even one right so we move odd from one to um to the one after the even and this case is three right so we have our odd pointer on the three right and after that we say that um we move the next point after the odd we remove this pointer from here and we make sure that the pointer after the odd points to the next odd right the pointer after the head points to the next odd so for example you could come here and get rid of this right we just cut this here paste this and maybe remove this and this is now even listed or even and now from our head the next pointer points to three right we have moved it right and after that we move our even uh even pointer to point to the um the one after even is going to be the one after the odd right so we move our even pointer to point to four right so we move it here like so right and um even the next is going to be the one after the odd dot next so it's moved to four so we could come here and um cut this get rid of this point this here so um this is our even and we can move it from the two right and after that we move our even we have moved even from the two to the four and after that we move our odd to the one after um our odd next is going to be our even dot next and in this case our even dot next was uh five so we move our odd here this is basically all going to happen in a while loop right so we move our odd here and after that um we of course come to null right and after not pull but now after that when it comes to null if um we get out of the while loop what you're supposed to do is take this list this even list and connect it what you're supposed to do here is connect it to the order.next when odd gets to when we the order.next when odd gets to when we the order.next when odd gets to when we hit null right so we just come here and connect this like so right so we have one three five and then two and four so basically that is uh that is the idea behind our code and now all we need to do is just write it out i've explained like the way we move our pointers and um how they interchange with each other with the odd um the odd.next being what is the even dot the odd.next being what is the even dot the odd.next being what is the even dot next and then moving it um the even.next to be what that odds um the even.next to be what that odds um the even.next to be what that odds version is and we continue until we get to a null and then we move the entire list um we move the entire list to the end of the final odd so basically that is the pseudocode and now what is left is just write right we need to check if we have a head and we say if not head return head like so right now we need our pointers right we need um we need uh the even lists the odd and the even right and we agree that the odd will start at the very head of the list the linked list so the odd is at the head the even is the one after that which is um going to be odd dot next and after that the even list is going to be also on the even right so both of them are on the even right and um what we need to check the while loop is going to check that even and even dots next right well we have an even while the even and the even the next is valid we have not yet hit null that is that's what that quote does what you're supposed to do is just move the odd so we say odd dot next it's going to be set to whatever is after the event because you know that one will be odd so it's going to be even dot next in this case what we are doing is we're connecting one to three right so odd.next is going to be even.next and so odd.next is going to be even.next and so odd.next is going to be even.next and after that um we move our odd pointer to the odd dot next right so we have moved our out pointers the odd dot next and when it comes to even we say event.next event.next event.next is going to be moved to that odds odd.next right so we say odd.next right so we say odd.next right so we say odd dot next right and after that the even is now moved to the even.next right to the even.next right to the even.next right so we move even to the even.next and now so we move even to the even.next and now so we move even to the even.next and now when we finally run through all this we get to the point where we get to null right and um when we get null right we have not broken out we want to um our odd will now be in this case we'll be now at five right so our odd is at five what we want to do is now we just want to connect the odd to the even list which started which is still connected to our first even right so here what we do is just say odd dot next is going to be our even list and what we want to do now is just return head like so right so if we do this um we are supposed to presumably we are going to get our answer hood we're going to get an accepted and if we submit it's going to be accepted and the what's it called the um the time complexity is going to be over and we're going through every node and the linked list and the space complexity is going to be of one because we do not return uh we do not use any structures so basically that thank you for watching subscribe to the channel i'll see you in the next video
|
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
|
968 |
hello everyone welcome to the 17th of june eco challenge and i hope all of you are having a great time my name is sanchez i'm working as technical architect sd4 at adobe and here i present binary tree cameras it's a hard level question on lead code and i also feel the same however for all those who have been associated with the channel may know that we already solved this question in the month of may 2021 last year the like says it all the comments says it all and i have clearly explained the algorithm here it's not a very difficult question guys once you will go through this video you yourself will feel that it was a medium level question however there's a small trick associated with it just walk through this video till the concept and then try to look around or device the algorithm by yourself code it up by yourself and if you're still not able to solve then come back to this video also guys thanks for such an overwhelming response that i have got on linkedin with respect to coding decoded dsl preparation sheet uh and it makes me feel that the entire effort for making these sheets were worth doing i'm getting couple of messages with respect to bit manipulation backtracking tries graph dynamic programming which is one of the most toughest topic to understand and these sheets are helping you out it makes me feel accomplished i'm attaching this link again for those who are unaware about these sheets so do check them out there you'll find the templates along with various multiple questions that are must do before an interview and they will give you enough confidence with respect to each and every topic that is mentioned over here so do check them out over to you guys in the next two months please give your hundred percent because placement season is around the corner and either you live a life of discipline or you live a life of regrets i don't want any subscriber of coding the goat it should feel that after these two months is gone he or she didn't prepare well for the placement season if you need any help then i'm always there for you with respect to placement internship job opportunities at adobe please feel free to drop a message on the telegram group or the discord server of coding decoded and i'll try to do as much as i could for all of you with this let's wrap up today's session i hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it and stay tuned plenty of things are coming up you
|
Binary Tree Cameras
|
beautiful-array
|
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0`
| null |
Array,Math,Divide and Conquer
|
Medium
| null |
349 |
welcome back to next problem of lead code 349 intersection of two arrays so we are asked we are given two arrays nums one and nums two return and we are asked to return an array of their intersection and intersection should contain only the unique elements so for example uh one two one and two num uh these are nums one and nums two and we will be returning only two we won't be returning two and two since uh it contains two and two we don't need to contain the unique elements we just need to contain the element that can both of arrays contain and its frequency should be only one for example let's take another problem uh 495 and 94984 so nine and four will be our answer so what I'll be doing basically I'll be putting one of the array in hash set headset will eliminate all the duplicates of one array and then I'll be looping through my second array I'll when I will be looping through my second array I will be removing the elements from has set whatever I have already got and put that in my answer I know it's kind of complicated right now but I'll be explaining you in a bit here let's declare the headset first hash s set no asset okay now I'm looping through my first array nums one dot okay and then set dot add nums one I so it's going to add all the elements of nums one array in my set and my for example my nums one is one two one so my set will be containing one and two only because set maintains an order as well and the set contains only the elements only uh I mean set doesn't contain the duplicates so that's the basic idea so in while looping through okay let me get my answer list of integers so now it's time to hydrate through secondary nums to so if now I have added all the elements of first array in my set and now I'm going to check if the area if the element that is present in nums 2 does my set contain that element or not if my set contains that element I will put that element if element that is present in nums 2 is contained by set as well I'll put that element in my answer and then after putting that element in my answer I will be deleting that element I will be removing that element from my set because I don't I do not want to deal with the duplicates so how I'm going to do it if set Dot contains nums 2i if my set contains this element the element present in the second array then I will be adding answer dot add nums to and set Dot remove nums to I so that's it that's basically it I'll be removing the elements and I'll be adding the elements in it so now the only thing is that is left because uh they our answer should be returned in an array so for that I'll declare an array new end and its length should be my uh it should be the size of my answer so what is that answer Dot size and let's Loop through the list if four and I is equal to 0 I smaller than n I smaller than answer Dot size I plus and then I'm going to do is uh area of I is equal to answer dot get I and answer return array simple so what I did I put all the elements or in my hair set of first array and then I compared those elements with my secondary if my set contains the elements that are present in second array as well I'll be putting those element in my answer and I'll remove those elements from the set as well the reason why I'm removing those elements from my set as well because I want to include only the unique elements so for example if this is the first array this is the second array and for example if I put this one in my headset first two and then I'm comparing these elements right one two one then my set is containing only two so then after checking this for example if it checked two so two is present in the set right and then it moves to another two and it says it's still present in this head so that will be a confusion for my problem so to avoid those confusions I'll be removing the elements of whatever I found in my set so let's try to run this problem let's see what we got accepted here and our solution is the fastest and the with the cheapest memory
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
508 |
hey everyone today we are going to serve with a little question most frequent subtree sum so you are given root of binary three Returns the most frequent subdivision if there is a tie return all the values with the highest frequency in any order the subtree sum over node is defined as the sum of all the nodes values formed by the subtriluted at the node that include including the node itself so let's see the example so you are given like a two a five to three minus 3 and the output is 2 minus 3 4 so because if this node is a root of subtree so in the case uh total number of subtree should be five plus two plus minus three and four so there's a 4 here and if this node is a root node of subject in the case so these two doesn't have any child so in the case the total number of subtree should be 2. so there's a 2 here and then same thing if this node is root node of subtree total number of substrings to be minus three so minus C is here so that's why output is 2 minus three in four before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example so to solve this question I use a div spot search and then every time we calculates the total number of subtree I put the total number into hashmap with a frequency so let's begin first of all we are now root here and then go left and there's no left side in the case um we put zero value and then go back so because zero doesn't affect the number or total number of sub 3 so that's why if there is not node we put zero and then go right so there's no right side so in that case I put there here so zero and then so calculates this subject so total number of this should be three so that's why I put three and the frequency is one right and then I move back and I go right and then so okay let me change the color and go left but there's no left side so in the case we put 0 here and then go back and go right and there's no right side so also put zero here and then calculates this sub 3 and the total number of this software should be four right so that's why I put 4 in the frequency is 1. and then go back so now um calculates uh this sub 3 so total number of this net subtree should be two plus three plus four in the total nine and the frequency is now one right and then go back and then we finish the calculation on the left side so go right so let me change the color to Blue so from -5 so from -5 so from -5 um take the left side but there is no left child so we put the arrow here and then go right and check the right side light style but there is no right style so we put 0 here so total number of this substitute should be -5 should be -5 should be -5 and the frequency is one right and then I'll go back so then um Orange we calculate this sub 3 so a total number of this orange actually should be 5 minus five and zero and the two plus three plus four and total nine right so are frequency to nine so now plus one and the total two then we finish all calculation then now check the hash map and the most frequent value should be 9 in this case so that's why we should return this nine yeah so that is a basic idea to solve this question without being said let's get into the code okay so let's go first of all initialize flick equal um hashmap and then um devs file search and passing the node and then let's create a text for such as an inner function and taking a node first of all implement the base case so if not node in the case as I explained earlier return zero so zero doesn't affect and total number of sub three and then after that calculate Cube right and the sub 3 sum early so left sum equal this for such and the node dot left in the right sum equal this for such and then all the dot right after that um sub 3 sub equal left sum plus light sum plus current value and then increase increment um the flick and see of the sub tree sum so freak sub 3 sum equal 1 plus um flick dot get and uh keys are sub 3 sum and if we don't have that number different value should be zero and then after that just return and sub 3 sum yeah so that is a device search and after that um so we have to return and all the values with the highest frequency in any order so the return value should be like a multiple so how can we return the highest frequency value so first of all um check the max frick equal Max and uh freak dot values and then um s for so s stands for like sum and if either like a frequency of the value so in Click dot items and if F equal Max fridge yeah so I think uh it will work so let me some submit it yeah looks good and the time complexity of this version should be order of n where n is the number of nodes in the input tree so because we visit each node once during the first search so that's why all the open so space complexity is also order of n because we store the frequency of each subtree sum in your dictionary so in the worst case total number of subtree are all unique so that's why Oda of n 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 will see you in the next question
|
Most Frequent Subtree Sum
|
most-frequent-subtree-sum
|
Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order.
The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
**Example 1:**
**Input:** root = \[5,2,-3\]
**Output:** \[2,-3,4\]
**Example 2:**
**Input:** root = \[5,2,-5\]
**Output:** \[2\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
| null |
Hash Table,Tree,Depth-First Search,Binary Tree
|
Medium
|
572,2126
|
139 |
lead code problem number 139 word break so this problem gives us a string called s and a dictionary of strings called word dict and what we have to do is return true if the string s can be segmented into a space separated sequence of one of more dictionary words and here it also states that we can use the same word in a dictionary multiple times in the segmentation so I wanted to do is basically here for example the string we have is lead code and the word dick is lead and code so what he wants us to find out is whether or not we can break this up into perfect pieces that suits that is inside the word deck which in this case we can because we have lead the first four characters and code which is a last four characters of the string here he also shows an example of us reusing the word apple right so we can use it multiple times and here it gives us another example where even though there is cats right there's cat there's sand and there's dog it returns false right because if you notice if we use cats or use cat right cat and sand then we don't have any another D for dog right but if you use dog then we don't have anything that can that when we break out cat sand into right because sand also uses a d do also uses a d That's why it returns false so the way I did this was to use a method called bottom up again so first here I'm storing the size of the string so let's say the string I have is for example D code I guess and then the word dictionary is lead and then code right so here in my DP I have a vector which stores the size which STS uh an amount of characters or false values inside so each character I'm going to be checking at that position whether or not it's possible to find a word that matches in the word string right that's why we need size plus one size D1 would be D zero right so one two so there is eight characters here so that means we will have eight + one so that means we will have eight + one so that means we will have eight + one false right because it's size plus one 3 four 5 6 7 8 n okay and the last one we are going to set it as true because we know if we were to reach the last character over here right it means that we have solved the word and the goal is to return the first uh the first Boolean so let's say lead code for example right so you know lead is we know we can find actually we are solving it from the back so let's say for example this character e right we know e does not exist inside Elite code so we set this we keep this as false we know D or de does not exist inside our word dictionary so we set it as false so we set false until we hit this character C and which you can see the word code exist inside our deck right so for this C we're going to mark it as true and think should be this one right c o d right so if you continue and do the rest essentially this will become true as well right because this L is dependent on whether or not we can solve lead right at the same time we also need to check whether or not we can solve the characters in front of it right so in this case we can because there because we know if DP lead which is this plus the length of lead which is four so 0 1 2 3 4 so if this is true as well meaning that we can move four more and over here it says that it's true meaning that we can solve lead on from lead onwards right meaning that we can solve the word e code using the dictionaries given to us right so basically that's the idea behind this bottom up strategy or lthm right so that's why here we have to set it as true the last character is true this will just indicate whether or not we have found the word okay so as I mentioned we are starting from the back so that's why I have a for Loop here which iterates from the back so I is equals to State minus one here I have another for Loop which will iterate through the word I'll do it like this so the word where add for now would be lead right and J would always stay at four for this case because all the words inside our dictionary are four in length so J will always be fall so let's say we are starting at the last character right character e so here we check first right size minus I so remember size is 8 minus I is s is it more than four right in this case it's not that means we know that there is no characters or at least this e character does not even fit our first word le all right so this if statement is sign n then we go on to the next word which is code but same thing with code since code is also four in length so this statement over here size minus I will not does not fit inside our dictionary so this is the would you ignore and this will go on until we iterate through all the word right which in this case we did read the code so once that is done we decrement I right so I will decrement to six and now we are looking at d and e but for this Cas since d and e is technically the same thing because what you have is 8 minus I which is six it's still minus 8 minus I which is six it's still more than it's still lesser than four right because de is of length two and the word we have in the word dictionary are for so spoiler alert this will decrement until I is equal to four where we are at code now all right so let me refresh this is lead we over here I to four and now sze I 8 - 4 is equals to 4 all right which I 8 - 4 is equals to 4 all right which I 8 - 4 is equals to 4 all right which is the size of our character and now we want to check whether or not the substring so subring works like this we're starting at I character I so in this case sleep code I is at 0 1 2 3 4 so I is over here and we are sub stringing four characters right four so one 2 three four which is perfectly fine which is perfect because that gives us a word code right so we're checking whether or not the current word code right the subring so we're checking whether or not the this subring equals to our current word which it does not because our current word is lead and the code we are at is code so again this if statement doesn't trigger and we move on to the next dictionary next word in our dictionary code now for this case since both of them are the same then we have to check again right so we to check again since we can solve for code can we solve it if we are using Code as one of the answers right so that's why we have this so DP I right now I is four plus the length of our current word which is four this will give us DP of eight right and if you notice DP of 8 0 1 2 3 4 5 6 7 8 will give will return us the end of the string right meaning that if we were to have code as one of the answers this is a possible solution right code is one of the possible solution so when it happens our DPI current DPI which is four 0 1 two three four this will be set to true okay once that is done we break out of the current Loop but in this case since we have iterated through all of the words in the dictionary it does not make a difference anyways we still have to decrement I and move on to the next word right okay so now since I is small enough this statement will always trigger right because we are at Big big numbers now but the substring we have does not have the word right we're not does not have the word right we're looking for remember that we are sub stringing four characters only right now we're looking at tcod and we're checking whether or not it is one of the word inside our dictionary which it's not right TC is not so we move on decrement one more time now the sub becomes etco again we cannot find anything and this will repeat until we reach zero where I where 8 minus 0 is obviously more than four and we are subring from character I which is zero starting from L and four characters right so one two three four we get lead okay now that this is true as well right because our current word is lead so we have to check whether or not with lead we are able to solve the string if lead were to be a possible answer so the way we do this is DP I which is zero plus J and J is four right so this will give us DP of four and if you notice 0 1 2 3 4 we know that from four onward we can solve the string using the existing words in the dictionary because we just now have tested that from code onwards we can solve it right that's why there was a true here so since this was true we can set DPI which is zero to true so we can set this as true which is the first character of our string so when that happens this fer will end or more like this for will be broken out so we don't need to test for code anymore this after for Loop will end because I now has reached zero it cannot decrement further and then we return DP of zero meaning the first character of our string the DP first character which is true right meaning that we can solve this string using the dictionary words right that's why there was a true here okay so once that is done we return true and that is basically the answer for the example given as well all right okay hopefully you can see that this is a pretty straightforward question but the solution to this can be a bit tricky if you don't know bottom UPS beforehand but either way that's all I have to show thanks
|
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
|
438 |
hello and welcome to another CS tutor Center video in this video we're going to talk about the problem finding all anagrams in a string but before we get started please go ahead and subscribe to the channel if you're enjoying these videos when you subscribe to the channel that lets me know that you enjoy these videos and as a result I'll make more of them all right let's get started so this problem says given two strings S and P return in array of all the star indices of P's anagrams in s you may return the answer in any order an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all the original letters exactly once so in this example below they have this um string ABC and then the anagrams they find is one right here and this is a start index which is zero and then they also find one over here and the start index here is six so 06 okay and then the ab here so we got one at Z starting at zero we got one starting at one we got one starting at two whenever looking at these problems you always want to start thinking what kind of coding pattern you'll use and in this one a sliding window would work really well because what we could do is we can make a window be the size of this string and what we'll do is we'll start that window size out over here and then we'll see if those letters are inside of this um the letter counts inside this window match what we need from here from this string and if so then we'll record that uh start window index into the array and then we'll just slide over one to the right and as we slide to the right one letter leaves the window and one letter enters the window and we keep on doing that sliding and what happens is that we only have to go over this once as a result of that and if you give me some uh string like this which has n characters and I only have to go over that string once I've gone over all n only once that's linear so that means the Big O is linear and then we want to think to ourselves is there a way that we can have a big O that would be faster than linear and the answer is no because if we think about this problem let's think about the string like this we have some type of string but I'm going to put a bunch of question marks in here because we have not yet revealed the letters inside that string and if I can do better than linear that means I wouldn't have to reveal one of these question marks but I know I have to reveal all the question marks because maybe one of them is you know the one that would be the key that would let me know if the letters are inside of the string so let's go like that so I know I have to reveal all the question marks I know that means that I have to look at all the letters at least once so I know I can't do any better than linear I know that the sliding window can solve this problem in linear time complexity so the sliding window is the way to go all right so we'll go down to the constraints to see what else we can learn the constraint says that the S string and the P string are between sze one and three * 10 4 one and three * 10 4 one and three * 10 4 inclusive so that's what that means is that um the P string which has our pattern of what we want to see is inside of the S string this P string can be larger than the S string according to these constraints and if the P string is larger than the S string then um we could just return false because there's because we wouldn't be able to find an anagram of P inside of s if p is larger than S okay um this constraint here tells us that P and S consists of lowercase English letters so then we know that the number the maximum number of letters that we'd be working with is 26 because the English alphabet has 26 letters so we can use an array of size 26 to keep track of the frequency count of each of these letters that is inside of P okay and that will be better than using a hashmap um we could use a hashmap in fact if this constraint wasn't here and there if there was no bound on what these letters could be if we could have all kinds of weird punctuation and um you know all kinds of Unicode characters then we would use a hashmap in that case because we wouldn't know how big our um array needs to be we wouldn't want to have some massive array so we would use a hashmap in that case but in this case it's only 26 and so we can use an array and the reason why it's better to use an array is because the real world old run time is going to be a little bit faster so you know that both the hashmap and also the array has a big O time complexity of constant so it's not going to change the Big O time complexity but the real world run time is going to be faster because when we access a value inside of an array we give it the index and it's a direct lookup there's no delay there but when we access a value inside of a hash map what happen happens is there's a hash function that calculates the hash code which mods that unique number from the hash code with the size of the array that's inside of the hash map to keep it within the bounds of that internal array and then it's going to go to that array location in the hashmap which each array location in the hashmap is a link list and it will then add on to that linked list the value and the reason why each location inside of the array of the hashmap is a linked list is in case there is any collisions and so really the hashmap you could run into a situation where there's a lot of collisions and that Collision slows it down but average out it's still constant so the real way to think about the time complexity on the hashmap is that it's going to be the time it takes to iterate over the longest links list um in that array um where all those collisions where the most am collisions occurred okay so I have another video where I draw it out um I'll put that in the description here so you can click on that to um look at me drawing out the hashmap and explaining that um this video is also part of a sliding window playlist so I'll put the link to that playlist in the description too so this is example one of the problem in this example we have P which is the string that we're trying to find all the anagrams for inside of this array we have a variable called match I'll explain what that means we have a variable called unique letters which is going to keep track of how many unique letters we have inside this string I'll set that to zero and we'll build that up then we have this array over here that um keeps track of um the counts of these letters and then I wrote this over here which if you go look up a uh ask key map that's what this is um I'm just going to do the first three here so we have the decimal value of the character a which is 65 the decimal value of the character B which is 66 and the decimal value of the character C which is 67 we'll use this the ability to um know this we'll use that to create the count of these letters so let's get started with this so first we're GNA um set up this counts so we read a from the P string and we say we're going to do a we just read a and then we're going to subtract off a from it which equals zero so we're doing this math to figure out our index so we read a we subtract off a we get zero so we go to zero and we're going to increment this to one and then we read B and we subtract a off from B and that's index one so we go to index one and then we read C and we say C minus a which is index two so we go to index two okay so now we have our counts okay and then let me back up a second here um let me go back real quick when we're doing this there's also one thing we're going to do what we're going to do is when we let's start over and I'll explain that when we read a and we say a minus 0 we go to index Zer we see that it is zero since it is zero that means we just encountered a letter we hadn't ever seen before so we're going to increase our uniques this keeps track of the unique letters we have okay and then this gets increased to one and then we read B and say B minus a is index one oh there's a zero there so that means we haven't ever seen the letter B before so let's say we have another unique letter that we haven't seen and we'll increase this over here to say we um the number of B's we have then we read C we say C minus a which is two so we go here and we see oh we have another zero so we've never seen C before so we're going to increase our unique letters to three now and this also increases to one to say that we have one C okay so we have 1 a one b and one C inside of this and this string consists of three unique letters now we shall work on our sliding window so we start out at location 0 we see there's a c that's inside of our window so we say C minus a which is 2 we go to location two and we see there's a one there so there's a one there and uh we decrement to say that we have to account for the C that's inside the window so we decrement now since that became zero we know we just um fulfilled all the letters of some unique letter inside the window so what we did is we just fulfilled all the C's that we need so all the C's we need is in this window there's only one of them you know so all the C's that are inside this string are in this window so that's good so since we went down since when we decremented that since when we decremented this number it became a zero then we say we increase this match to one the match represents that we matched all the letters of some kind of letter we're interested in so in our case we matched all the C's so the match goes to one because what we're going to do is when the match ends up equaling the unique letters that means that we've matched everything inside of this string okay so now we are going to increase this window and the B entered the window so we say B minus a which is one so we go to here and we decrement and that just became a zero so we come to the match and increase this to two Okay and before we loop at the end of our for loop we're always going to check to see if the window end which is one right now if that is greater than or equal to the last index of this string is two so it's not okay and I'll explain why we do that when we run into this scenario where it is greater than or equal to it which is on the next go round okay so now in our for loop we're always increasing the window by one so we increase the window by one a entered the window so we go to location a here decrement that became a zero so we increase the match and now the Matched equals the unique letters so we have fulfilled all the letters that are inside of this so we found an anagram so what we're going to do in indexes is we're going to keep track of the window start so the window start is at location zero so we add that in there and then now the window end which is two is greater than or equal to the last index of this so last index of this is two and the last index of that is two when that happens we know we need to shrink our window so shrink when we have window end greater than or equal to p. length minus one okay so we shrink this window so C just left the window so we go to C which is going to be C - A which go to C which is going to be C - A which go to C which is going to be C - A which is 2 we see that it was a zero and we're about to increment it so it was a zero so we need to go to this matched and decrement the Matched because that's leaving the window and we're no longer going to have all the C's inside our window so we decrement that we increase this to one and um and then now um when we Loop then we increase our window size so e entered the window but that's not part of anything and this window end which is three is greater than or equal to two so shrink that b just left the window so we go to the B which is location one that is a zero so we decrement our matched and we increment this and we cow the window B just entered the window so we go to B and we decrement that became a zero so now we're going to increment our matched and our window end is greater than or equal to P do length minus one so we're going to shrink this window a just left the window so we go to a it was a zero so we're going to decrement this matched and so we increment this to one and then we grow the window a just entered the window so we go to a which is one so we decrement that just became a zero so we increment our matched and window end is this is true so we shrink this okay and then we increase this P just B just entered the window so we go to B which is location one it was a zero and um we now we're decrementing it so it's a negative one we got more than we need in there this is true so we shrink it B just left the window so we go here we increment and then we grow ages enter the window so we go to a and we decrement and then we shrink this window a just left the window so we increment and then we grow C just entered the window so we go to C and we decrement that just became a zero so then we increment our matched which is three now matched equals unique letters so we append the start window start to this array which is six and then this is true so we shrink this B just left the window so we go to B decrement denter the window okay and then we're done um and this is the answer 06 okay so let's go code this up so we need to have a list of indexes this is going to keep track of our answer this is what we return okay and then the other thing we needed was um keep track of the frequency counts which is the English alphab alphabet and then we also wanted like the unique letters okay and then we're going to um go ahead and populate the frequency count and also update the unique letters so go like this and this is coming from the P string okay so we're going to say we're going to create this index so C minus a and then we're going to say if the frequency counts of the index equals zero then we've never seen this before and we'll increment the unique letters okay and then we increment the count of that letter in the array then we're going to make a matched variable and then we'll do our sliding window ah and we're going over the S string okay and then we're going to get our end index and subtract off the a to convert it to the index and then we will um decrement from the frequency counts that the end index and then if that became zero then we increment our matched and if our match ends up equaling the unique letters then we have found an answer and we incre we put our yeah Windows start in here okay and then if our window end is greater than or equal to the P do length minus one then we KN know we need to shrink the window so we'll calculate our start index which is going to be s. Char at Windows start minus a and we'll check to see if that is um check to see if that is currently zero so if it's currently zero then we know we need to reduce our matched because we're about to cuz that letter is leaving the window so we got to account for that and we count for that by increasing the number of letters that we got to find again in the window okay so that shrunk it that we got the start index we checked to see if it was Zero if it was we do their matched and we incremented that looks good let's run that okay good okay great so we have the answer there and then I also wrote this in um python here oh yeah one more thing let's go back over here you know what I could have did it was I could have said that scenario we talked about where the P do length if that's greater than the S do length then we'll just return false so before I run that check it out we're at 68 we beat 68 and then after I add that in there we'll be faster we will have compile we have a compile ER so uh super fast because it crashed and didn't work all right so it ends up being a little bit faster instead of 68 we have 7493 all right so then we'll go to the um python code all right so same thing here so we did that and it's just all the same code just in the python syntax uh the only things to note is that in Python you have to use the or function to convert from the character to the decimal value this is initializing 26 um a list size 26 all populated with zeros I'll give you some time to look at this code I'm going to scroll down now you can pause the video if you want to look at it longer okay so there we have it all right so if you are enjoying these videos please subscribe if you have not had a chance to Please Subscribe because that lets me know that you want me to make more of these videos and when I see that subscription count go up then I say I will make more of these videos also if you like this video go ahead and like it CU then that will mean more people will see it in their search in YouTube and then more people will subscribe and then I just get more motivated to make more videos all right well thanks have a good rest of your day
|
Find All Anagrams in a String
|
find-all-anagrams-in-a-string
|
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
242,567
|
114 |
hey everybody this is larry this is day uh was it 27 of the leeco day challenge wow my loading is a little bit slow today hit the like button hit the subscribe button join me on discord let me know what you think about this farm and yeah hit every bun uh okay so today's problem is flatten binary tree to link less okay uh let's see is it moisture so we want to do it in all one extra space um if we don't do it in all one extra space it's you know this is just regular like if you want to do in linear space then you would just do a victory a pre-order traversal put it victory a pre-order traversal put it victory a pre-order traversal put it into um uh putting into like a list a literal or like a wait list and then just iterate through it and then connect everything together right so that would be pretty straightforward and you could do that in i would expect people to do it in a couple of minutes with enough practice of course if you haven't practiced then it's gonna be a little bit harder um can i do an over one extra space i think that depends on the invariance and i don't think that i might have to think about a little bit so i'm thinking about the extra one space otherwise this is pretty straightforward um at least for me practice makes perfect i suppose okay so then let's see right so let's say we start at the root node on and then what happens well we only go to the left and we want to set the right to the left right is that true kind of maybe i mean i don't know if it generalizes but let's uh okay maybe i'll just use a drawing thing instead of using ascii art today so okay so let's uh let me give me a second you can get it pull it up okay and now okay so let's say i have um because the hard part about these problems and it's similar to who this is a little big similar to uh the ling list problems that you might have i guess we only need the left side um similar to the linguist problem that you may see is that when you change a pointer um with respect to like what does the left and the right point at when you change those references then you have to make sure that the invariant that you're thinking in your mind is still true and also that there may be multiple steps to keep to make sure that the variant is true so i'm trying to think for it maybe a little bit slower today but you know trying to do the right thing for once hopefully that's good so here let's say we have one right so okay we have to know that's one that's good and then we want to connect this to two i mean obviously but how do we do this right we go to the left uh okay so then i um okay maybe another way i can phrase this is okay so let's say we have one right so we want to go next and in fact we want to go this entire subtree next that means that we don't go this entire subtree because it's pre-order before subtree because it's pre-order before subtree because it's pre-order before the five right that means that maybe thinking about it backwards we can say this so then now we store the five somewhere because this is the old pointing to the right we store it and then we go okay let's do all of the left stuff first before it goes to five right and then now here um so then now the process is one and then it you know maybe some way of doing it we have to figure out how to do an r1 and that's not trivial uh of the five after that and we and then while this happens so we will go recursively almost now but but is that going to be cons oh well um yeah i don't know that's going to be constant extra space if we do it functionally so anyway so then this goes to so now after doing the five we go okay this is the two right maybe we can play around some pointers this way so now maybe another way of thinking about it and this is what i would sketch on my paper pad so i'm just thinking at full let's say web one right now we have two three four this is before we modify these strings and then the five what do we still have a five folding around and we want to connect them right because we want us we have to be able to store only linear amount of these and you cannot uh oh sorry a constant amount of these extra nodes in a good way right so we just if we gotta just did a modification here i don't know that's good enough and also this five will be five six say but how do we do it how do we keep tr like how do we know which one to go oh maybe the other way is just doing it the opposite way meaning getting the last notes first can i do that by going to the right side what i mean by that is that if we go down the two's right side then we'll connect the four to the five and then here going back now processing the two because it has a left now we go one two we put the no we go left we go to the left most right column and then connect it to the floor is that true is that a principle so then now here i'm trying to think whether this makes sense but i'm going to articulate it one more time because i think a little this stuff is in my head but is that we get the right most component of the left and then we connect it to the right component because okay so then the idea here is i've drew way too much on the screen so it's a little bit confusing to follow and i apologize because again if you're new to this which some of you might be i'm doing this as a problem solving this isn't i mean hopefully i'm explaining it well as well but some of it is going to be like if you give me this problem in an interview this is what you're going to get and it's not necessarily a perfect explanation because not every time i'm going to be perfect immediately knowing the answer i don't know the answer to this one i don't know about these conditions so but the idea is that for each node we connect the right component with the left the rightmost of the left component and the reason why we can do that is because which in a linked list order in a pre-order in a pre-order in a pre-order the note that is right before so we process you know current left right so that means that the rightmost of the left component is going to be right before the right component okay i think that sounds right let me know in the comments or discord if the explanation's a little bit off um yeah i think the idea here is just to get um you know i always think about it backwards oh sorry i got some stuff in my eye but basically we're going to the left okay so yeah let's take this um and as a result let me think make sure that this is correct and then after we did that then we now we could go to the next node because now we finish processing the pre node now we by going to the next node uh effectively and let me bring back it up just for one more second here for example um i'm gonna change the color real quickly um when we're processing one let's say we already move all this other stuff right um once we move all this other stuff then now we can go to the right node and then process this because what we've done now is just finish processing this node and then okay maybe i think that's like i could i don't know if i have a i don't know if it's a strict proof it is an invariant that we have kept so we'll see right so current is equal to root right so now while current is not none what are we doing right as we set we go as we said we go okay the right note is equal to current.right is equal to current.right is equal to current.right and then the and then now we want to get the right most left node or rightmost on the left side of the subtree right because the region and again this is so that we know that this is the node that process right before the right node so then here we go where we're naming is hard but uh left right maybe quite a terrible name to be honest does it go to current.left um yeah i'm just thinking about the edge cases is if left right is none then um then yeah then actually then we're good with continuing right i want to say continue but that would just be infinite loop so um we don't have a left note so we're done here so then here we just want to increment maybe this is fine got right and then else so that means that there is a left right note then we do let while left right dot right is not none go left right is equal to left right dot right so now we're going to we went to the left and then we go to the right most element um that has is that true wait hmm well it is i'm trying to think about edge cases still and what if i have so i'm so the case i'm thinking about and i'm going to draw it out for y'all sorry let me put bring it back up and again this is new to me so yeah so the case that i'm thinking about is something like let me bring it back to black there's something like okay so let's say you have a one node you have you know whatever the numbers don't really matter right so you have these notes and then now let's say you want to get let's say i have this and then uh something to 11 and here right now here do we want this node or do we this would be the right most node but i think this is the last node right so actually i was wrong about saying that it is the rightmost node i'm just thinking about edge cases but basically you want to get the node that is the last node that you process and then actually do the analysis which you have to think about so the last note you process is not the rightmost node so you don't just keep going right it is the node in which in fact you know let's say this node is uh i don't know a right oops in fact this node b let's just say and this is c b is processed after a so we is so we want to we keep on going to deepest so we're almost doing a pre-order so we're almost doing a pre-order so we're almost doing a pre-order traversal but in a reverse way of finding the right first and then the left second and then the current node okay like a reverse pre-order so like a reverse pre-order so like a reverse pre-order so uh like a post order kind of but i know post already has another order but um okay so maybe this isn't quite right okay now i'm looking at the code again so let me get rid of this but yeah this is a tricky analysis right so okay so this is wrong uh maybe we'll find the um find the last note to be processed on the left i think that's a good invariant to do and then whatever we're doing we should um abide by that even though my original assumption is that i assumed that the rightmost node was the last node to be processed but that's not true right so yeah so now we have to think about it again um last note is you go to current.left if last note is you go to current.left if last note is you go to current.left if the last note is not i mean this part is true um so then we're done here and then oh i forgot to continue otherwise it's just weird okay so then now what happens right so um while so that means that effectively what we always want is going to be a leaf note right so while last dot left is not none and the last dot left is not oh it's not none right because basically the last note to be processed has to be a leaf node in a post or in a pre-order a leaf node in a post or in a pre-order a leaf node in a post or in a pre-order situation because otherwise you just keep on going left no matter what so okay so then here we go okay if this is not a leaf node then if last.right is not none then last then if last.right is not none then last then if last.right is not none then last is equal to last.right is equal to last.right is equal to last.right else last is you go to last.left last is you go to last.left last is you go to last.left right and then now that we find the last leaf node then we can do last okay current. right is to go to um okay so that's one wait hang on so last that right is equal to um the right the previous right and then the current dot right is you go to the previous current dot left and then current dot left is you go to nut i think this is right and then we move kernels to go to turn going down right to move to the next frame um okay let's see if this is right and then we'll see if okay so this is right so far let's draw the example that i had which is kind of hard to think about hang on so one is the root note okay so i could do it this way and then two maybe four five the three has none and then maybe six none yep okay six none and then seven no and then eight nine maybe i don't know if that draws oh yeah wait i put something like that okay yeah all right that's one that real quick because then ideally nine is the last number before the three and that is correct okay um so then the question is now is it fast enough right so a naive reading of this is going to be linear time oh sorry um n square because this these nodes get processed and for each node that is processed we do well we don't do it that first search though right but we do like something that's height of the left tree so yeah so this is going to be and square time so we have to think about how to optimize this a little bit or at least maybe revert it i think the idea is right and it's good that we have something to build off but it may be too slow even though it's all one extra space but you know i'd rather have all of end time and of and space so okay so let's go back to the drawing board a little bit and in the in terms of just thinking about why this is no bueno like what is the bad case right the bad case and i'm going to raise the top now because i'm just the bad case would be something like the bad case now would be something like okay so literally every ring to the left except for one extra note and then now after one iteration you would have something like to do it and then we get to we do the entire elevation uh to the left side and then it goes to basically this and then this node right because we connect the last node here and then oops and then the next one we don't have a right node so okay i think one optimization that we can do which is clear is that because now this node doesn't have a white node right that means that we can skip this stuff but is that enough because then now we have to construct another case where this is you know which is fine but there's a couple of okay let me think about this for a second um because now let's say okay so here actually we can just do a skip of you know if there's no white node then we just move everything to left to the right and we don't have to you know do the processing right but that said what if we do something like this okay let me erase this real quick again what if the input now is instead you know something like this then in this case we would actually on the def or on the search we would the last note is actually this node right so then we don't even have to worry about this because the last note before the thing would but then now this node using a different gun this node would actually be here right and then now this is very tough to think about so i'm just trying so now i think my solution worked but i'm trying to think about a more definitive way of saying that it is linear time in terms of the processing right and this is going to use amortized analysis so it's a little bit trickier to say but i think it because okay so i think now let's okay yeah so let's go back to the beginning tree first of all i think here another way of saying this is that given that there is a node here right how do you um process the right side right and here you can think about instead of nodes you can think about it instead uh in terms of edges and in these edges you know this is the top one maybe you know maybe we can just ex um just we always if whenever there's a node on the right side we always process this but we're getting rid of it next turn anyway so it should be okay but then here once we reach a node and once there are two thingies left and right well what happens um if we go right then we're saying that can i construct the worst case let me think about this so then here we can say maybe we can do another one here right but then it would go dot all the way through but then when we process this node we don't have to process it we don't have to process anything to the left so nothing maybe that's one way to say it huh because i'm trying to think about the right way to say this node we can only process this node once in terms of it being on the left side because every time after this it will um there's no white node anymore right if it has the right note then by definition uh everything on the left would not get processed the first time so and if it doesn't then that's when everyone on the left gets processed is that true though let me think because now let's say we move everything to the okay so now this moves everything to the left and then now we have a node here right we move this node here and then what happens and then on the next node well we don't process the right because maybe that's the way to go about it because let's say this is a little bit lower right because we don't process this node this will never be on the left side again because after processing but i can generalize it right because this will be on the left side again kind of after we move it to the right but then here if there is a for okay so for here there are two cases one is if its parent has a right if it has if the parent has a right then it would get processed and then everything to the right of it would be a sub tree and therefore it would have no left or no parent otherwise man this is hard to analyze i think the amortization is correct and that each node can only be processed once um but i'm not gonna lie i haven't i have trouble explaining this um even though i feel like it's right i guess the other thing we can do is just do a lot of random cases and us analyze like literally but that's maybe too hardcore i'm just gonna give a quick submit and then see what happens oh well what happens is that i forgot some cases uh i was too i spent too long uh what is this visualize one two three so oh yeah i forgot to put in the case that we said we would which is that um yeah if uh if there's no notes on the left but if there's no node on the right then we also um why is this down so current right is it going to come left and that is not that should still be okay and then the last one will be i mean this is fine the last node is empty anyway right and current is good why did i why is that wrong i did forget one case though so it would time out anyway to be honest because that's the things that we were talking about where um if current dot let me just fix anyway if current.rate is none current.rate is none current.rate is none then we just do current.left then we just do current.left then we just do current.left oh sorry don't turn that right at zerocoin.left and then we continue um right did i mess that up no i think this is okay oh and we have to set kern that left this none um okay maybe that so that fixed it why did that fixed it did i just forget huh i did forget i mean i was talking about we were talking about that case but then i just forgot to actually write it out way sloppy well some of it is that i'm talking to camera because i just lost track of it um why was that wrong before though because there's no numbing to the right so then now it moves to two to the left or to the right and then after that as i mean like this should work without this code though right it just oh because the left side doesn't have any last but that should be oh because the last is none now then we just move to the next one is that true what am i doing i'm just trying so there's this case we move to two to the three how did that get rid of the three i'm just curious where my thing originally was wrong because i thought this was full disclosure is that i thought this was for optimization purposes but without this is wrong i'm trying to figure out why like so focus on this yeah let's check let's see uh yeah so we process the onenote it looks okay and then by the time we process the two node the three is gone so we process the one node uh okay last is equal to two so then here we find the three right this is gonna be distributed way right yeah the last note is two oh then this logic is wrong so that's why i'm debugging it i guess because this logic is wrong where the lat last is you go to current.left the lat last is you go to current.left the lat last is you go to current.left which is the two node right oh this should be an or okay that is a bad typo actually but i'm glad that i caught it now versus you know we would have to catch it anyway because this code is done for an optimization purposes so that it ensures the amortization is correct but that's a bad typo i didn't mean it to be that but okay and we're getting the print statement the easiest optimization getting rid of print statements um all right let's try again okay yeah and we can also let me try again without this optimization because then i think that actually is really bad because it should still work but then it should be n square maybe not okay then i have no idea to be honest i mean i feel like this is n squared the way that i did it without this optimization but apparently didn't do anything with respect to the test cases um i guess i'm just walking the analysis in general but which is possible as well no because if i have something like that a linked list we get the last out of it and then the next time yeah because this i don't know why this is slower actually that's really weird because if current.rate is none then yeah because then we do all this work yeah i don't know what to tell you i uh maybe today is just a bad analysis day i feel like the idea is correct um but you know it's right child points to the next i'll appear yeah i mean we knew that i don't know so that means that you know the last element here points to the right which is fine so basically another way of thinking about is that we chop off the right side we put it into the last thing and then we move the leftover i'm still trying to think about how to explain this as a linear what i how did i do it last time anyway typo decide i guess i just did the pre-order thing i guess i just did the pre-order thing i guess i just did the pre-order thing and this is just as fast so maybe or faster even but um just trying to visualize this like finding this note right is that always going to be true that because then now let's say we have yeah because the case that i'm trying to think about and maybe i'm going to give up soon on the explanation is something like you know let's so let's say i have something like and then just like you know a lot of notes here right and then let's say this node right so then the first thing you would do is like i said you chop off the right and then put it here under the last note and then now let's say we're here right here if you don't do the speed up trick that we said we will look at the last note anyway again oh maybe there is an optimization here now because it could have been that the last notice here and then in that case you would have to chop it up and put it in the left anyway um well i mean there is an optimization but maybe not the one that i think of but then you still have to go to the last note to the left right which is this one that we've just visited but that's besides the point and then here you will do it again so that's what my if statement was trying to do and then here you're already gucci well you would move this to here but that's you know you just look at the left most thing here so then this goes to here but we never visited these trees to begin with so it's fine i don't have a proof for you friends uh not today maybe i'm just a little bit tired but i'm i feel like i'm missing some parts of this so it works apparently so yeah anyway that's all i have this is a long video i gotta take a break uh stay good stay healthy to good mental health i'll see y'all later and take care bye oh and also i guess if you do have a better explanation let me know in the comments below uh yeah all right bye-bye-bye-bye uh i actually have an alternate uh i know that i said goodbye and i came back but i actually and if you are watching this let me know in the comments so map props to you uh my mic and to prove that you are up to here let me know if you can watch the movie nope by jordan peele i'm actually hoping to watch it soon but keep on being too tired lately but in any case um i think i there is another way to do this problem which i think i did it the weird way but and as a result the proof is harder even though i think they're the same complexity and the thing that i'm talking about is that instead of doing like instead of trying to get the note before what i can do actually is convert it to the right most node right and let me uh and i think that's the thing that i was doing earlier but then i kind of thought to myself and i couldn't prove it as easily right and what i mean by that is let me draw it out again um the idea here now instead of getting the previous note every time what we can do oops what we can do instead is just do it to the right the left notes right most note what i'm what do i mean by that right let's say we have something like this right um and yeah and maybe even here we have left notes but and then now i'm gonna change the color real quickly uh this right subtree right um that will process and here as if previously our original algorithm we would have set something like that let's just move it to here right and it makes sense because this is the last node that is processed but what if instead we move it to the rightmost node which is here well the thing about moving it here right and the reason why this is just as good is because when we process this node what are we doing what are we going to do right when we move and by definition this node does not have a right node but when we do move it here by definition we're going to do it again which is then now it goes to the left most might know so that means that this thing this entire substrate will move to here right next and also by definition when we process this that this thing will move again to here right and so until this knows until we find a node that doesn't have a left subtree right and this way um so the two things right one is that well we can code this so no problem and the reason why and you can see that these are equivalent we're just doing it skipping steps right because now um yeah so i hope that it makes sense that these are equivalent because now you're just skipping steps right but now the amortization math is easier to show why because that means that for each node that we're processing meaning and by that i mean um say this one initially but eventually this one and so forth right dot well we this node can only be processed once right oh sorry maybe another way of saying it this node again can only be on the rightmost path once right because after we process this as the rightmost path this goes to a lot of it goes to the left right so that means that in um so that this path now will swing to the left so therefore if we're going down this path how did that happen if we're going down this path it means that it is now on the left side afterwards oh sorry is that on the it was on the left side but now it's going to be on the right side and next attempt and therefore this edge i'm trying to bring another color therefore this edge will only be processed twice once on the initial you know from the top going to the right and then only once on the left side so because of that this edge will only be processed twice we can now prove that everything is um linear and because this is equivalent to my code it has the equivalent of because you could do it in one transformation that this is gonna have the same complexity i think that's basically the proof maybe um even though my code is much harder but then now we can also write this in what um what i did was i what i don't i was going to write in the first time but apparently the equivalent we just had to prove it which is that while last.right is not which is that while last.right is not which is that while last.right is not none then yeah and then now last and then now this should work as well if my understanding is correct um and uh was it one two no three something like that i think that was the case i was wrong on yeah okay let's give it a submit see if that works faster it's definitely more com maybe some of this measurement is because it's so fast that it's just random fluctuation but at least now as you can see the code is much easier and we have a proof of why this code is equivalent than the other one it's just that instead of moving it one by one my other code just move it all one together and now because of the same structure you could see the amortization map easier at least for me maybe you could have done it the other way anyway so this is gonna be linear time constant space i think i cut out a little bit earlier on the last video anyway so yeah um glad i finally resolved it happily so yeah let me know what you think stay good stay healthy take your mental health i'll see y'all later and take care bye
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
232 |
Hello gas message Samiksha Agarwal welcome tu freaks channel made for you made by today late good problem nowadays name of late good problem is implement why using tax is easy level problem and trust me is very simple problem there is nothing to worry about So first of all let's see what is 'Apne' and 'Apne' in the question and what is 'Apne' and 'Apne' in the question and what is 'Apne' and 'Apne' in the question and what is this question trying to say to itself. So in this question 'Na' has said 'Apne' that ' So in this question 'Na' has said 'Apne' that ' So in this question 'Na' has said 'Apne' that ' Apne' is tightly implemented with the help of some functionalities like Apne' is tightly implemented with the help of some functionalities like Apne' is tightly implemented with the help of some functionalities like Pushp Pop and Empty Statics. To do this and to tell its implementation, how that implementation will be done, this is such a simple question, to answer this question, first of all we understand what sex is and how it works, then what is our Just like there are simple lines, then it happens to the one in which one's own people are standing, similarly it happens that if the person comes first, then only the first person will get the first service and then while traveling like this, he will come to the starting point and then he will leave the K. Will give, then after that you will leave three, meaning the person who has come first in why, will be the first out, okay, here the van was the first in, the van is the first out, like in any of your lines. Just like you are standing in the queue of any bank, if you stand first then you will be the first to take the people in the service and then you will be the first one out and what happens inside the stack like if you take any of your books. Take the stock man, like if you have kept the book of Physics first, then Chemistry, and then Maths, then you will have to pick up the book of Chemistry, then you will have to pick up the book of Physics, is it okay, Physics was the first in, that means it was first in. He is getting last out or you can say that this match took place on the last day but he is getting first out, okay so both of them have the basic functionalities that the one who goes in first comes out last and In that it is the reverse that the one who has gone in first will be out first, that is, he will come out first. Okay, so why will we function on that? Now let us take our 123 example that first one was made, then you went out, then 3 went out or 45. Let's take a bigger example, okay, first of all the van has to go because inside, okay, so why did I include the van, then you have to go, so why did I include you, okay, we will give our party, similarly, everything will continue like this. Empty tapan will say that whenever your MP3 is ok because elements is also present in track van, ok now let's check its code, first of all what should we do for the court, see if we have got posh element, that means our If any teacher wants to push Elements are present and here let's say that if you have placed 4 then what will you do? Now if you have to delete any element then you will not do that. You have placed 4 at the top. It is okay because it was the last day of Fourth, so if you are like this. Will we say that if Apna Four is placed in S2, then what will happen to Apna? Four will come on top. Till then Apna was in the last place, so Apna cannot be first. It has become It has become It has become empty, then we will put Apna Four inside it, whatever is present Apna. We will insert it and then keep deleting from it. Okay, we have to delete the top elements only. If it becomes empty, then in its top, as per the science studied, Tapan will first insert six and then four and then remove 6. Then Back to Alexander, we don't do empty and then if we were to call the empty function, we would see if the stock is empty and the stock is empty because the tag is created as the element is present in both of them, then we would see that if both It means that your key is empty, it is ok, and then if you give it will return false, ok, let's see after submitting, yes, it is getting submitted, it means it is a completely accepted solution, thank you so much.
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
1,026 |
hey guys how's everything going this is Jay sir he's not really good at he's not very good at algorithm and I'm recording this video to prepare my interview from Facebook in June which is exactly like one month from now so actually not that time not that much time is enough so I'm trying to do as much practice as I can and this video is about 102 6 on each code maximal difference between node and ancestor let's take a look at this quick description first given the roots of a binary tree we find the maximum value of V for which there exist different nodes a and B where V equals the absolute value of the difference between the Val and a is an ancestor of B well for the example here so basically for every node on the same root us are on the same path may generate a new value array a three five eight one seven three six three eight six two a seven one eight four two something like this at maximum is 7 well for this binary tree I think the first idea coming to my mind is that we can like we can use recursion so let's first analyze the basic form like there is only a 3 10 of course for this case there will be only two values right 8 3 5 and 8 10 - now let's suppose we 8 3 5 and 8 10 - now let's suppose we 8 3 5 and 8 10 - now let's suppose we add a new node like one here what change is the what changes the situation how the problem is changes when a new node is added so when one is added it actually has two possibilities or feed the value right one is one against three is just two and one is against eight seven so you see that the two values actually if we know that a3 is more than 8 and it's 3 is bigger than 1 actually we don't need to calculate the calculate 2 1 3 because it's definitely well gotta be smaller than one against 8 right and of course if a is like - right and of course if a is like - right and of course if a is like - or something and if here is like 5 3 is smaller than 1 well that might my sense sound different but the idea is saying if actually for one we actually just pass it with the maximum the largest number and it will cover all the cases that notes bigger than 1 suppose there is 5 or 7 it doesn't matter because it is this largest one so only we only check 8 with a 1 with 8 and of course it's another case that of the numbers are smaller than the value so besides the largest number we actually can pass both the largest one and the smallest one so that will cover all the cases right yeah so cool we can use a recursion to do that okay so the maximum because these absolute value the max will be we can set it to 0 to default to 0 oh I use of our God and then we can you create a recursion method called node walk the parameters first will be note and next one is max and note max minimum right okay let's say we pass with Max and minimum if this what we do of course we just to calculate the max a two V's from Max mean and the kirino's Val and update the result right quite simple so the result would be a result Oh if the note itself is new or we just return right do nothing and we update the result means math.max the first the result means math.max the first the result means math.max the first math.abs max - no - pow next one is mass math.abs max - no - pow next one is mass math.abs max - no - pow next one is mass abs mean nice note well this is a result hmm right of course and now we can have it we can start work on the children of this node and the gnu/linux I think ok I can just use one gnu/linux I think ok I can just use one gnu/linux I think ok I can just use one niner walk no it left with max now the max would be max note about right update to the backs updates the mean obviously this will be called a gang on right note so we catch it new max equals this new mean cause this is new max okay and now we walk from the root is the route might be empty we're said that number of nodes in the tree is between two so it cannot be empty for what route Lutz what's the maximum max itself right because it's true there will be no as no note on your a sister so the route would be wow the minimum yeah it's it doesn't matter okay I think we're done here let's try to review our algorithm let's try to do it bug free with one pass okay so for these this kind of input or first walk to eight and a maximum itself and the result would be this will be zero it will be also be zero and as a result will be oh yeah we find a bug we hit update the backs and we find the numerix it's so itself and the minimum okay it's still itself and then we walk to the left like there will be new eight the left with three now we go to the left node maximum is 8 - it's five three left node maximum is 8 - it's five three left node maximum is 8 - it's five three five right so minimum five okay so we updated results to five and the new max would be eight minimum would be three so now we go to one and the maximum would be three eight minimum 3 so we update it to seven the result and the new max would be eight the new minimum will be one now we go to the nor write that note one new is read empty is a rate return yeah I think this would work what it's not working what really it's not working I like a three he's just like this mm-hmm mm-hmm mm-hmm really Wow the increase this I want to give up an engineering okay which I ate so yeah Oh allow me to update the result eight why become so 10 still it's a eight now we got he 14 we got 10 max means 10 minimum is 8 so we mmm subtract the node Val and they become 10 why note about is hmm you see node values less - right so max it should be values less - right so max it should be values less - right so max it should be mm-hmm is it this is not numbered not Val and type of node well ring its number Oh so note value is 10 and Marcus is eight minimum is 8 the result would be max this would be 2 this would be 8 so it's still 8 oh yeah oh there's no problem here and we got 14 the max will be 10 uh-huh and the max will be 10 uh-huh and the max will be 10 uh-huh and the minimum will be 8 so the result will be 10 y maximum max 4 & 6 & 8 so it still 10 y maximum max 4 & 6 & 8 so it still 10 y maximum max 4 & 6 & 8 so it still it should be theirs but it's weird allow me to lock you there something typos a typo or something okay so we got four and six mm-hmm Max's Max is ten god sorry this should work cool ah at last I didn't do it bug free God we're accepted but not that fast let's analyze the time and space complexity here for space-time you see complexity here for space-time you see complexity here for space-time you see that each time we just a traverse one note so time is obviously in the clock in OB go in space mm-hmm it's kinda in OB go in space mm-hmm it's kinda in OB go in space mm-hmm it's kinda seems like we don't use extra space so it's constant but there's a worst case of cost AK so worst case is we go in cool now let's try to improve it I think there is nothing we can really improve right the improvement is that we can reduce the space because this is typical you can't you see it's a typical tail recursion that we can rewrite it into iteration okay let's just try to you iteration wait BFS first okay so as we did just now with the recursion we need to pass on max main so for BFS for bsut BFS intuition we need to push the node together with the main max and then handle them for each round we add a new row here north to the stack or to the queue and as the ending identifier and do that over and over again and update results oh cool let's do it constant Q of course we just use a array here Wow q has tenements got I need to put pull it in cube push good an or net head Wow head equals Q shift so for each round so this means each round use know as an ending identifier to do it around by oh I think there's no need to do round yeah there's need to do the round problem because there's not no there's no information attached to the round right we just in the past stacked up max and the main so sorry they're not there's no need to do this so I'll say let head while head equals this I got pushed a max on me rich Wow cost no man mean who's rich right I know head just as what we did here we'll update this copy the code here max note Val yeah this is the same new max it's a saying and we'd just rather than walk we push into the queue this we push only if there is left hey sorry oh no left of course we do the same to if left no right I push a new right cool I think this will do try run the code yeah this might be better mmm it seems that it doesn't help so much well let's analyze the time and time complexity for time all the nodes will be Traverse for only one so it's a near time space we used a queue to store the call stack and the maximum is the half of the nodes right so it's o2 it's linear time it doesn't this doesn't change the time complexity actually change the time or space complexity actually well for these problem actually we can rewrite it into iteration with DFS right DFS iteration for DFS we will push to the end and yeah I will use us I'll use a cue push them in and handle them and push them in so it's a stack okay for DFS so I create first out criest create a stack root well roots Val has the main max I'll define the method called push so for the push method not only we push two three like a push three we will continue push Oh God I'll remove the initialization I push until all the left notes are in the steena stack Wow note stack push oh it's not possible here because ok it's ok I get it hmm Wow because I need to push the max and a mane also in a stack this method is not going to work anymore how can we do it well I think the cost of push will be switched to not push the notes but push the node max minimum right yeah and then the FS and then this way yeah cool and we and actually we need the logic here so the result will be we update it like this okay and then we will we update it and new max and new Ming is like this right and then if note if node left if there is left node we will continue push it so we push note left new max you mean so we would push a note actually there's no need to do the DFS brought DFS check right because we already checked it we already checked the data and there we don't need to do we check it back check it over again well anyway just like the practice of do tree traversal let's do it okay so now we push the first one right which is the roots good Wow good minimum for the results I think we don't need to do it now we push this huh and it means we need to Oh God it's actually 2 o'clock in the morning so my brain doesn't work very well we were pushed a node and Max and min man we push it and it would create a new one and push to all the node left node into the stack right and then we push the first one and then we start popping right so Wow I say lid top while top we pop whereas theories there is something in the stack while stuck I'm creating actually a stock application okay we pop the note we will handle the result right yeah so actually this will be reused this is the top and we can update result we separate the DFS in to push face and collect face this is a clock face so update it and this your work rendering what we do we will check because it's already popped we check if it has right now it or not if there's right node right we push node right mmm this is not very good I need to calculate the mean max again right first I'll copy the code like this no it's right new max you mean left is handle and we pop it and like this we pop it and push right in hmm it seems right but it's not that elegant new max a new name can we merge these two together when we push in a note if we keep track of this like a previous maximum it's my do right okay so actually this would be pre max create me we push the note for these case the new max actually we stack push a note proof max proof mean this works and then now we could push right way directly uh-huh could push right way directly uh-huh could push right way directly uh-huh it's not okay Wow it works I think this is not actually a good solution I think max is not defined who stop Max is now defined 71 here there's no max not a number mm-hmm not a number mm-hmm not a number mm-hmm stack we first we push all the nodes in and then update it push it in oh there is foul here my god mmm still not a number you pushed it in we get the top and then we find the max well we push those right in it hmm sorry I need to block top undefined stack is empty what we push the ah god my bed this valley I'll define ah yeah Oh zero Wow so we the first would be three four six seven this one right there's no one 3 4 6 7 8 10 14 13 that wears one what is gone we push the roots and then if no left we push the no left push console.log push no - Val I push eight console.log push no - Val I push eight console.log push no - Val I push eight and then push three with push sex there's no one you should push one right note left is node left push eight left is three and then we push ah God Wow I think I need to go to sleep so sorry for my mistakes guys okay for this case so actually for DFS it doesn't change that much for this problem and we will do a follow-up on problem and we will do a follow-up on problem and we will do a follow-up on tree traversal everything in the future videos hope you will please stay tuned and I hope there will become good news to tell you guys in June's interview and ok so that's all for this problem I'll see you next time 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 |
705 |
Watch this Hello everyone welcome to my channel today to of birth change any problem in design is decided so design is without using any in built in the festival of red tube specific sexual day function and value interview in to the sentence value return of the rebel remove This example subscribe content with to properties subscribe to subscribe this Video subscribe and subscribe apne hriday chest half reserve change airtel in the content for to return true and removing to checking contents for two years not always win 10 ki usse lexegi more operation bilva vriksha tuesday servi juice one of the mind will use this is the number of different subscribe 2100 subscribe thank you ne bullion are in the default everywhere you will fall so whenever i get any add call to let's add call to one will go to Inductive Call Thursday Remove Thursday E Will Just Override Life And Daily Key Services Will Update Key Updates To Forms Members Of Simply Solutions For Examination Of The One Should Declare The Winner Of The Difference Capacity Subscribe To The Scene Not Using Simple Solutions In Chief Of the earth is one time watch loot so how they can not optimized space complexity and also good increase time complexity of the match in wave 100 subscribe and more than 60 from this side will keep load factor and placid I am one of the load factor Late Se Left Loot Hai Na Also Be Gyan Nilgiri Ghaghare Of Mercury Using Simple As Modern Technology With The Help Of 1000 Subscribe Videocon A30 That Suited Purpose Will It Help And Values As Villain Do Divya The Amazing Are Values As Villain Do Divya The Amazing Are Values As Villain Do Divya The Amazing Are So Let's You A Message All Articles Edifice 2515 With Subscribe Thursday To The List Of This Is The Giver Hai To This Is Add Logic Service Available For Remote First Model Of The Match Lalit From The Indians Now Half Tent House And Acts And Visited Note Channel That Is Not Alone Will Treat All The Element Using the tractor over and compare is the item play list item any where is equal to our key effective will remove it from the list this is the time for this is the function similarly for the content will have that rio de em so let's be defined By its coordinates of teachers that from wicket so initial other office will cause it's bark at people should avoid that and some will guide you to cut off her but from B.Ed loot dad will read all element it is not done and will check Baikunthpur Difficult That on Thursday the elements on the pan which are used for increasing its revenue service 275 processes will go for 200 initial load factor which starts with appointed shift that and initial capacity was us thrust will also come to check for increasing its eyes should develop into the city Tha Is Causative AComment 202 Here Is The Implementation Is First Declare Dabg Using List Play List Of Cities Are Appointed Subscribe Like Subscribe That's The Power Of 31 But It Already Contains That Key Doing Nothing Simply Continue Subscribe 10 Cars To Loot 133 Capacity After Delivery Episodes TV Are Getting Old Into Gold From Creating A Bigger Size Are But Also To All Elements In To-Do List In The World That Was Interesting Threw He Didn't Know Life Is This Is Not Done Thru All Of The Year That's End Jack It's All James Like Mother Begusarai Journey To Do The A New Vakriya Singer New Hai Singh Approves Software This Is The Chief Marketing Simple Model Of The Egg Subscribe And Tap Medium Size The Software Bihari Mishra E Think What is the language and a great to the is obscene to our in this simple that and after effects for the remove them and will calculate given that you daily war episode and reduced from the Kwid Renault Kwid Thursday Daughter and all the elements in the Remove element to turn will remove hanging and reduce account development also remove them element member remove method implementation that in food content method this is like and similar to remove the chairs on requester that is equal to the department of Dhruv Diner Buckets After Change in Avoid Taxes Code members also accept such a place implementation Sudhir and point And subscribe The Amazing Custom appointed nodal person not enter this is the simply SIM not and dislocated curve they are not doing basic operation Water with a girl this thanks you
|
Design HashSet
|
design-hashset
|
Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` does not exist in the HashSet, do nothing.
**Example 1:**
**Input**
\[ "MyHashSet ", "add ", "add ", "contains ", "contains ", "add ", "contains ", "remove ", "contains "\]
\[\[\], \[1\], \[2\], \[1\], \[3\], \[2\], \[2\], \[2\], \[2\]\]
**Output**
\[null, null, null, true, false, null, true, null, false\]
**Explanation**
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = \[1\]
myHashSet.add(2); // set = \[1, 2\]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = \[1, 2\]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = \[1\]
myHashSet.contains(2); // return False, (already removed)
**Constraints:**
* `0 <= key <= 106`
* At most `104` calls will be made to `add`, `remove`, and `contains`.
| null | null |
Easy
| null |
394 |
hi guys hope you're doing great a today's question is the code string given an encoded string return its decoded string the encoding rule is K and then will be given in square brackets 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 no extra whitespace is square brackets are well form etcetera furthermore you may assume that the original data does not contain any digits and that digits are only for those repeat numbers K right for example there won't be an input like three a or two four okay so for example if this is the given string so three represents how many times the output string should have a like we have two if three and after that whatever the string is being represented in the square brackets needs to be written to our output string that many number of times okay so this is three a that's why we have a three times then this is 2 and B and C so we have BC two times right similarly if you see this so you have three times the whole of this and inside of that you have got any and then to see so first you'll have the inner string would be 8 CC which will be repeated thrice right that's why we have an ACC and similarly this one alright so I hope the question is clear this clearly is a question on strings we have some set of approaches we can take to solve questions on the strings please have a look pause the video and come back so I think the way we can solve this is simple traversal but of course the question amongst us to keep a track of the number of times a substring needs to be repeated and then we also need to maintain a final string right along with some I would say subset string which handles the problem at hand right so for example the final string or the final resultant string would be this but we will also need a string which will handle just this part of it just the 3/8 right so the way we need to the 3/8 right so the way we need to the 3/8 right so the way we need to solve this is by making use of some collections and in such cases stacks are always a good option where you need to reference whatever was the latest work that you have done till now and then use that to basically append the new part of work that you have done to it and then again put it on the top right so what we'll be doing is that we can we need to maintain two stacks maybe one for the integer and one for the strings the sub strings and then after that once because we know that the square bracket is only going to be used to embark the start and end of the string that needs to be repeated so whenever we encounter an opening bracket we will whatever string we have been building till now we will just dump it into a string stack right because that is what we have created till now and we'll take a fresh string which will be like null which will have nothing and then after that we will just character by character start appending these characters to that string and then when we see a closing bracket it means that whatever was the last number we had seen so for example it will come in handy in this case right so our integer stack would have three and on top of it will have two and when we encountered this closing bracket we pop two from that stack and we have see as our string so we will write C twice right and then because we want to append to it a would already be present as a part when we start appending this C to it and then finally when we move out of that we'll have three and we'll repeat this string thrice so that's how I think we will do it and I'll explain more as we go about the solution so yeah let's get started okay so as I said we need to two stats here right one would be storing the integers okay so which is called integer stack okay and another one which will be storing our string so let's just call a strange stuff SS okay now we'll just take a pointer which will point us through or move through the spring right each character which is the given string s so our representation so we'll just take call it pointer this to 0 and then we'll say well point 2 is less than s dot length right okay so our current character right so a current character is s dot character actor right so what we'll do is that first of all we'll check that is that a number right because we have been told that the numbers would be used only to represent the number of times and not will not be a part of the string right so we just check that if this is a digit right so if current is a digit then all right we need to form a number that the reason for doing this is because it might be possible that this is not just 3e it is 32 a right or it could even be 3 63,000 32 a right or it could even be 3 63,000 32 a right or it could even be 3 63,000 a right so we need to form the complete number by keeping on iterating or implementing these the pointer through the length of the string until we find a character which is not a digit right so what we will do is it's really simple we have initialized this with 0 and while a pointer or let's just say that while the whatever character we are getting is a digit right so we'll just say that s dot can at point-o okay so while this is can at point-o okay so while this is can at point-o okay so while this is whatever character is at the pointer is still a digit we want to continue right now we just say that the number is equal to number into 10 okay plus we want to okay so we just want to use this and since this is a character we want to convert it into a number so we'll just subtract the character 0 from it so that it gives the actual ASCII value which will be an integer and hence the number whatever it is or whatever the digit is right so we just do this and increment the pointer right so for example if the number if the string is something like let's say 32 a okay so any the number is zero and we get a three so what we will do is that zero into 10 that is zero plus three right after that when two comes in so the number is 3 so 3 into 10 gives us 30 plus 2 that gives us 32 right so that's how we form a number okay right and once this is done we want to push this to the stack the integer stack right so we'll just push the number to get you just an okay else now otherwise if this character is equal to an opening bracket right so we know that there are some specific actions related to the opening and closing bracket because we know that if I am seeing an opening bracket it is going to be starting a new string that I have to start recording somewhere right so what I do is that whatever spring I have been building till now would be pushed on to our spring stack so let's just say we are taking this result okay yep so what we do is that if we see this first of all let's just secure whatever we have been creating so we push that to it right after that we basically are refreshing it with to make it point like have nothing because we want to record all the new characters and then just increment the pointer all right so okay now otherwise if I am seeing a closing bracket okay so if I'm seeing a closing bracket then it means that I have a recorded string for example in 32 eight my result this re s string has got E right so now what I want to do is that I want to append to my final result right 32 times a right and I want to get over with this so what I will do is it has this create a string window and I'll initialize it with what I had pushed onto the string stack over here right so for example if we take this simple one so it for example it is e-e-e so I one so it for example it is e-e-e so I one so it for example it is e-e-e so I want to append this BC twice to the AAA string and that is what I had pushed over here so I'll just initialize it with that right so I'll just do a pop so my string builder is not starting with null it is starting with AAA string right okay now to this I'll append the result string but how many times so the count will get it from our integer stack right so I'll just pop that so these many times so we'll just use a simple for loop which will start from 1 and both till less than equal to count because it's the number of times you want to repeat result is count right I just increment this and we keep on a pending result to it yep okay so um all right once this is done we can just implement the pointer so we don't need to do anything to this right but we need to do one thing that we need to because in the next step when we know that after this it should if the string does not end it should be getting an integer right and it will go in this loop and then once when will it will get opening bracket whatever is this it will push it and the next repetition will be appended to this right so we always after we are done with this process we need to update it to the whole string that we have been creating till now right so what we will do is simply do right so now in this case for example this will have a because that is what we had started with right initialized as we will and then we added twice VC to it so this is what our result would have okay so fine and then is our last possibility that it could just be a character and in that case we have to do a really simple thing is that is just to add it to the result the character yep and then increment the pointer because if it's not an opening bracket if it's not a closing bracket if it's in order digit it means that we are traveling through one of these sub strings and all we have to do at that point is keep building the result so that when we encounter a closing bracket we use that result and append it to our larger string the number of times if needed needs to be appended okay so after all of this is done all we have to do is to return the result because it will contain here for example here this was ending so it should ideally contain our answer right so let's see that works okay enough okay yeah that works so the time complexity for this is o of n because we are roughly traveling the string just once and the space complexity is also o of n because we are using two stacks - how because we are using two stacks - how because we are using two stacks - how will not show the whole of the string but yeah the worst case time complexity would be off in that case as well so I hope this question really helps it is one complicated question and involves using a bit of a trick but if you learn this and develop approach these approaches new mind when you use a stack where and how to use a stringbuilder and how to append these so it would I think build a really good base so I hope you find this helpful if you do please like share and subscribe keep pouring and take it as
|
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
|
368 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem largest divisible subset I really like this problem we're given a set of distinct positive integers and we want to return the largest subset answer such that every pair of values satisfies this condition one of the numbers is a factor of the other that's pretty much all that this means cuz this is saying that if we have a pair of numbers like four and 2 four modded by 2 is equal to zero if we take the reverse of that if we took two moded by four it would end up being not zero it would end up being two the remainder of this would be two but they tell us we can arrange this in either way like if we have a pair of numbers we can either do it this way or that way if either of these ends up being equal to zero then it satisfies the condition so this is basically a glorified way of saying that one of the numbers is a factor of the other one number multiplied a certain amount of times can equal the other number this would also be a factor if we had 8 and 2 so 2 * 4 be a factor if we had 8 and 2 so 2 * 4 be a factor if we had 8 and 2 so 2 * 4 would be eight so this is the first key observation that you really need to make for this problem if you can't it's difficult to solve it once you recognize this though you realize that we can try to save ourselves having to do both of these wouldn't it be nice if we sorted the numbers kind of like they have in both of these examples if we sorted the input then as we are iterating over the numbers let's say 1 2 3 and we have two pointers I and J then we don't have to try both of these we can always take the bigger number three and try to mod it by the smaller number two and if this ends up being equal to zero then it satisfies the condition in this case it doesn't I think it'd be equal to one so it doesn't work so this will be easy for us and another thing to notice here is when they ask us for an answer what we have to guarantee for the output in this case let's say it's 1 2 4 and 8 what we have to guarantee is that every possible pair is divisible by the other but this second example kind of indicates that we don't necessarily need to do that what I'm saying is if we know that one is a factor of two in other words 2 modded by 1 is equal to zero and we also know that four modded by 2 is equal to Zer so 1 is a factor of two 2 is a factor of four do we really have to check that 4 moded by 1 is also equal to zero no we don't cuz that's just how math works now one is kind of a misleading example because one is a factor of everything but forget the one if two is a factor of four and four is a factor of eight then we know for sure that two is going to be a factor of eight I don't want to bore you with the math but if you're still not sure let me just show off my algebra skills if two is a factor of four we know for sure 2 * is a factor of four we know for sure 2 * is a factor of four we know for sure 2 * X is equal to 4 if we know 4 is a factor of 8 then we know for sure 4 * Y is of 8 then we know for sure 4 * Y is of 8 then we know for sure 4 * Y is equal to 8 and now we just take this part and replace it with the four over here and we would get 2 * x * Y is equal here and we would get 2 * x * Y is equal here and we would get 2 * x * Y is equal to 8 so basically what we found is that 2 multiplied by some integer is equal to 8 so this will help us eliminate some repeated work now we still kind of have to brute force it and let's look at an example to show you why consider this example let's say we look at the first pair of numbers as we naturally would we find two is divisible by 1 so this is our result so far now when we look at the next pair of numbers we don't need to compare five with one we just compare these two so we can in other words keep track of the previous number that we have added to our answer great but I'm trying to prove to you we can't be greedy here because what you're going to find is five is not divisible by two okay so now we're done is that the best result we could have possibly found no just because a pair of numbers is divisible doesn't mean we can't consider the alternative we can consider the alternative where we skip two and then we would find 1 and five it's also divisible so next we'd go to the next pair of values 5 and 15 this is also divisible next pair of values 45 5 ID 15 is going to be 3 also divisible this is the result this is the longest it's of length four we do have to brute force it and the way we're going to do that is kind of how I just showed you right now we're going to keep track of two variables the current index that we're at and a second variable called previous which is the previous number we added to our sequence technically we are allowed to skip the first number as well by the way so just keep that in mind because of that the way we can start our sequence is by starting the index at zero and having previous always be set to some default value one because one will always be a factor of any number because we know that every number in the sequence is going to be positive so this is just like a trick to make this work out it's not like a super important detail let me kind of show you what the tree would look like though starting at 01 we can consider where we include the one in the sequence our sequence would look like this then we would move to index one and what would the previous element be in the sequence it would be one still so we can also consider skipping this first one then our sequence would stay empty and we would move to index one and our previous element would still be considered one I know this part is kind of confusing it's a minor detail so please don't try to waste too much time on it and we know that this side is not going to lead us to the answer this side was basically to enumerate all possibilities where we don't include that but I won't draw this out because we already know it's not going to lead us to the answer for here though let me show you we can either include the two which our sequence would look like this 1 2 or we can skip the two our sequence would look like this it would stay at one and then we'd go to the next position at two where our previous element remains one on this side we'd move to index 2 but our previous element would now be two our previous element in the sequence let's continue down this path where we can include the five or skip the five and we know that this will end up leading us to the result so this is essentially the logic of the tree the base case of course is going to be when I reaches the end of the input and this is actually a perfectly valid way to code this up Brute forcing this it's obvious that the height of this tree is going to be n in the worst case and we have two branches each time complexity is going to be 2 the^ of n but we have two variables we 2 the^ of n but we have two variables we 2 the^ of n but we have two variables we can use these variables for caching so the size of our cache will be bounded by these two variables I is going to be the size of the input the number of possible values for previous is also going to be the size of the input so memory complexity is going to be n^2 and memory complexity is going to be n^2 and memory complexity is going to be n^2 and you can consider the time complexity as being N2 as well the reason is because on each recursive step we're not looping or anything we're just doing a constant operation we're doing a recursive call here and a recursive call there and we're caching the result of each recursive call there's just one catch if we're caching a list doesn't that mean the memory complexity is actually going to be n^2 times the size of that list to be n^2 times the size of that list to be n^2 times the size of that list which could get pretty inefficient n cubed right the answer is no and it's not easy to figure out I actually first coded up this solution and I was surprised that it passed so then I looked into it and I realized that the max size of a sequence is actually not going to be n in the worst case it's actually bounded by 32 that's a special number isn't it you might now be able to figure out why it's bounded by 32 without me even having to explain it but if you can't let me show you let's say we start at one then the next number would be two then the next number would be four 8 16 because we want the next number to always be a factor of the previous number so the easiest way to do that is to double them we could triple them as well but actually that will lead us to a smaller sequence because the limit of this sequence is going to be bounded by 2 to the power of 32 because that is roughly 4 billion first of all it'll overflow in most languages in Python it probably won't overflow but they do tell us that the max size of any element in the input is going to be I think roughly 2 billion or something like that so basically none of the sequences will ever be longer than 32 which is technically constant so that's how I'm getting this time and space complexity from so this is the code for that solution and there's a reason I'm not coding it up in front of you cuz I'm actually going to code up a different variation of this solution in just a second but I just wanted to give you this in case you wanted to pause the video or something you can see here's the logic where we skip the element here's the logic where we include the element and we try to maximize the length on each time we added caching here technically this does pass on leak code but there happens to be a better way there is a way for us to actually make it so that we don't need to pass two parameters in we can only pass a single parameter why would do that because the time complexity will still remain n s but the memory complexity will be Big O of n CU we won't need a cache of size n squ it'll be of n we just have one key for the cache now how do we do that variation of this solution well we're going to change the logic cache at I is going to be the longest sequence starting at I and including the number at I the way we're going to do that is basically instead of now having two variables and just making two decisions each time we're actually going to take one of those variables remove it and now we're going to have to actually make many decisions we're going to have to make a loop of decisions logically it's going to look like this we start at index I let's say we're at zero we know we have to include this element in our sequence so our sequence looks like this now we go through every possibility we can either go to index one we can go to index 2 we can go to index 3 and we want to find which one of these is going to lead us to the answer and the reason we're doing this is because we do have to consider skipping elements we have to consider maybe we skipped two elements maybe we ski three elements our previous solution did account for that and we have to make sure this solution does as well what we're going to find is that the sequence from here is just going to end up being two the sequence from here is going to end up being this whole sequence the sequence from here would have ended up being this and the sequence from here would have just ended up being this among all of those which one is the longest I think it was this one and that's the one that corresponds to this decision so among all of these we would find the maximum and then return it that's the idea recursively we'd probably do the same thing like from two we would consider going to three and we'd consider going to four which among these two is the longest probably the one from here so we'd find the maximum and you know that's kind of how the recursion will work so let's code up this variation of the solution because it's more memory efficient so let's code it up the first thing let's not forget we do need to sort the input it's not necessarily going to be sorted but this won't really affect the time complexity because it's going to be n^2 regardless now I'm going to be n^2 regardless now I'm going to be n^2 regardless now I'm going to write the recursive function we just take a single parameter I and the main base case is if we reach the end of the input we can return now we're not going to return zero because we know that this recursive function is meant to return a list so I'm going to return an empty list as the default value next let's consider every Poss ability well we know we're going to be starting at nums of I so we can initialize our result instead of being an empty list we know we're going to include this element regardless so let's go ahead and do that and we can write the return statement we know that's what we're going to return but we actually have to compute it so now is the part where we Loop we will consider every possibility we go through every decision so starting from I + 1 all the decision so starting from I + 1 all the decision so starting from I + 1 all the way until the end of the list we want to consider this but we have to make sure that this number is divisible we have to make sure nums of J is divisible by the current number nums of I otherwise it's not valid so we do this then we check DFS at J we recursively find the longest sequence starting at J so this will be assigned to Temp but since we know I can be included in that we can basically add this to the beginning of this list there's a way to do that with a method but the easiest way to do that in python at least is like this we can basically create a list with this element and then add these two lists together and you might be thinking isn't that big O of n no remember the max size of this is always going to be 32 and usually it's going to be pretty small it's probably going to be a lot less than that so this is usually going to be pretty efficient it's possible that this temp is greater the length of this temp is greater than the current result if that's the case let's reassign the result to Temp so this is The Brute Force solution I guess there's only one catch that I didn't go over if I call DFS from zero now it's probably not always going to give us the correct answer because DFS of zero would only calculate the longest sequence starting at zero but what if the longest sequence actually starts at a different number so for that reason we kind of have to do another loop out here so I have to say for I in range we have to consider every starting position so I'll just do line length of nums and I'm going to declare a result out here it's going to be an empty list that's what we're going to try to return and we're always going to set DFS to a temporary variable and then we'll always check if the length of temp is greater than the length of result then let's assign the result equal to Temp there is some duplicated code here there might be a better way to code this up but the idea here is that this is memorization but we are saving space compared to the previous solution that I showed you which in my opinion the previous solution was more simple looks like I forgot to actually add the caching so let's do that so we'll declare our cach up here and we'll add a second base case for the cache so if I is in cach let's I want to save space so I'm going to do this on the same line let's return cach at indexi I'm also going to move this to the same line I want all the code to fit on the screen so here lastly before we return let's just make sure to Cache the result so cache is going to be equal to result this is the entire code but actually it looks like there is one bug and I actually made this multiple times as I was trying to solve it myself when we check if this is divisible by the other we have to check that this is equal to zero not that it's non zero which is what we were doing before so sorry about that and there's one other error over here we're hardcoding this to always call DFS on zero we should probably change this to I again sorry about that now let's run the code and as you can see on the left it does work it's about as efficient as we can get it but if you're interested in seeing the tabulation solution I will go ahead and show you that now so we're going to basically apply the same idea here except we're going to do it without recursion I'm going to follow the same logic and for us to do that we are actually going to allocate some space equal to the size of the array so the cache is going to be of the same size I'm going to go ah ahead and just draw that down here our cache is going to represent the same thing as it did before and because of that I'm actually going to iterate in this array in reverse order rather than front to back because if we were to go front to back we'd have to change what this represents some people like doing that but I think it makes it harder to go from the recursive solution to the tabulation so I'll be doing it this way but again it's your preference so what this is going to mean is we're going to go and compute the longest starting here first because we know if we want to get the longest sequence that starts here and includes this value we have to go to all of the sub problems but how can we go to all of the sub problems if we haven't even computed them yet because we're not doing it recursively remember so for us to do that we have to first compute all these sub problems before we can fill in the value that goes here well the first sub problem is pretty easy 45 what's the longest sequence starting at this index it's just the list with 45 okay to compute this one we might need to look at the sub problem and starting here let's just compare the elements first let's just check that the longest sequence that starts here is valid for this guy for us to do that we have to check that this is divisible by this remember the array is sorted so we know the larger element is always on the right this is our J pointer this is our I pointer and these are divisible 15 is a factor of 45 so this works so now to fill in the value that goes here we create a list with 15 and then we take all elements that are in this list and add them to here as well so we would just take 45 and put it here and this would go in there I'm probably going to run out of space to put the actual list so sorry about that now just quickly repeating this five we're going to look at two sub problems now I'm going to redraw the pointers so our ey pointer would be here we're going to consider if J pointer was here check if these are divisible yeah they are so what we do is create an array with five take all the elements from this array atom here 1545 and now we have an array of three elements we would also consider the opposite case where J would actually be over here and this technically works as well so we could create an array with 5 and 45 but this array is obviously not longer so we uh keep the first array 5 15 and 45 at this point you probably get the idea two we're going to find that I is here and we would consider J for all of these but two is actually not a factor of any of these three numbers so two by itself is going to be the array that goes here and lastly we know what's going to happen when I is over here we're going to look at this and we're going to find that five is divisible by one and then we're going to take all three of these elements add it to one and then we'll have an array over here with four elements that will be the result and this is what I'm going to code up now so I'm actually going to leave the code here for the recursive solution because you'll see how easy it is to go from the recursive to the tabulation so I'm going to create that array that we were kind of looking at and I could do it this way where we have an empty array for every number in the input nums and so this would represent DP of I is going to be equal to the longest sequence that starts and includes I but just like how in the recursive solution we always initialized the result to the number itself a list with the number itself cuz we know it's always going to include that number we can apply the same logic up here we can always include n cuz if the sequence starts at I we know that at least the sequence will look like this of course it might be longer as well now I'm going to go in reverse order just like I talked about so for I in range length of nums and a trick in Python you can do to go in reverse order is actually just wrap this in a reversed call so this is a function as well and this will basically iterate over the indices in reverse order it's just a cleaner way to do it and then we want to consider all possibilities consider all sub problems so for J in range from I + 1 until the so for J in range from I + 1 until the so for J in range from I + 1 until the end of the list we will look at this and before we even consider the sequence let's just make sure that the numbers work out let's make sure nums of J is divisible by nums of I and let's not make the same mistake let's make sure this is equal to zero and so if that's the case let's create a temporary array kind of like we did in the sub problem over here I'm actually just going to copy and paste this because I want to show you how similar it is copy and paste instead of calling recursive function the sub problem is stored in DP up above so we can just say this we can actually change this from a function call to being a lookup in our DP array here we're going to do pretty much the same thing I've done down here except we're going to store the result in DP of I cuz that's what we're trying to compute that's the problem we're trying to compute here we were Computing the same problem but we stored it in result because that's what we were returning and we also stored it in the cache as well so we're kind of doing the same thing so DP of I is going to be equal to Temp if the length of temp is greater than the length of result otherwise let's set it equal to DP of I it'll stay the same in the otherwise case that's pretty much the entire code now we've computed all of the longest sequences starting at every single index but where does the result go the result doesn't necessarily start at the beginning DP of zero isn't always going to contain the result so to get around that we could just look through here and find the largest one or we could just maintain the longest one as we are building that array I'm going to choose the ladder so here I'm going to declare result it's an empty array that's what we're going to return so for us to do that let's populate it after we have found the longest one that goes in DP ofi and we know we found the longest after this whole Loop is finished out here we can say result is equal to DP of I if the length of DP of I is greater than the length of result otherwise let's leave it as is so this is the entire code unfortunately looks like I did have another typo I don't know why I took the length of result here I guess we were almost making it too similar to the recursive solution let's not forget that in this case in this context the result is actually DP of I so we only want to reassign this if temp is longer than it otherwise it stays the same sorry about the confusion now though we can run this code and you can see on the left that it's pretty much as efficient as the previous solution if you're preparing for coding interviews check out n code. thanks for watching and I'll see you soon
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
1,887 |
Vrat month mein sandeep android problem 1872 in this problem bichuran head and went to make all the elements equal to zero for diploma in operation what is that operation it is only white shoes largest army in the second largest element hindi are and you replace the largest and oldest And largest for example in this he behaves 513 What is the largest river is 5 second step three previous subscribe with three does it is 12313 Sudhir one operation subscribe to has so let's understand and completed 100 behave as possible to import network looking At 5.30 Initially World's looking At 5.30 Initially World's looking At 5.30 Initially World's Largest 15 to 0538 Victims 30 Next Largest S3 Limited This End Technologists One Should Replace Them With One Services 2share Notice Set The Choice of Words and Matter This Respective Which Will Do the Sense of Preserving The Electronic Cigarettes For no Veer 100 Researchgate one-wicket win For no Veer 100 Researchgate one-wicket win For no Veer 100 Researchgate one-wicket win 9 placements in three and technologists one replaced one 11058 operation doh and definition of you 3123 reach against and have replaced ST replace enemy Woodward 43351 and again the largest producer of revenue world championship improve wicket One one saw the observation here is later element like share it also from now we are back that ho no matter and r zooming day from this minute that access garlic wife always remember develop in operation where destroyed civilization from which largest bores access mobile shop no matter which Biopic Dushman Aur Dushman Evolves Into Equal Before Values In This Whole Forum Is Reduced And Will Prepare subscribe to The Amazing Subscribe Button More Next Week Computers So Let's Particular Person Computers A Yes To Kuch Bola Tha Main Tujhse Iss Disgusting Har 5400 Start Scholars' Lectures Given that the newly Scholars' Lectures Given that the newly Scholars' Lectures Given that the newly formed element of the sky which is greater than one 200 reached all these hotspot diabetes heart there springs in sequence solved the limits to at least RS equal and greater than 800 also sensitive is greater than one for all the value side of this from Her Vast And Always Will Always Be In This Particular One Should This Will Be Replaced By One At Some Point To Rate We Valued By All Eight Answer 5605 Operation Liquid Form Next Week Continue Games Video then subscribe to the Page if you liked The Video then subscribe to the Page Yesterday morning our in operations were targeted at $100 which problem na amla for record $100 which problem na amla for record $100 which problem na amla for record swift initially festival initially beginning of the first amazon quiz more reverse organized and smaller and cheaper and value on and which mince york and se zee entertainment enterprises that Diner for a particular person Dash Episode 238 Question Vihar Dahan Samiti Par Shak A Step Back Bachchan and
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
74 |
hey everyone welcome back and let's write some more neat code today so today let's solve search a 2d matrix and i really like this problem because it's not one of those problems that you need a fancy trick for you can actually solve this problem just by using logic so we are tasked with creating an efficient algorithm for searching for a single value in an m by n matrix the matrix has two properties in every single row the integers are sorted from left to right and the first integer of each row for example this 10 is always going to be greater than the last integer of the previous row so greater than this one so in other words we know that each row is sorted and then the next row is going to be greater than that so technically each value in total throughout the entire matrix is going to be in sorted order so that's pretty good in this example we were given a target 3 so if we search for the target we will find it right here so then we can return true that it does exist if it does not exist then we simply return false so how can we solve this problem the key word here is create an efficient algorithm what would be the brute force of course we could do an algorithm o of m by n basically by searching every single value in the input array right that's a pretty easy algorithm to do on a two-dimensional algorithm to do on a two-dimensional algorithm to do on a two-dimensional matrix but can we do better of course we can because they gave us a couple properties that this matrix has some sorting already applied to it assume that we just had a single row like forget that we had a matrix if we just had a single row like this one and we know it's in sorted order do you know an algorithm that can search for a target value in a sorted array i know of one called binary search right and how efficient is binary search well let's say the size of this array is n we could do a binary search in log n time right but of course we know that we actually have m different rows right so let's say we ran a binary search on every single row until we found the input target value right what would the time complexity be well log n multiplied by m is going to give us a solution like that so that's using the first property knowing that each rows integers are sorted but and this is a pretty good solution but can we do even better than this i'll give you a hint we're definitely gonna have to use this second property that they told us each row itself is actually in sorted order as in we know that the values in this row are going to be smaller than all of the values in this row and all the values in this row are going to be smaller than all the values in this row so can we use that property to instead of searching through every one of these m rows maybe we can actually do a binary search just to figure out which one of these rows to search in the first place because for example if we're looking for a target value 3 let's take a look at this row could have any values between 10 which is the lower bound and between 20. so obviously the target value 3 is not going to fall within that range between 10 and 20 right so then the question is okay if the target value is definitely not in this row we can cross this row out but then which direction are we going to go are we going to look at the row above it or are we going to look at the row below it of course we would want to look at the one above right because above the top row is going to have smaller values than the bottom row right so when we cross this row out we can also say that you know let's cross this row out too because of course this row is going to have greater values that's how the binary search is going to work to even figure out which one of these m rows we're going to need to search right so we can reduce instead of m we can do a log m by running binary search after we've ran that log m search then we know okay this is the row that we have to do our second binary search on so after we're done with that we're going to do another binary search so let's plus here log n right log n for binary searching the row itself so that's a better time complexity than we had previously right log m plus log n that's pretty dang good so once we get to this row we're going to say okay 3 is what we're looking for does that fall in the range between 1 and between 7 of course it does so either our target value exists in this row or it doesn't exist at all so let's run binary search here so of course we're gonna have two pointers left pointer and right pointer then we're gonna check the middle value in this case i think the middle value is gonna end up being this one because zero plus three is gonna become index one but let's just say it became this one just to kind of show you what it's going to look like let's say our middle value is here we're going to check okay 5 is that 3 nope 3 is less than 5. so what we can do in our binary search is cross out these values cross out our pointers now our right pointer is going to be over here and let's say we ran binary search again we compute the mid to be over here we check is this 3 nope 3 is greater than this so we cross this out and we shift our left pointer over here left and right are both here middle is going to be here as well we're gonna see okay either this has to be three or nothing or three just doesn't exist of course this is three so we found it we can return true and that's the entire solution so it's just a double binary search and we can implement that pretty easily once you kind of know how to do binary search and if you don't i'm going to show you how to do it right now so now let's get into the code so the first thing i like to do is actually get the dimensions of the matrix so let's get the rows and the number of columns in this matrix we can do that pretty easily because we know for sure that the matrix is always going to be non-empty and now we're going to be non-empty and now we're going to be non-empty and now we're going to do the first binary search we're going to look for the row that we need to find so i'm going to have two pointers one for the top row and one for the bottom row top row is zero the bottom row is going to be the number of rows minus one so now we're just going to continue to do the binary search until we can either find the target row or we figure out that the target row does not even exist in the binary search so one case is that the target value is even greater than the largest value in this row so let's go to that row okay first before i do that let me actually compute the row so we want the middle row in this case we'll take the top and bottom and divide it by two that's kind of how binary search usually goes right so and then we have that row so in our matrix we're going to look at that row and we're going to look at the right most value in python you can do that with negative 1 but we could also just do number of rows minus or the number of columns minus 1 but in python it's a little bit easier so we're going to check is this target value greater than the largest value in this row if that's the case what are we going to do well then we need to look at rows with even larger values so what we're going to say is our bottom row is going to end up being the current row plus one because now we want to look at rows that are uh larger than this row else if the exact opposite happens so let me copy and paste this if the target value was even less than the leftmost value in the array aka the target value was smaller than the smallest value in this row and that's in that case we need to look at rows with smaller values so we're going to shift our top pointer actually i think i just did it backwards so when we look for larger values we actually want to take our top pointer and then shift it down because when you go down in the matrix is when you actually get larger values and when we if we want to look for smaller values we're going to take our bottom pointer and then shift it up in that case we would want to set it to be row minus one so that's the case if the target value was either too big or too small if neither of those evaluates to true that means that the target value is actually does fall within this current row in that case we just want to break out of this while loop and then we can do the second portion of the binary search now it's possible that if we uh did not break out maybe we just created an invalid condition where we figured out that the top and bottom pointers are invalid right then our while loop would stop and what that would tell us is that we crossed out every single row in the matrix and none of the rows contained the target value in that case we have to return false immediately so basically if not top is less than or equal to bottom that means that none of the rows contain the target value and then we can just immediately return false if that's not the case then we're going to move on to the second binary search portion and we're going to run binary search on the current row that we found from the top and bottom pointer so let me just copy and paste that this is the row that we're going to run binary search on and we're going to have a couple pointers left and right which is going to be 0 and columns minus 1 because that's going to be the right most position in the row and we're going to do the pretty much the exact same thing that we just wrote above a second binary search while left is less than or equal to right let's compute the middle point we can do that by taking left plus right divided by 2 and now we'll do the same thing so if we find that the target value is greater than the value in this target row at position middle that means we have to search towards the right of the row we have to search towards the right of this middle point in which case we'll say our left pointer is going to be m plus 1. we're going to search towards the right else if the exact opposite was true then we want to search towards the right so we can shift our right pointer to be mid minus one and else the last case is if we actually did find the target value in that case of course we can return true now if this loop exited but we never returned to true then outside of the loop then we have to return false meaning that we never found the target value okay i just forgot that when we're copy and pasting i forgot to change this condition so the first one of course is if target is greater the second else if is target if target is smaller then we want to shift the opposite pointer and that is the entire code so you can see that it's pretty efficient so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
1,074 |
hey what's up guys this is john here so today let's take a look at this 1074 number of sub matrixes that sum to target so it's a hard problem okay let's take a look at the description here so you're given like a 2d matrix and a target so and it just asks you to return the number of non empty sub matrices whose sum is equal to the target okay so here it's just telling you that what is defined as like as a matrix and how you define the two matrixes are different those are kind of like a subtotal and here are some examples here so the first one let's say we have this like three by three matrix and then the target is zero right so and the answer is four right so one two three and four so that's the four sub matrices and here it's 5. so y is 5 because we have 1 minus 1 and a 1. so how do we get this 5 here right so we have one sub matrix right that's one that's two right and this is four so this is three this is four and the entire thing is five that's how we get five okay so first thing first right the brutal force way we can always do what we can always do uh try to find all the sub matrixes and then we do uh we do a pre uh 2d sub prism and then we just get each sub matrices sum and then we compare with target so if we do that right that's going to be a m square times n square time complexity and with that i think it's most likely it's going to be tle here because we have a length of 100 right so to improve that we have to find a better way right i think a common strategy whenever we see a like a 2d problem and ask us to find the uh the sum right alpha matrices you know so we can always like uh fix either a column or row two column or two rows and then we compress the row or column in between and then we convert this 2d problem into 1d problem let's assume we uh we fixed two rows here sorry two columns here and we compress that all the values in between now we have a 1d array here okay so now the problem comes down to the what there's a 1d array here the different numbers here right the different numbers here and with a given target k here what how what are the numbers of sub array whose sum equals to the target k that's going to be a different like a 1d problem right so to solve that so now how can we solve this problem right so the best way of solving this problem is to what is to use like a hash table basically the way we are solving this like a number of sub arrays whose sum is equal to k is we use a hash table it's going to be a actually it's more like a dp right so i'm going to like have like hash table right here so the key in the value right so the key is the sum and the value is the frequency for this sum and every time when we have like a running sum basically we're keeping like a running sum here right running sum and every time we get a running sum right we'll do a running sum minus k and then we have a target sum right and if the target sum exists in the hash tables we just add that frequency to our final answer and of course and in the end we'll be uh updating the frequency for the current running sound and so how will this thing work right why this thing works so let's say we have a i'll give an example here so the example is like this we have like let's say 1 3 -2 let's say 1 3 -2 let's say 1 3 -2 and two okay and let's say the k is equal to two so how about what's so what is the running sum so we have a so the random sum right the running sum is 1 4 2 4 and 6. right so let's assume we are at six here okay write six here and six minus two so six minus two equal to four basically our target sum it will be four and we'll be looking for like this four in the highest table as you guys can see we have like uh two fourths uh before six so that's why we will have like the frequency out of 4 or equal to 2. so it means that you know when we add 6 here we're looking for 4 here and we find 2 4 right which means that there will there are like two basically there are two uh sub array whose sum is two uh up until this up to this position so why is that and as you guys can see so what are those two sub arrays right so the first one is this one three minus two right so that's the first sub array that will get us to the two sorry my mistake what am i looking at here so the first one is this one that's the sub array two basically from this four to six we have a two here right that's the first one that's the first sub array ending at this position right ending at this position and second one is what second one is like it's this it's two minus two to two minus two and this one this is the second one and that's how we get the second four here right as you guys can see we have two four so the first one is it's as if we from the six between the six to this four we have the first sub array and the second one is between the six and the other four we have another sub array right that's how we can that's how we use this frequency to help us track how many summaries we have seen so far okay all right so with those two things in mind we can start our coding so the first thing is i'm going to use a presump right to help us to squeeze to compress the 2d problem into 1d problem you know so this is like a common techniques you guys should know so now we have zero right so that's that and now i need to i will populate i'll populate those uh the 2d prism okay now i have the current sum equals to this four j in range and if j equal to zero okay current so because we have the first element right that's why i'm going to do this you know actually another way of doing this is the uh we just uh pat this it's pre-sum with pat this it's pre-sum with pat this it's pre-sum with zero okay that's one way but in that but for that later on when we do the uh the loop here we instead of from zero to n minus one we have to loop through one to m plus one that's gonna uh i'm not a big fan for that so that's why i'm gonna stick with the original size here you know i j that's why i need to handle this uh j the first column separately so that the array the index will not be out of the boundaries you know so here we have a matrix you know high j plus right current sum -1 okay so that's that and then in the -1 okay so that's that and then in the -1 okay so that's that and then in the end we do a pre-sum dot append we do a pre-sum dot append we do a pre-sum dot append current sum right so that's that and now later so here we have an answer equals to zero so fix two columns right so the first one is c2 in range n and so that's that second one is c2 so the first one is cy in range c2 plus one so we do a plus one because even we want to include a single column case you know so that's why we have a current array here close to zero equals to not zero to empty list sorry that's my chinese input here so for i in range m right so because for each row we i want to compress the values in between those two columns so the row sum equals to the pre sum i c 2 right minus 3 sum i c 1 -1 i c 1 -1 i c 1 -1 okay so that's another thing we need to be careful since you know the c could start from zero if we if when c y equals to zero this will be out of the boundaries so that's why i'll do a check here c one greater than zero right else zero yeah i mean that's the uh a small catch if we're using the original size you know if we do a paddings we do a we initialize everything with zero with the size m plus one and an n plus one right so here i mean we start from one plus n right and then here we also from one to c two plus one and here we don't have to worry about these things here i mean just a small trade-offs trade-offs trade-offs you guys can choose whatever you want at least for me i'm sticking with the original size here okay so the current array right dot append yeah the row sum so in the end i have like uh a compressed 1d array here so all i need to do is i just need to create like hyper functions to help me uh get what get sub array count right this is target right so here i'm going to pass in this array here and then in the end i simply return the answer so now this is what i mean uh convert 2d problem into 1d problem now how it's left it's just to implement this hyper function right so define that uh we have array here so like i said you know we're gonna use a hash table to store us the frequencies of sums okay and i'll just use a sum dictionary and then as default we have a dictionary right with int okay and then we have answer equals zero so you know and then the running sum right the running sum starting with zero now we have a i for num in this array here first we do a running sum right and then plus numbers and then we have a target sum the target sum equals to running some minus target okay and then we check if the target sum in the sum dictionary okay and then we just do our answer plus the sum dictionary the frequency of that basically with the target sum right and then later on here we're just uh updating we update the sum dictionary that the frequency of the wizard type with the current rendering sum here plus one right and then in the end we simply return the answer okay but there's like a small things you uh we need to be careful here you know the thing is like this let's say we have this array we it's like one two as simple as this and the target sorry and the target is three here so we should return one right because one two has the sum equals to three but if we follow our logic here let's say we have one here right so at the beginning the random sum equals to one right and the target is it's equal to one minus three which is going to be a minus two and minus two is not in the dictionary so we'll skip okay so now we have a dictionary like this right so one and when it comes to two here so the running sum is what is three right the running sum is three and three minus three is zero but still zero is still not in the dictionary but you know as you guys can see here zero is a special case it means that if the sub array if the one of the sub array starts at with the first element okay then we need to have like a base case with a sum equals to zero so that we can count this array we can handle this case all right so that's why after we created some dictionary here we're gonna start with zero with one so that you know here we can accumulate that one into our final answer here all right yep that's how we calculate the uh this uh count of the sub array yeah this is the target here and this is a very useful uh sub problems i think you guys should try to remember that at least remember the concept and the logic you know as you guys can see this one can be combined with some other techniques and then form a hard problem so it's better to uh to master this uh the sub problems first okay so let's try to run the code oh dumb sum okay all right answer run the code all right cool accept it submit all right cool so accept it all right so how about time and space complexity right so i think it's pretty straightforward right so here uh i think this is the most expensive part so we have a m times no this is like n square right so this is a n square and we have like uh o of m here right then here the sub problems here so as this is like a of m as well right so this is only a single photo here so in total this problem is going to be a n square times m right so that's that and the space complexity is the uh is the m times n because we have that presump stores here that's going to be a 2d array here and this is the time complexity we uh when we fix two rows here two columns here you know we can also fix two rows here so in that case the time complexity will becomes m square times n right yep cool i think that's it for this problem thank you so much for watching this video guys stay tuned see you guys soon bye
|
Number of Submatrices That Sum to Target
|
high-five
|
Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.
A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.
Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.
**Example 1:**
**Input:** matrix = \[\[0,1,0\],\[1,1,1\],\[0,1,0\]\], target = 0
**Output:** 4
**Explanation:** The four 1x1 submatrices that only contain 0.
**Example 2:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\], target = 0
**Output:** 5
**Explanation:** The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
**Example 3:**
**Input:** matrix = \[\[904\]\], target = 0
**Output:** 0
**Constraints:**
* `1 <= matrix.length <= 100`
* `1 <= matrix[0].length <= 100`
* `-1000 <= matrix[i] <= 1000`
* `-10^8 <= target <= 10^8`
|
How can we solve the problem if we have just one student? Given an student sort their grades and get the top 5 average. Generalize the idea to do it for many students.
|
Array,Hash Table,Sorting
|
Easy
| null |
51 |
hi guys uh we are solving a new question today this is a n queens question in this question we are given uh n cross n checkpoint and we have to put n queens on it so first we have to you know draw the chess board so this is a chess board and it's basically we have to put a cue for a queen so we are using a string if you have to put a one we will use integer and for every value on the board we are initially putting a dot as in the question and then we will make our solve function main function so let's make the solved function in this the solve function we are passing our forward and the initial column so initial column is here zero we first pass zero and the power then it the it will check that it has iterated to every uh column and if it has done every column then it will push back the board into the results so we need to make our result vector also which is also a 2 cross 2 a string vector then we have chosen the column and we have to iterate to the rows so we check for the rows every rows in which we have to put the values and we have also check we also have to check the particular cell is safe or not so for this we have to make a save function so let's make a save function which is a boolean type so this is our is save function here we have passed the board in the row and the column so we have to check that particular column in which we are putting the queen save or not so for this we first check the uh column so let's say this is our chessboard and we first put our queen in the zero column and now we are checking for the rows so then we let's say we first put our queen here let's see this is our queen now for the second queen for the second time we are placing our queen let's say we have to place our queen for the column two now iterating we have to then iterate through rows here so we have to iterate through rows and then check that particular cell is safe or not so while in first row we check for the columns the particular queen we have a queen first column so we have to check that this particular column is having a queen or not so in this we will check that particular column has is having a queen or not if it is having then we will return false second thing we have to check for the diagonals so let's say we have another queen here now for placing in the next queen what things we have to check for placing the next point so we have to place the next screen first we have to check the columns so this column is occupied this is not occupied right this is we can't place our queen here this is this state this is ensured by this first and for the diagonal part we have to check uh let's say we play a placing our queen here so we have to check that this diagonal row doesn't have any queen so for this we have to uh iterate our rows and column uh both at the same time so from the present cell we uh put a decrement of minus one so and if in quarter encounter any queen we will return false similarly we have to check the lower diagonal also by for checking out lower diagonal we have to put i less than n because earlier we are iterating to the zeroth row now we have gone to n and we have to decrement uh increment the rows now so basically this is the lower left diagonal this is our upper right packet so this is our is function and we have made our void we have made our way we have placed our queen in that particular cell which is safe now our job is done by particular placing the queen and that safe wall so we again call the function sold it again call itself and this time we pass the second column and again till every column is passed and the final result is pushed back to the original column now for the in the back tracking part if that particular column is safe if it not say we have to put point or dot there so this is the part where we have to put dot for the uh cells in which we are not putting the queen or we have wrongly put the queen in black tracking we are just we have to backtrack also know okay so we haven't returned our result i think this is sufficient so this is basically and queens backtracking we first check uh it's safe or not in this part then we iterate through the rows and again recursively call the function itself and if there is a something wrong we will come back and put a dot there this is it thank you
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
355 |
hello everyone so in this video let us talk about a problem from lead code the problem name is design twitter so let us go to the problem statement it goes like this that you have to design a simplified version of twitter where user can post tweets follow unfollow another user and is able to see the 10 most recent tweets of the user's news feed now you have to implement the twitter class and you have four functions you have to define the first function is twitter you have to initialize your twitter object that is we will go the code part the second one is the post tweet uh function which will take a user id as well as a tweet id as an input now what this like what this will actually post a new tweet on the what you can say a timeline okay or like that user with a user id tweeted a new tweet and this is a new tweet id so this will unique now this is a like a integer list which is get news feed so it's like a vector of in like a vector of integers you can say which will return for a particular user a news feed or a tweet feed or different users who are friends of that particular user you want to get so let's say that you log into twitter so you will see the tweets of different connections you have or your tweets also let's say that you are also tweeted out so you will have to get 10 most recent tweets by tweet id so you can also see that each item in a news feed must be posted by the users who the user follows or by the user themselves so you get the tweets and they must be the like they must be the from most recent to the least recent in the 10 most recent tweets such that they should be either by you or by your friends now this is the follow or the unfollow function in which like a particular user can follow another user so you will be sending out the particular follower id and the followee id okay so as you can see the user with id follower id started following the user with this follower and similarly you can unfollow it so you can pause this video try to think over there can be multiple approaches you can solve this problem because it's just a way to implement twitter not twitter but actually a smaller minified version so you can be you can pause this video try to think over that how you can come up with this but what you can like when i come up around these type of problems i generally try to like hit and try different data structures so what most efficient data structure can be used here to implement this type of scenario okay so what you can see here is that i what first see what functions you want to implement so you want to first also have to implement a user type of manual that what user is friends with what user so you have to get users out and let's say i'm a user with you and i'm a friend of yours so you have and there are like hundred of friends so i want to somehow fast retrieve of me who friends are like who are friends with me oh i am the follower so that in that place the best way is using a set okay so you can make some sort of a vector to a set or let's say a map to a set in which uh you give a unique id and then you'll get all the friends i am to and then you can just do a very simple login search over that whole set to get who's i'm friend with so that is most optimal if you can use like different approaches but like in this because they're different user ids they are unique so you can use this type of approach now to get out another thing is how to get out the news feed so you have to somehow get from the most recent to the most like least recent so you have to also store some time stamp like at which time these feeds are what you can say like uh likes uh put like when they are posted okay or like when they're tweeted so you have to also store some kind of a time stamp also if you have all the tweets then you can easily filter out if you have the tweets by their timeline you can just easily filter out what tweets you want and what tweets you do not want because you just want 10 tweets okay you don't want 100 afraid you don't have to implement a large like ever ending to it system you just want 10 to it so it will be very fast to retry in that case what you can do you can use multiple data structure but i'm using priority queue here why because priority key will be storing out by the what you can say by the time okay so i have to sort them and practically will obviously be sorting them if i'm like inserting a different twitch it will be automatically sorted out i don't have to sort it every time okay so maybe there are some tweets that are inserted then maybe they're like we then maybe sometimes deleted i am a user not user there will be multiple scenarios but as you can see that this is a dynamic list so you have to somehow keep it in a sorted way so it's better to make it like a priority queue so that is what i'm using here now i will directly move down to the code so how i'm doing it because it's not much to explain what is the at that implementation but you're just using different data structure so i'm directly moving down to the code so it will become more clear when you move down to there so what you can see here is that uh what i have initializes these three different data structures so one is a map that is taking an integer and pointing towards a set of integers that is just storing out my friends okay so this is the current will tell you the current time what time that you will have to use to store the time stamps okay and this is the priority queue that is a different timeline is just storing all the different tweets on the different twitter platform so that uh it will be differently like it will be stored in a particular timeline manner so twitter will initialize this actually map with clear so that it will be first cleared out current is zero because it is current time zero there's no to it so you can slide with zero and you can also initialize a timeline to be null so that like it's not null it's just empty okay so what you can now start is when you want to post a tweet what you'll do you will push in this new timeline the current plus because now you will like update your time that a current uh post or tweet is done tweet id and uh user id is sent by this whole uh this function call so like you can use these parameters to be inserted also now coming down to follow and then follow i will move down to this again but what if you just directly come down to fall and follow what you can use is because i'm using set you can directly insert into the set and erase from the set so you are the follower id you can directly insert in the set and erase from the set fine that is also done now what you can see here is now i have the complete timeline so what you can directly do is just copy that timeline in user timeline because you have the kind of complete timeline what you can do is just make a copy of the timeline in a particular user you are so that you want to form the news feed you'll get that whole timeline here then initialize end with zero because you only want 10 timelines so you'll do a while loop till the user timeline that you have the timeline you get is not empty and they are not like less than 10 feeds you have you get the top feed and then you pop it out from that particular timeline and then what you'll do i'm just checking it out for every feed as you can see so what you can checking checks is so like whether that particular feed that you have what you can see is that whether that you feed you have is the user's feed like the user have posted it out so as you can see that top feed as you can see that the top to eight is just a tweet so tweet has these three parameters the current time because that is why they have sorted by time so as you can see that this time and then tweet id i just want a user id okay user id because either the user has posted or the user's friend is also posted so user is 012 so this is a second index so as you can see that whether the tweet id the second is the user itself then i will push back into the tweet so answer is just storing out the top 10 tweets so i will push that particular to it that is one so this is the tweet id i just want to print a tweet id so i will be pushing the tweet id into the answer vector only if it is posted by the user or the friend of the user so i will be checking out the friend of the user so this will give me a set because i'm iterating my map so in the map i'll be sending out the particular user i am on and i will check that whether the user i am like the butler tweet i have is from the friend of a user if i it is a friend from the user then only if any one of this condition will be like true then i will be pushing out the tweet id in this answer vector and increment my end that i got one more tweet like one more like to it in the news feed so as you can see then whenever i got 10 then i would be the stream turning on the answer that is the overall logic there are multiple approaches as i have told you but you can use this also that is perfectly very fine so thank you for watching this video till the end all this code will be in the description of this video so don't worry uh as a next one thank you coding and bye
|
Design Twitter
|
design-twitter
|
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed.
Implement the `Twitter` class:
* `Twitter()` Initializes your twitter object.
* `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`.
* `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**.
* `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`.
* `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`.
**Example 1:**
**Input**
\[ "Twitter ", "postTweet ", "getNewsFeed ", "follow ", "postTweet ", "getNewsFeed ", "unfollow ", "getNewsFeed "\]
\[\[\], \[1, 5\], \[1\], \[1, 2\], \[2, 6\], \[1\], \[1, 2\], \[1\]\]
**Output**
\[null, null, \[5\], null, null, \[6, 5\], null, \[5\]\]
**Explanation**
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\]. return \[5\]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> \[6, 5\]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\], since user 1 is no longer following user 2.
**Constraints:**
* `1 <= userId, followerId, followeeId <= 500`
* `0 <= tweetId <= 104`
* All the tweets have **unique** IDs.
* At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
| null |
Hash Table,Linked List,Design,Heap (Priority Queue)
|
Medium
|
1640
|
739 |
hello and welcome to another video in this video we're going to be working on daily temperatures and it's definitely a solid interview problem that you should know how to do it's not super hard and it has fundamental algorithms so in this problem you're given an array integers temperatures represents the daily temperatures reten array answer such that answer I is the number of days that you have to wait after the I day to get a warmer temperature if there's no future day for this keep it zero so we're going to go through example one and kind of exactly what they're talking about and how to get these things so here we have our days so basically for each day we have to see what's the day that is the closest day to this that has a higher temperature so for 73 it's going to be this day over here so how many days is that difference that's one day difference so we're going to mark this now for 74 what's the closest day that's bigger than it 75 so that's one for 75 there is 76 so that's 1 2 3 4 for 71 that's 72 two days apart for 69 72 one day apart 72 76 one day apart 76 there's nothing bigger so we're going to leave this as zero and there's nothing after 73 so it should be1 42110 0 and here it is right here so that's kind of what we're looking for so essentially for every day we want to know like what's the closest day so let's think about how we'd want to do this like what's the minimum amount of information we need to store well let's say we have like let's say we just store the current day or something let's say we store we have a temperature at 73 at index Z and we get to the next day so as soon as we get to the next day and that day is bigger we don't need to store this anymore because we kind of found the bigger day than this right we just said like oh look 74 is bigger than 73 so therefore we don't need this anymore we can just figure out the distance there and record it so we can get rid of that one now let's say for 74 we store 74 with an index one and we get to 75 so for 75 kind of the same thing right we found 75 is bigger than 74 we don't need 74 anymore we're only checking days to the right of the current day so then we'll store maybe 75 with an index of two and then we have 71 so 71 is smaller than 75 so we that means we need to keep both 75 and 71 because we're looking for a day that's bigger than both of those so 71 we'd also need to keep then we get to 69 and 69 we'd also get to keep and so on so that's kind of the idea is you're going to be storing your temperatures in decreasing order and then anytime you find a day that's bigger it's going to get rid of a bunch of stuff so let's say we have our temperatures in decreasing order like let just say we have some random numbers we have like 75 71 69 and we're going to be storing the temperature and the index so then we know like how many days is apart and let's say we get to some temperature that's bigger than 69 let's say we get to like 72 then we're going to be Crossing stuff off from the right because our temperatures are in decreasing order we can just go one by one and see like is our current number bigger than this is it bigger than this and because the rightmost one will be the smallest you'll be able to do this efficiently right you won't have to see like where is the smallest uh element so for 72 we'll say it's big than 69 so we don't need 69 anymore we found the bigger element we don't need this element anymore either and then we'll just pop on 72 and so this data structure is called and these are ones that you should be aware of it's called a monotonic decreasing stat and basically in layman's terms what that means is just you have a stack of elements that are decreasing or equal to each other um I don't remember if a monotonic decreasing can have elements that are equal but either way like every element will be less than every other element so it'll be decreasing and the other one you can have is a monotonic increasing stack and whenever use a stack data structure those are like for the most part that's what you're going to use the data structure for it'll either be monotonic increasing or decreasing and that will give you the biggest or smallest element in know of one time because it'll just be the last element so let's walk through this again with our stack and let's walk through like exactly what this is going to look like and this works for any problem that you want to find like the next greater element or the next smaller element or something you would want to use a monotonic increasing or decreasing stack so let's actually have a we do have a stack looks like hopefully we have enough space here so let's use a stack so essentially like I said we are going to be storing the element and its index so for 73 we're going to first check is anything in our no it's not so we're just going to store 73 with its index so we'll store 0 and 73 then for 74 we're going to check is anything in the stack yes it is 74 bigger than the number in stack yes it is and how many days apart are those they're one day apart so that means for whatever is in here we're going to take this index and put a one in this index and then we are going to record the 74 along with its index so 74 with an index of one now we will go to our next element so 75 5 is 75 bigger than the top of our stack yes it is so we will get rid of this element and this had an index of one that means we are at currently 75 so we can mark that we're at 75 we had index of one now we have index of two so those are one day apart so for whatever was that index of one this is one day later so this is one now we will store 75 with an index of two so two 75 then we'll move on over here so is 71 bigger than the top over no it's not so that means we will store the value and its index three and now we get to 69 so 69 bigger than the top of our stack no it's not so we will store it so this is 469 now we get to 72 is 72 bigger than the top of Stack yes it is so 72 is bigger than 69 it is an index of 5 69 had an index of four so that's one day apart so for four we will write one and get rid of that element then is 72 bigger than 71 yes it is it had a day of three so these are two days apart so for index three we will write two and finally is it bigger than 75 no it's not so we'll just add on the 72 now with an index of five so whenever you're done getting rid of elements you will always push on the item onto the stack and so yeah so next we are going to go to 76 and 76 is it bigger than 72 yes it is so for 72 is that index 5 is that index six so one index difference so we're going to put a one here get rid of 72 then is 76 breing 75 yes it is the difference is four days so here we will write four and finally we will put on 76 into our stack so 76 let's actually just delete it with an index of six then we'll go to our next item is 73 biger than 76 no so we'll just put on 73 with an index of seven and we can just initialize every single element in our result array to be zero so whatever we didn't fill in will just be zero so now if you look it's 11 14211 which is the same thing so that's kind of how you do it you just have a stack and because you're looking for the next greatest temperature your stack is always going to be decreasing and then every temperature will just automatically find the smallest available one in the stack and if it's not smaller than the smallest available one or it's not bigger than the smallest available one in the stack then it's not bigger than the rest of the stack so we don't need to check our whole stack we can just check efficiently just the last element and yeah that's going to be all for this one so let's code it up now so we're going to have a result array we'll just initialize everything to zero maybe you can even rename this to like temps or something just to make it shorter um then we're going to have a stack and now we want to go through every single index and the temperature in our temperatures so for index and temp in enumerate temps now remember what we need to do is we need to check while we have a stack and while our current element is bigger than the top of a stack we need to be popping off elements so while stack and temp is greater than stack and the way we're going to store our stack is like I said we're going to store a tuple of index value so it's going to be the top of our stack and the second element in there so you can do this as well if this makes more sense to you so the top of our stack and the second element in there will be the actual value so we will pop off those things so all we really need we don't really care about the value anymore we know that our current element is bigger we just need the index so we can just say like location and this we're not going to use equals stack. pop and we need to figure out this difference right so result at index location is the index of the element equals the current index minus that location that's how many days have passed finally once we're done popping things off the stack we will append so we will append a tuple of the index and the temperature and then we will return result and whatever is left in our stack it doesn't really matter because those will all be zero like the trick for these kinds of problems or not the trick but if you want to return some value and you want to have a default value just initialize the whole array to that value and then if you never change it'll just be that value to begin with so if you wanted to return negative one for every value that wasn't found just initialize this to negative one and we can run it oh we need a two here okay and there we go so pretty good so this is going to be yeah and like I said this is a probably if I had to guess it's probably a common interview problem let's take a look yeah because it's pretty easy and it tests basic algorithm knowledge so this is going to be time oven so most stack things are going to be oven because you will at most put an item on the stack once and pop it off the stack once and the space is oven for our stack um yeah so that's going to be all for this one hopefully you like this one definitely one that you should be knowing not a hard problem at all um let me know what you think uh write in the comments and so on and if you did like this video and this explanation as always please um like the video and subscribe to Channel I think we're getting close to like 900 Subs so hopefully get to 1,000 pretty soon hopefully get to 1,000 pretty soon hopefully get to 1,000 pretty soon that'll be great okay and thanks for watching
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
863 |
okay so hello everyone this is AA here and let us proceed with today's question given so today's question is a hard category question but we will do it in a very simple way we will use the very basic fundamentals of the binary tree so let us read the question first and then we can proceed here with the solutions so we need to find the nodes at the given distance in a bin let us understand how the input and output is working then we can proceed ahead given a binary tree a Target node in the binary tree and an integer value Cas so find all the nodes at a distance cas from the given Target right so the output is as follows 10 14 and 22 so what they have done is the k would also be given to you that k equal that means you need to move K levels up and K levels down of the target node and you need to print all the possible notes on that particular level so for this eight if you move down by level two so one level would be down by 12 another level would be down the level two will have these nodes so 10 and 14 is in the answer similarly if you move two times ahead in the directions given so this the clearly times move so 8 20 one move 20 this the second move and on this we have the that is why 10 14 and 22 we have seven right we have seven and that is we need to that we can do two moves so 7 three that is one move guys so we are at this point so one is definitely in the answer similarly seven so that we are at this 20 again we can move make a one move in the right hand side direction for this pent child of for this root 20 and we got the N 24 and that's why and4 are the answer now I hope we are clear what we are supposed to do now how we can do is so then the logic is very simple right code may be complex the logic is very simple so the entire logic that we going to use here is level order davers homework you have homework to do if you do not know how the works and what it istion considering you know how the level tral works now we can proceed ahead okay so this is what is the prerequisite okay so what we will do here is that we will make a function let's say Mark parent okay what it will do is that it will store um we will have a hashmap here we will have a hash map Tye okay and this node would be this node with the all the possible nodes and this is nothing but the parent of that node okay so we will do a BFS or let's say level our Tri make the function Mark parent and we'll do these things right so how the hashmap will look like is that for each and every note for eight the parent is 20 okay let me okay for the eight parent is 20 then for 22 the parent is 20 then for four the parent is 8 for 12 the parent is eight then what else for 10 it is 12 and for 14 it is 12 again right so this will be the entries present in your hashmap take first step First Step what is the Second Step what is the second step and uh what is the Second Step the second step is what is the Second Step second step is that we will make a one more function let's say fun right and we will perform level order traversal I'm writing it as lot level or traversal for its children for it children means for left child and for right child and since for every node we have the track of what is the parent we will perform the level traval for the parent as well for the right child for the left child and for the parent as well so let us do the traval now we will start from Target node we can go upes right count initially count equals okay what happens to my cursor wait a sec yes I'm back so initially ini count Z what the ex again one second whenever we are pushing any node adding any node in the queue we will also add in the hash and we will only process it children left right and parent we will proed these notes only when it is not visited right so for or so for four left and right child does not exist parent exist but that is already visited so we do not have to go further 12 you can clearly see the child are 10 and 14 that is not visited till yet so we will visit it again and what is the 12 the parent is eight but you can clearly see that eight is already was already visited in the CU right so we'll just again move ahead so for 20 what is it for 20 the children are 8 and 22 so 8 is already visited so I will visit 22 right and yes right so that goes so up Q so that me we use a Lo here right and then once the current Q the element the elements which present in the current then we will also increment counter as count equal to two right since K and count is not equals whatever you have in your Q will be your answer you can make a move in upward direction also right but we can only move in the downward direction that is we can only access children that is why we have made a function and then we are doing a level of Trav not only for children but also for the parent we are moving ke moves towards the parent side and towards the children size and we are also maintaining a hash to maintain the duplicacy already that will give us the redundancy and at final we have the answer right I have tried my best to explain you guys so I think we are on a good way to now code this approach so I will not give you a pseudo code because the code is very large right doing these things the code is very but code is very simple I'll give you a very in-depth simple I'll give you a very in-depth simple I'll give you a very in-depth walk through is very simple right now your homework or let's say your work is to pause this video here now give yourself a 15 to 20 minutes if you have understood the dry run I think you have if not revert back to the video again try to watch this video again and then do some on your own if you understood even then also do some on your own and then start ahead with your coding section okay question has also been asked in the lead code question my last submission was I guess in 2022 same question the only difference for the gfg and the lead code is Target right node reference pass but in the gfg it has not passed the reference but it has passed the int Target right I have named this start so what we'll do is that first of all we will make a Target node you'll get the reference of it because then only level or so we have made a F Target so find Target is nothing but we are searching in a binarity that's a very simple code we are searching in the bin that means we need to make a recursive call the left and for the right as well what would be the base case that whenever we hit the null or the root equals to Target then and then you need to return the root so let's say the root was not present then these two cases will be there so but in this case the root is already there right so that's a very simple and a naive code and yes again if you are not able to understand this code as well search insert delete B then let's go to the Second Step as I told you that we have to mark the we have to make a map and store all its all the node neighbors right all the value part right there the parent of the node BFS so we have made a hash map here and then we are calling a function mark parent we are giving two parameters that the RO root node of three and the parent hash map right the hash map we are passing it there again if you're notar with the level so we have again the same as we have maintain a while then we keep on popping the que we keep on popping the current node the top most node present in the que right that thing is done and using this B Technique we have now a hash map where all the nodes are stored with its neighbor step complete using the mark function is very simple but code is ly but that doesn't matter we need to make a function CL we need to return the result again purely level for Left Right and parent right and we are stopping the traversal when the times when the or let's say the count of move is equals to K let us go again and let us see again a level out traversal again we have added the target node first of all in the reference integer value it is the node actually structure Target pass and then we have marked that particular Target as visited node right that is we adding the first Target node again I'm count need toel right at that particular time that is the width of your or that is the particular level of your tree so that is why we are using a for Loop here again I'm saying if you very clear with your level tral code the first two videos of a binary tree playlist then you are good to go for this code so this follow Loop is ensuring that we are traversing level wise right traversing and what we need to do we need to process the left children right children the parent children right so that we can move upwards we are checking if left children exist and it is not visited then add it in the queue and Market has visited again right children is present add it in the queue Market has visited again if parent is not visited like if parent is there if it is not equals to null then definitely if it is not visited as well Mark it in the add it in the que and Mark this as Vis at the last we have seen that whatever after the key moves after the KE moves whatever nodes we have in the que that would be the answer right and question sorted format return right you need to have to return this list so our answer is present in this answer AR but we need to um what to say return it in the sorted format so I will say just collections. sort answer and that is it that is the complete code let us hit the your output expected outut matches let us hit the button mean it is submitting what is the time we are giving we are doing inun but 2 N plus n l so ignoring the lower complexities what is the overall worst complexity it is n logn and that is what it is given here of width of the tree would be the space complexity again any time comp right great let us see the C++ time comp right great let us see the C++ time comp right great let us see the C++ code now and do not worry you will get all the source code Link in my DSA repository you may star and F my DSA repository you get help with the source code in the future as well because there are maybe more than 500 code present of the standard question code present there right let me just call it for you I'll not give you a code work through the same thing is happening in Java and what we have seen in the dryon as well now although it was a hard question and the same we have done in this lead code as well so let me hit the submit button here as well and then we shall end this video great and till keep learning keep gr bye-bye and till keep learning keep gr bye-bye and till keep learning keep gr bye-bye and take care guys
|
All Nodes Distance K in Binary Tree
|
sum-of-distances-in-tree
|
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._
You can return the answer in **any order**.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2
**Output:** \[7,4,1\]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
**Example 2:**
**Input:** root = \[1\], target = 1, k = 3
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* `0 <= k <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Graph
|
Hard
|
1021,2175
|
1,647 |
hello everyone and welcome back to the helgi kareena and today we are back with yet another very interesting problem on lead code which is minimum deletions to make character frequencies unique now let's take a look at this problem so according to this problem a string s is called good if there are no two characters different characters in s that have the same frequency given a string s return the minimum number of characters that you need to delete to make as good now according to this problem you have been given a string s which contains all uh lowercase english alphabets and each of the alphabet can occur either one or more than one times right so uh what you need to do in this problem is that you need to delete some of the characters from this string such that no two different characters have the same frequency so for example in this case uh a and a occurs twice b occurs once so basically there are no two characters in the in this string which have the same frequency so we print 0 over here we don't need to delete anything over here right now in the second case if you see there are three is uh there are three b's and there are two c's right so there are since there are you know both a and b occur three times so we will need to do some sort of deletions right so according to the explanation over here we need to delete two b's uh resulting in uh you know good string triple a b and double c because see if we would have just deleted a single b there would have been two b's but those two b's would have collided with the two c's because c also occurs twice so basically what we need to do over here is that we need to uh you know delete two b's from over here so after deleting the two b's what we will have is we will have three is one b and two c's so all the characters are having different frequencies so let's try to look at this like how we can solve this problem so let's take an example where we have been given this big string right now let's try to see how we can solve this problem so a very intuitive step uh as a first step would be to just to note down what are the frequencies of each of the different characters over here so let's start let's say you know a has you know one two uh then three right so there are three is present in this uh in this basically string right now let's move to b so there are one two so we have two b's in the string c we have one two three d we have one two three and four e we have just a single e and f we have one two right and rest of all the characters starting from you know till z are all zero because they are not present in the string so basically we can this is how we can represent the frequencies of the different english alphabets present in this string right now if we see over here that straight away like there are three a's and also there are three c's right so there is no uniqueness in the frequencies and then similarly there are you know two b's and there are two f's so again over here also there is no you know uniqueness in the frequencies so now what we are going to do is basically we are going to traverse across all these 26 characters one by one and then we are going to keep on checking that whether the frequency of that character has occurred in the past or not and if it has occurred in the past uh then what we are going to do is that we are going to try to delete some of the occurrences of that character one by one right and to check whether the you know that particular frequency has occurred in the past or not what we are going to maintain is basically a hash set right so we are going to maintain a hash set over here other thing that we are going to maintain over here is basically a deletion count right so deletion count will basically maintain that when as and when we are traversing across all these characters we would be deleting some of the occurrences of this these characters right so to maintain the count of those deletions we are going to maintain this particular variable called deletion count so let's start traversing our alphabet starting from a so a has three uh you know occurrences now we check our hash set three hasn't occurred till as yet right so uh what we are going to do is that we are going to put three over here that now we have uh come across three uh we do not delete need to delete any occurrences of a over here so our deletion count still remains to zero now what we will do is that we will move to b now b has occurred twice so we are going to check our hash set is there any other character which has already occurred twice no right so we are going to put two over here and our deletion count maintains to zero now will we move to c so c has occurred three times now we check our hash set so three is already present in the hash set right so we need to do some sort of deletions in c so what we are going to do is that first we will decrease it by one right and we will increase our uh you know uh deletion count by one so now we check whether two is already present in the hash set yes 2 is also present in the hash set so what we are going to do it we are again going to delete it you know delete one more occurrence of c so the number of occurrences reduces to 1 right and our deletion count increases to two now we check whether one is present into the hash set or not no one is not present in the hash set so what we are going to do is that we are going to add one over here right and uh the deletion count is not touched anymore so we boil down to that only one occurrence of you know c uh can be there for uniqueness and we delete two occurrences that is why we dele we increase our deletion count by two now we move to d has total 4 occurrences so we check our hash set is there already 4 existing in it no 4 doesn't exist over here so we are going to add 4 to our hash set and deletion count maintains 2 as it is right so now we move to e has just uh one occurrence we check our hash set now is e already is one already there in a set yes one is already there in half set so we need to you know decrease the occurrence of e to zero and also increase our deletion count to three now since uh the occurrences of e are reduced to zero we cannot you know delete it further or reduce it further so we are going to ignore it and we are going to move to the next character now f has occurred two times in the original string now we check whether two already exists in the hash set yes to exist in the hash set so what we are going to do is that we are going to delete one of the occurrences of f and similarly we are going to increase our deletion count to four right now we check whether one is present in the hash set or not yes one is present in the hash set so we are going to you know delete one of the occurrences of f to zero and our deletion count increases by one to five right now since f has uh has been reduced to zero that is zero occurrences of f we cannot do anything for it so we are going to stop over here now uh similarly like we have traverse still f we can move for further like this for all the you know characters but for the sake of this problem we do not have anything after f so we are just going to ignore it for this time uh now our final answer is basically five that is you know we need to do five deletions uh at minimum to have all the unique characters that is you know have all the unique frequencies for the different characters right so let's try to re-evaluate uh how we went across this re-evaluate uh how we went across this re-evaluate uh how we went across this particular algorithm to solve this problem so first thing that we did was basically you know first we found all the frequencies of characters from a to z so basically we created this array of a to z ah there is a mapping of character to uh the number of time it has occurred in the original string right so this is our first step the next thing that we do is that maintain a hash set to keep the occurred frequencies right this is which is about this particular hash set so we maintain a hash set then the third thing is that we iterate in the frequency array from a to z so we are going to iterate across this particular mapping uh of you know characters to frequency uh from the order a to z and what we are going to do in each of the iteration is keep on reducing the frequency value till the point it is no more found in the hash set or it is reduced to zero right so in case of like you know c we saw that you know three was already there in the hashtag and two was already there in the hashtag so we reduce the frequency and increases the deletion count and in case of e and f what we saw was you know since one was present we reduced it to zero and you know since it is reduced to zero there are no more occurrences so we'll have to stop this particular iteration at this point right so after performing all these steps whatever is stored in the deletion count will be our final answer now let's take a look at the code for the solution now over here we have maintained a frequency array this will be storing the number of times each of the element has occurred in this string s right now instead of this we would we could have maintained a mapping of character to the frequency but just for the simplicity purpose what i've done over here i have mapped the zeroth index of this array to the number of times a has occurred the first index of this array to number of time b has occurred and similarly the 25th index of this array to number of times that has occurred right now uh what we do over here is that we will iterate across this entire string and you know fill this frequency array now as we discussed in our algorithm that we are going to maintain a hash set to uh to keep count of what all frequency have already occurred and we are also going to maintain how many deletions we have already done right now what we are going to do is that we are going to iterate across this entire frequency array and for each of the characters we are going to you know decrease the current frequency count and increase the required deletion count till the point that particular current frequency is already present in the occupied frequencies that is uh that frequency has already been seen in the past right so we are going to delete those uh occurrences of that character right and when we are going to uh stop this particular loop is when either you know uh we come across a current frequency which is not already present in our hash set or we reach a point where you know current frequency has been reduced to zero right now uh you know as we already know so if the frequency current frequency at the end of this loop was not zero then we will put it into uh into the hash set so that you know if in future uh we come across that frequency again uh you know we can call out that you know this frequency has already occurred the next character shouldn't have that frequency again right so in this entire loop we have been updating this required deletion so at the end of this entire for loop this will have our final answer and we are going to you know return it so that's all we have for today uh so thank you for watching this video i've added the solution for this problem in the description given below please do subscribe the channel thanks for watching this video and please do comment in case you want any of the topics to be discussed thanks a lot bye
|
Minimum Deletions to Make Character Frequencies Unique
|
can-convert-string-in-k-moves
|
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
|
Hash Table,String
|
Medium
| null |
1,443 |
hey everybody this is larry i'm doing this prom as part of a contest so you're gonna watch me live as i go through my darts as i'm coding uh there'll be an explanation near the end and for more context there'll be a link below on this actual screencast of the contest uh how did you do let me know how you do hit the like button hit the subscribe button and here we go okay cue 3 uh minimum time to collect all apples in a tree so this one you're given a tree but it's not a well it's an apple tree but you're not giving a tree data structure and when i refresh i was like wow 40 people already finished this i'm really slow on today um because people you know that's intense but yeah now the first thing i do is i convert it to an adjacency list um i think one thing to note is that uh it's not clear that it's a binary tree and i think i try to be sure that it doesn't seem that way so now i just construct an adjacency list um so as a reminder if you want uh an explanation on this problem skip a little bit ahead uh or click on the video that's for this uh problem specifically and there'll be an explanation there and let me know but for now i'm just going to talk about my thought process as i uh as i go which for now i'm just reading the problem i just want to make sure that i'm reading it correctly uh and at this point i'm just looking at the input just to be like okay let me make sure that is okay but after that i was like okay i could just do a deafest search and that's essentially what i started already look at that game face uh and i spend too much time just trying to figure out the naming for this problem uh for a helper uh basically at this point what i wanted was okay given a node what's the recursion well the recursion should be some variation of um and i was trying i mean i knew it was going to be some sort of recursion or that first search if you want to grab that but i was like okay what are the base cases and that's what i was trying to type out a little bit i was like that's not a base case um and because we have uh not a tree not a node uh or vertex data structure we have to visit it so we kind of treat this almost like a general graph and that we follow that for a search we have to make sure that we haven't seen the note uh and that's pretty much what we do here and we have a helper function of apple right for a node and for me this apple node is um for uh this apple function just because if this tree or if subtrees have apple if any apple then mark that is true so a better name a better function name for this would be uh apple in subtree or something like that uh and i you could probably calculate this with another way but i did it with lru cache um the reason being that we know that uh for apple they're well they're only n vertexes and you want a calculation of at most once so that's what i do here and i here i think what i'm struggling with is coming up with a recurrence right i mean the recurrence of symbol is giving every node look at the subtrees and then if any of those subtrees uh half an apple then return true and you could calculate that recursively because you know by definition if any of your uh if any of your child if any of your children uh it's true then go for it then it is true for this note the problem is that um the problem is that i was just still trying to figure out like here like okay um in this sense because there's a second that first search uh like how do you maintain the state of stuff that you've seen and you haven't seen and you keep track of them together and that's what i'm trying to do here in a really funky way and i think that's and that i think like halfway through i'm like i don't know if i could like prove that this is correct or that like it's good enough to be true so i'm just trying to figure out how to do it here um and i was like if i do this it might not be but then it might still go off the tree because or something like that um those are the things i'm worried about when i'm doing this just in terms of edge cases and carefulness uh and here i was like okay we don't want to create a copy if they're insane just so that uh it saves a couple of psychos but yeah and i'm still trying to figure out how to use this and i'm like i spent a lot as you could kind of tell i spent a lot of time thinking about how to do this mostly but because i wanted to avoid um i was obvious of just creating a tree myself and i was like okay if i just want to create this tree where it's a directed graph uh how do i go about that let's just go through a definite search and remove we moved to uh we moved to back edges up upwards uh starting from zero so that's what i did with the call of duty staff research uh it's a bit of a terrible naming uh but during the contest i was just like okay just get it done you spend a lot of time on this um basically you can see that for every node uh remove the back edges that are coming back from this or to this edge uh and that's what i do a couple of things is that you notice there's a typo uh and also we're using this so i was like okay actually i could just convert it to a set uh which i do in a second after i fix this code so the recurrence is right and maybe that's a problem today in general i feel like i got all the algorithms pretty quickly i'm pretty correct at the end uh but my implementation is just it's just off today uh which i guess maybe you just have one of those days sometimes um yeah and now i just spent um yeah i noticed that i used the wrong functioning bit but yeah i spent too much time on this in general because here i should have been able to submit if i was correct uh there's no set so uh yeah i have to change the function name okay but now maybe i should be able to submit if i was um accurate but if i get maximum depth recursion which is actually having a blessing in disguise because uh for a hundred thousand actually i think if this didn't if i didn't have it in a weird way if i didn't have an infinite loop um i would have gotten a wrong answer because of the recursion debt because i forgot to think about it uh and now i'm just copying the case from before because i was like oh actually n is it was a reminder like i knew that it wasn't going to solve my issue but it was a reminder that um n is ten to the fifth or a hundred thousand so i need to do this thing anyway otherwise it's not going to make it i just chose some really big number it actually doesn't really matter what the number is as long as it's bigger than what you need uh because at some point it would crash uh without memory anyway so then like yeah for competitive programming it doesn't matter i guess it's maybe a better way of saying it because it just wants our memory before it runs off stack uh but yeah but now i'm like wait why is this not working see if you can spot this bug that took me a couple of minutes um and i comment that out just in case so that well just so that printing is a little bit easier and i was like okay this is definitely going back and forth so the difference now it's like okay wait uh what is wrong with this well the thing is that you keep on calling itself i ran it again uh still the same thing and i was like ah why do i have another bug yeah i do have another bug see if you can spot that one too but yeah so in general uh yeah i mean there'll be an explanation later you know maybe quick forward in the links below but that's kind of my thought process for this problem yeah after printing that out i'm like oh this doesn't print at all because we don't call it at all so that's the bug that took me a couple of minutes so just a lot of silly uh implementation things that uh actually when i ran the code i was like oh i'm surprised that this actually uh i'm just surprised that this actually uh red and then put back the recursion limit and that i mean i'm also surprised that to just run the first try kind of after that because i just struggled a lot uh so i submit add two q3 minimum time to collect all apples in a tree um yeah i end up taking 10 minutes on this one i should have been faster uh so for this one given an undirected tree you have zero uh i was that i was just a little bit careless today i think or a little bit off it happens we have off days and you know because i because yeah i mean you have off days because i think i just have like little weird things like here i spent some time debugging the fact that um yeah i just had to debug um i just had issues debugging that dfs i just forgot to call this and because everything was uh depending on that part it took a long time to debug but yeah to actually explain the problem again uh minimum time to collect or apples in the tree so for this one that the way to solve it is uh i mean the way i solved it more specifically i did a different search or breakfast search mean i did a different search you could use a breadth research to get an ordering of the tree and what i did is that i just make sure that the tree only goes one way and once i have that uh basically you're given almost like an actual tree where you could only go downwards so because before that you may go into infinite loops which i did so for that we look at well recursively for each what is this thing right for you to know that you're given uh for each edge going outside that node um if that edge leads to an apple go down that edge so that's what the two is for because you need uh two one to go down and then another to come back up and then you know you just do that part recursively um and then the apple is just a difference a quick uh therefore search as well um where um i guess i could have done this recursively but i did it with lu cash because i was a little bit lazy um but you could actually prove that you could just do one recursive and the recursion in the beginning but basically it's uh this apple is not the same as the input apple my apple method is just to calculate whether this node and well sorry this note all is subtrees uh have an apple because if this note or any of the sub trees or children or whatever has apples or has one apple even then we have to visit this node that's what this function is saying um and that's pretty much it uh and because i memorized it uh this is gonna be linear uh because we only calculate once for each uh for each node and here's a similar frame because we're doing this is actually a definite search so yeah and this is definite this is just to give me an ordering because it removes the back edges going upwards uh and i do that recursively and that's why i changed to a set um i'm not sure why i took 10 minutes on this one but i think i was just being a little bit careful and i was a little bit silly with the depth research so i just didn't call and i was printing things out trying to figure that out uh yeah so it's been a while since i did one of these um code reviews so let's actually do a couple of code reviews and see where i can learn because i definitely did not solve this for uh contacts very well i end up at 175 or so okay q3 what was my q3 oh yeah that's the three one uh okay now this is way too long this is yeah so i think i actually noticed this be uh and i didn't mention this because i didn't do it that way but because it is a tree it is good enough that when you do a definite search um that you don't go up the tree and what i mean by that is that and what i mean by that is it's good enough to just keep track of your parent so and then not go to your parent so that you always go downwards so that's a common recursion thing but unfortunately i wasn't able to uh remember that one i guess it's been a little bit and i need more practice on that one but i mean i did something else which is okay but not great um but yeah would say my same idea except my implementation is bad uh so i did learn that i could do that so that's kind of cool thing to learn uh or relearn i think i used to do it but i don't know today implementation is not my skill uh and a lot of people you see are doing the parent trick um yeah okay could have done that way as well there are a couple ways i could have done it i did it a silly way uh and yeah this is wow it's really short and that makes sense actually instead of using non-local or something
|
Minimum Time to Collect All Apples in a Tree
|
minimum-distance-to-type-a-word-using-two-fingers
|
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._
The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple.
**Example 1:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,true,true,false\]
**Output:** 8
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
**Example 2:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,false,true,false\]
**Output:** 6
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
**Example 3:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,false,false,false,false,false\]
**Output:** 0
**Constraints:**
* `1 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai < bi <= n - 1`
* `hasApple.length == n`
|
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
|
String,Dynamic Programming
|
Hard
|
2088
|
929 |
hello everyone so in this video let us talk about one more problem from lead code the problem name is unique email addresses so let's go to the problem statement uh it is a problem also in different interviews so stay focused uh the problem statement goes like this that for every valid email consisting of a local name and a domain name so and it is separated by an at the rate sign so beside lowercase letters an email may also convert con like consist of dot and a plus sign so that given different examples uh so as you can see that this is one of a valid email type and alice is the local name and is the local name and is the local name and is the domain name fine now if you add period as you can see or dot between some characters in the local name part of that email address mail sent there will be forwarded to the same address without the dots it just means that uh if you insert a dot or not insert a dot before the ampersand sign or like the uh at the rate sign then that is equivalent only okay so what it actually means like you have inserted a dot not inside your dot they both point to the same email addresses according to the problem statement okay but it is only uh applicable for the local name not for the domain name if there is a domain name that has dots then they both are different so and different so and different so and lead. are two different like our lead. are two different like our lead. are two different like our domain names but alice dot z and alice zed similarly for the plus sign so if you had a plus sign in the local name everything after the first like the first plus sign will be ignored okay this allows certain emails to be filtered so it doesn't apply to the same to the domain name only the local name says that if you have like this so whenever you find out a plus sign that actually means after that all of them are ignored so as you can see and both of them can also possibly use so dot and plus can be or like both of them can also be used so m dot y is just like m y and after plus all the characters are ignored till the ampersand sign so as you can see at the red sign so fine and then the uh domain name so this is the problem statement now given different emails you have to find out how many different type of email addresses are there now there can be multiple ways to solve this problem out i'll tell you two ways okay but let us talk about the first way first uh so what you can directly do is that you have to first see that uh there is no alpha like there's only alphabets there's no numbers also okay so because they're the only alphabets what you can do is that if you find it like a period or a dot then you just ignore it if you have characters just push back into a new string whenever you find out a plus sign whenever you find a plus sign just keep on ignoring all the characters till you find out and at the rate sign because and whenever you find an ad rate sign then after that whatever string is this just completely put the entire string because after that the rate sign then you have to take the old domain name because in the domain name all of these rules do not apply so whatever is a domain and you have to completely take that so uh what's the overall rule here that uh whenever you like before the plus sign whatever is there keep on taking that after the plus sign don't take anything like after the plus sign and before the absolute sign just don't take anything and after that it signed whatever is there just take it everything that is the overall idea now however like however you want you can do that the second approach can be that uh like iterate from the back of the string and keep on popping out elements like in a string until the at the right sign so because before that sign you have to take everything out so what you can do is that take out everything before the algorithm okay you can use a substring function to take out all the things before the update part now if you have extracted out before the other eight you only have the like the local name so you have two parts local name in a domain name you have extracted out the domain name such that you have the string like keep on popping out the elements from the back and you have all the domain name you have now you have the local name so for the local name what you'll do you just iterate from left to right in the local name like till you find out the plus sign if you find out the plus sign just break out of this for loop if you have dot or plus just keep on appending the string and now you have the like the local name and domain name attach them out you have the final answer so there are multiple ways and you can use any of them so that's the overall idea how you can approach subscriber problems let us move down to the actual solution now what you can do here is that because you want different type of strings in the end whenever i see like and whenever i find out a term that is different and you have to count on different number of types of things uh the first thing which comes to mind is set because set comes very handy here so i'll just create a set of strings now whatever quietly what we'll do here is that we'll iterate over all the emails and we'll create an okay means key whatever is the final okay uh email that will be formed after converging of this string so there's a plus and the at the right sign so both of them are false initially and what we'll do here is that it read over all the uh characters in the given string so if i find out the address sign to be true okay then i'll keep on appending all the characters after that the rate sign no matter what and just continuing out so appending we don't have to talk about anything else okay so if you find an address sign we'll make that great sign true and just append that red character okay if we find out the plus sign true then we just keep on continuing out we will not add anything so this is this containing order and if we don't find the plus character and the other character we will just keep on appending the characters as we are and whenever we find that plus character will just make it true so the order of the operations matters so if i just put the plus sign up like on the top or the other side of the top then the order might differ but uh you have to just keep in mind that the whatever order you are like taking out these conditions should be correct this is one of the like options you can do or second operation i've already told you that just keep on popping out elements from the back and then you have the domain name and for the like local name just right from left right till the first plus sign you find out so these are the two options and then whenever the final string is built just insert the final okay string into the set and in the end just find out the size of the set that is overall solution for this problem other than nothing was complicated but uh it just helped you to build logic because these are easy problems but still they actually help you to like move around and see how you actually can find out solutions for easy problems as well but tricky in some sense so that is the overall like logic and idea for this problem i hope you understand it and thank you for watching this video till then i will see you in the next one thank you for watching and bye
|
Unique Email Addresses
|
groups-of-special-equivalent-strings
|
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` and `"[email protected] "` forward to the same email address.
If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` will be forwarded to `"[email protected] "`.
It is possible to use both of these rules at the same time.
Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_.
**Example 1:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 3
**Constraints:**
* `1 <= emails.length <= 100`
* `1 <= emails[i].length <= 100`
* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`.
* Each `emails[i]` contains exactly one `'@'` character.
* All local and domain names are non-empty.
* Local names do not start with a `'+'` character.
* Domain names end with the `".com "` suffix.
| null |
Array,Hash Table,String
|
Medium
| null |
327 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now you'll be ahead of me 3:27 can arrange some be ahead of me 3:27 can arrange some be ahead of me 3:27 can arrange some given an integer way gnomes we turned a number of rain sons that lie in lower/upper inclusive when some s I J is lower/upper inclusive when some s I J is lower/upper inclusive when some s I J is defined as the sum of elements in nums between the index I and J inclusive okay I did that hint thing my friend could never get 80% on her ap bio test and never get 80% on her ap bio test and never get 80% on her ap bio test and she's got a hundred percent on the most difficult test of the year yeah that happen I mean if you watch my stream sometimes you see that happens to me right we're like on a hard problem I solve in five minutes and then on the honor on a coin code um double-length honor on a coin code um double-length honor on a coin code um double-length less problem I took like half an hour so it's just sometimes it is just practice a little bit because even if you know the answer like you know like they being able to articulate it and in programming diamonds coding it you know precisely it means something yeah okay so the first thing I usually think about when I come to this is like pre prefixed some does that help so prefix some allow us to most of thinking something about like the binary in that Sri which we talked about a little bit earlier on the stream but with negative numbers and without coming to bounce is hard to kind of figure out how to do the binary index tree but let's see so I definitely want the prefix psalm I think maybe so yeah that's a little bit tricky with some but I think what I wanted to do is basically I don't have to formulation yes I've basically some lookup table so you can look think about like okay because I'm thinking something similar to dynamic programming where you like well what is the number of count of sub so there is a known problem which is not easy but it's known ish but it's not dad known so but it's known to me I guess problem we're like well given an array of numbers try to find the number of sub arrays that sums to a given target right I need to do that with dynamic programming in of n times but I am trying to because in for this problem you have a range as I'm trying to figure out if there's a small way to leverage some sort of log n e algorithm oh maybe huh can I do something like a prefix some of the prefix some that would be interesting take the prefix some you do the lookup table and then you do a prefix someone that maybe yeah I think so I'm doing this live and I have not seen this one before so if you're wondering why I'm just like thinking I'm just literally thinking through how I would think about if I'm on a contest but basically okay let's get the prefix on them let's get the prefix um up first you go to zoom time and someone told me it showed me a clever way to do perfect some in one line but then I forgot it so yeah okay so now we have to prefix some what does that mean right Bobby obviously it's wrong and zoom it so this gives us to some it's an entire summers I guess to actually fritz so as you insert it so as we cut late this prefix some so the idea behind this is that you would add something actually this is the prefix some but let's together a running count alright so like I don't know how to express this I'm still half thinking for it let's say you have this number as you well I'm just more equity you have these numbers so when you get the negative one you're trying to basically do a query of the count of numbers data between there's some inverse thing in it in here but basically doing query between numbers that are and maybe I get the signs wrong but between like negative 3 and 1 or something like that because and the number of counts on those and you could solve that with a segment tree actually now that I think about it I suppose so what it's not true and I'm just more I'm just making it up yeah because you look at negative one and then you look up to syntax actually sorry the negative one will get you like I need the inverse of test so maybe I need to suffix so that you can do the query going for yeah that is weird well now we are just horn maybe just use the prefix some directly so given that the current sum is 2 well you know that you know well you know that there is a sequence data yeah actually I'm thinking and talking yeah I'm just going and oops it is hard that is why by the way that is why when I'm on a contest I am able to solve these much quicker because I also on a contest to be honest like sometimes I don't move I don't prove something correct if that makes sense like sometimes like ok I have an intuition that's why right but like I feel like when I'm on stream i'm explaining I'm like gonna I'm trying to like make sure I prove it a little bit first before like yoloing ok so given this prefix I think so I think there is something to kind of divide from this prefix um because given this prefix what does this mean right that means you want to do a query so the of numbers that I the numbers that you've always seen between the tween negative four and zero because negative four plus two is equal to negative two and then zero plus two is equal to two and this of course is to input lower bail and this is the upper bound so given that we just have to hash this in a way or excuse me or more precisely I mean yeah so I'm I think that's essentially a segment tree I'm also just trying to lazy and not implement a segment tree because also in it if this is a segment tree then I mean on an interview that would just give up but by Delhi index tree which I guess a little bit of foreshadowing is what I did earlier but with negative numbers there's a little bit trickier I guess actually if I used I guess I could just use a regular tree okay I'm going to switch languages even though I love pipeline just because I don't want to implement any tree but I think maybe I can leverage maps in C++ okay so let's do that right and now I'm thinking - you need to prefix some away thinking - you need to prefix some away thinking - you need to prefix some away so you know just to uh I guess I don't I just need to run in count and then put that in a tree switching languages sometimes a low top all right okay I'm gonna put this so let's keep a map what a multi map actually or what he said yeah it's a multicenter low tide 20 and insert I can go to zero and then after this is roughly something they're just a thing no I guess this is actually one in count running some I just got something because I'm gonna I should use count and that would make it confusing and now I have to get the sides wide that's a little tricky is for me because I sometimes have trouble visualizing this but this is - it just I have just open but this is - it just I have just open but this is - it just I have just open up and in theory I would also done in theory but in general I actually have pen and paper to kind of help me visualize this but how many numbers are between so we want am tight lower bound it's not all about which one is know about yet wait maybe I'm doing this wrong just have moti's map I hope so but the current so this is lower so if we want to add lower and then I can actually take the negative of this sign okay so that's the bang that we're looking for and then we're also looking this gives us what kind of in a multiset what kind of iterator does that give us I should forget instead of sorry friends a lot these days a bi-directional mmm so a lot these days a bi-directional mmm so a lot these days a bi-directional mmm so I guess my question is where I can do something like this that is longer Brown and then now we want to find the upper bound which is I guess the same logic can I do something like that I don't know if this is quite syntax correct there is a thing for calculating the distance between two elevators right on my finger of someone else Kirstin debt in theory this will be like and for each of these the exact same tax now yeah it's been a while just toying with scent I say we turn to an elevator and I thought you could just subtract Raider oh you still a distance what am I thinking of another language maybe okay fine I'll ticket if it works so did I not have a semicolon hmm no matching function testing wrong there's some like yeah and I might have actually have these backwards but see we're up were for shot oh okay I think you're supposed to put your first that's maybe I think that doesn't matter maybe they just won't have to figure it out but that's at least do that maybe I'm also off by one so this shouldn't matter but I just wanted a DS ever defend this a little bit time limit exceeded maybe I am wrong I didn't really change anything I was right whoops right good that's fine for now let's print it out I just want to do that's why did you so much C and C of no elements that I read okay sort of cut Crone Sami see negative - so this should actually it should actually be one because it shouldn't could itself well that's okay let's take a look at their dependent over there I'm looking for what so my thing my upper bound may be off by one I was thinking down a little bit you mean where else do it Zoe's okay I forgot to use more form a premise okay so for negative two it searches for four and zero is that right but it should find a zero let's talk about number one why is this returning to zero then I mean this should return the end of the multi set and there's some like weird stuff with the end of it maybe I need to do thought you'd still maybe return em got end but it's the distance not going I'm done huh thanks doctor you and that well I'm just always cool in my ways why doesn't let me try actually what does that what does y'all do if you I should don't know see how that Wow maybe just meet like something like that does that work I should not know how the magic I guess they just cause - I think yeah well okay then is it does nothing for me hmm okay well it's that time we exceeded maybe this distance function is a little bit weird everything I know okay so testing actually is not all of one anyway it just uses to increase operator repeatedly but for me is not super helpful in terms of where okay fine also I get the direction well I think this is a case where I know the algorithm bit and implementation is always trickier and think about what I want to do this the idea is okay oh yeah wait I told you getting some like this multi set but I don't remember do I need which record yes I country I'm not I haven't done a segment we in the trade decades and it's funny because I think I'm box was talking about it yesterday but I think I would actually I mean for sure I think that would solve it but it still a non-signatory why I'm doing it okay I need to be very small and I okay so I gain nothing by having it in English McCoy but in C++ I'm just thinking about what are the other ways of doing it maybe I'm maybe I could do some sort of binary search I mean you said raised the same idea but then the part of the binary search you have to keep their way in a good place or sort it which is essentially why I'm doing this wave the binary tree ish because that's natural and we're like this but uh let's do yeah I gotta go buy one okay always forget minded you stop when his youth longer it's not fast enough I have some questions actually oh okay maybe I'll worry about it have to get away oh yeah I knew that okay so zero doesn't touch that soon but the tears tense hmmm off-by-one again the berries are soon so some whistles why should it not return I guess these are the same numbers that's why one of my inputs I need someone like this first one or something oh my god yeah I had that but I had to really confused upper-bound I had to really confused upper-bound I had to really confused upper-bound know about because I'm taking the negative of it then now I have too much so what hmm well I have no idea why is well that's why I have dumped about I suppose let's just wrap the bell propellant here by accident before the cost in negative numbers I should have swapped them but okay so that's still well but maybe hopefully a little bit more right but why am I getting what we're getting for here so X returned one two three Oh which one's self warden zero which is flying so the falls I find one that's good it was even in the description way negative 1 to the negative 5 to negative 1 which is true I guess because there's one version negative 2 but I don't think that should since we turns to it so that designs well I guess I've signed the wrong that's why I was struggling a little bit cuz would use one I guess that was one of the things that I was a little bit worried about in the beginning which was the signs okay let's print it out let's submit that okay I'm happy that maybe oh no overflow okay fine yeah they don't tell you I blame it on them okay cause this count should still be okay everything you know is It's Made okay hey how you doing Yas and dente huh hope you have a good night so I having I'm really close hopefully so we finish this prom okay I thought about this before that's why well as I go if I don't need it okay that's good yeah I mean oka and then this was a very hard problem for me anyway I think I knew how to do it well this I have the idea behind it but um and to be honest I think mine is a little bit how do you say this is almost n square you know it's not deny even square but because the distance actually walks to tree instead of getting some bounds which using like a segment tree or something like that you could get this in of log and time instead of maybe oh and but yeah you think of a segment tree or some sort of binary search tree with and you would have to kind of implement the binary search tree by yourself I would say yeah you could do this in n log n time I don't know if I have done much I don't know how much tips I and this is all and in an insert ology wheel again I don't know how many I mean how many tips I have to be honest because you because if you watch this then you know you see me struggling I actually got this I want to say that I did get disliked relatively quickly in algorithms and not decoding I think I was having one thing that I like to for me to add to my to-do list is to just like really study to-do list is to just like really study to-do list is to just like really study segments we have I had segment we like hey I know how did kind of do about him and come on in years and yeah it's not a trivial thing to implement for memory and he's not for memory when you don't have an in memory but uh so I think if I had that then this is like you century there's like we use a segment trees and you I can into it to an increment on there some and then there's like get something and then that would give you an eccentric old looks very similar except for it's backed by a segment tree that if you use it as a abstract data type that's how you would look but I think yet my evolution of how to kind of yeah if you get this on interview you're probably not having a good day anyway so I don't know I mean I think I say that a bit but I think like unless you've really strong on like a lot of other algorithm stand I'm not a fan of segment tree of binary search trees and those things or so I binary index tree binary search tree is for your game I suppose I reason terms of talking about it no one I think no one expects you to implement a balanced binary search tree in an interview but you play expect at least be able to talk about articularly yeah and I think for me the biggest thing was just going through the prefix some discussed that because prefix summer now to answer queries between you know of one time to sum between two indices and from dad it reminded me of that in a classic dynamic programming problem of how many subsequence some to a given target except for in this case the target is a range from lower to upper which for me suggests like I mean whenever you see these like up and lower things maybe not all the time but because sometimes if the doubter is small enough you could do something linear but for me if there's some sort of ordering that we can take advantage of then it suggests some sort of trees and you can kind of reason that about because like and I kind of used analogy a prefix some of a prefix some and in the way that do you if you think about particularly but yeah if you look at the prefix summer way which I have some way actually yeah like I mean I think I essentially I mean I've actually explained this Parliament made my signs were wrong which also cost me some time but Jeff you know this prefix some in order for this - I guess that's where I order for this - I guess that's where I order for this - I guess that's where I got these signs but I got some signs wrong but essentially you've won given the number - do you want to subtract the number - do you want to subtract the number - do you want to subtract that's why you want to subtract a prefix such that the remainder which is to sum between the index and your current index is between the lower and upper and because you know the low enough but you could just do the math backwards I mean I quit either not because I can't assign as well but that would be my idea and I would kind of think about it yeah hope that makes sense to a lot of I think that's I mean for me and you kind of see my logical progression but it's clearly not using each other maybe the first couple of steps are kind of things too I would maybe expect someone to get prefect some for whatever reason it has become very popular and it's just like a very simple coin called dynamic programming slash query lookup slash pre calculation type things that comes up some time to time so that definitely something I would study the China even the dynamic programming thing where like number of sub sequence or yeah sub sequence that was several ways that's some still target even that it's a little bit on the hotter side I keep anyone comparator programming I feel like for whatever reason they expected everyone to know it by now but I think it's a little bit non trivial I mean you just have to learn it for a competitive programming for in three years I don't know why what and then from that you have to do in order prefix some which you can do which given that is if it is static then you have done a prefix someone down and into a binary search to calculate the number between two numbers like basically just like an array and then you just get the bounds and that's you know login you said you also likes kind of dis really we're just giving in a no way but because we have an insertion dynamic the prom dynamic and it forces you to add numbers between or well one number well it force you to increment a number of from in this case my rainbow of some all the way to infinity and in the sense that like you include one by all those things which is something that is taking which is a property that segment we type problem ourselves for you which is how I make that leap but yes so there is a lot of steps to solve this problem and like I said give it up you got all that on the outgoing side the implementation is in Trivial either given that I did in a cheesy way that's not technically and login and that's why the code isn't it's just it's way faster than and a naive n square but it is not strictly om again but it is a faster and squared per se as a result but um but yeah I think that's why I have about this poem I here's a hot one so definitely uh I would wait until you know with you wait until you're good at everything else before suffering with this problem I think I'm not everything I was but like others similar level problem was I think if you're studying for an interview then there's a lot like I would rather be like get my foundation on something as trivial as binary search like that foundation stronger rather than like wondering what would happen if just shows up on an interview if that makes sense cool you can also do K order statistics with these prefix and subtracting prefix uh yeah and I think that's essentially what I'm trying to do but because this is dynamic so yeah like you have to do it dynamically as you insert more and more numbers so I think that's the tricky part
|
Count of Range Sum
|
count-of-range-sum
|
Given an integer array `nums` and two integers `lower` and `upper`, return _the number of range sums that lie in_ `[lower, upper]` _inclusive_.
Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`.
**Example 1:**
**Input:** nums = \[-2,5,-1\], lower = -2, upper = 2
**Output:** 3
**Explanation:** The three ranges are: \[0,0\], \[2,2\], and \[0,2\] and their respective sums are: -2, -1, 2.
**Example 2:**
**Input:** nums = \[0\], lower = 0, upper = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `-105 <= lower <= upper <= 105`
* The answer is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
315,493
|
264 |
hello guys welcome to algorithms made easy today we will go through day 4 problem from july lead coding challenge ugly number 2. please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update write a program to find the nth ugly number ugly numbers are positive numbers whose prime factors only include 2 3 and 5. in the given example we need to find the 10th ugly number which comes out to be 12. we are given note that one is typically treated as an ugly number and n does not exceed 1690. the naive approach will be to loop on all the numbers till we find the nth ugly number if the number is ugly we decrement the value of n and when n becomes 0 we return the value let's see how we can do it through dynamic programming wherein we will just focus on calculating the ugly numbers we will initialize a result array of size n and 3 pointers one for each factor to calculate the next ugly number we will use the previous ugly number to calculate the next one as given incursion 1 is an ugly number so we place it in the array at 0th index also all pointers will point at 0th index we will now loop from 1 to n on the array we will calculate the next ugly number multiplying the number at the pointer respective to the factor so the next ugly number for factor 2 will be the value at pointer p2 multiplied by 2 and same with 3 and 5. now as we have calculated the three ugly numbers we will take minimum of the three this minimum is nothing but the next ugly number so we put it at index i in the result now as we have calculated ugly number of the current pointer for 2 we have to increment it so that the next time it gives us the next ugly number for 2. so we increment the pointer for 2. we will check the same for 3 and 5 as well but as both values are not used till now we won't change the pointer for them this completes our first loop and hence the i gets incremented we again find the next ugly number and this time the minimum is 3 so we add 3 into result and increment the pointer for 3. now index is incremented again the minimum is 4 so we add 4 in the result and increment p2 for index 4 we will do the same now we have a case where both result of 2 and 3 are equal to minimum in this case we increment both pointers moving on we continue applying the same logic we have reached the end of the array and so we return the last value which in this case is 12. here is the algorithm we followed let's go through it once more we will initialize an array result of size n then we update zeroth index with one we will also initialize three pointers for all three factors and initialize them to zero now we will loop from one to n we'll first find the minimum of the three ugly numbers formed by two three and five we put the value into the result array whichever value matches the minimum needs its pointer to be updated so that it gives next ugly number in next iteration at the end we return the last index value the time complexity is over 1 because we know that the value cannot be greater than 1690 so we will calculate all the ugly numbers till that and just return the value at that index space complexity is of one because we have the constant array of size 1690. here is the actual code snippet from the method also check out the link to the java code in the description below thanks for watching the video if you like the video please like share and subscribe to the channel let me know in the comment section what you think about the video
|
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
|
1,187 |
hey everybody this is Larry this is day 17 of the leeco daily challenge hit the like button hit the Subscribe and join me on Discord let me know what you think about today's poem make a race strictly increasing okay I mean that's the title I have to actually wait for it to load don't know why it's loading so slowly internet technology who knows how that works we'll get something to drink while man uh everybody understood Amity here in uh everyone's doing all right oh geez all right assistant C plus oh no this is one of those poems isn't it um all right well I haven't looked at it yet so let's take a look so given two integer ways of a one and way two return the minimum number of operations to make oa1 uh increasing in one operation you can make a race of i as you go to a way to survive but they're not the same length foreign just because then um you know you want to do them in order so that uh now instead of keeping track of the subset of numbers you've used you only used either the uh you only use the prefix or alternatively way of saying it is you don't have the suffix left right so that's basically the core idea behind this one um sorry I'm at like 10 battery for some reason uh I'll be right back but that's basically the idea so then because of that then you could represent the number um the things that you have used in a way too with just one number instead of like a bit mask or something funky right and since the 2000 which is uh 2000 square it maybe by this is called tlu but give me a second I need to plug this in otherwise I'm gonna lose attack uh sorry friends I'm all crazy out of sorts uh yeah but I think that's after you make the observation about sorting I think that basically becomes more straightforward why is this cable so short let me move the table oh juice as you can see this is a professional stand up we're running you know oh geez why is this complaining angles there we go super professional video we have today uh anyway okay yeah so now you're representing the number of things you're produced in R2 as a suffix right why is that because in this particular part we're going to keep it strictly increasing and because we're strictly increasing after you sort it after you use a number everything's smaller than it you cannot use again right so that's basically the idea and that's basically the going to be the function we have uh yeah but basically we have um the number of operations we're trying to minimize and basically we can do something like Min I don't know naming things inside but get min and then you have the prefix and yeah basically i1 I2 right and let's define this a little bit i1 is you go to the index web processing in Array one I2 is equal to the first index of the suffix that we were that are available to use right like this and then basically yeah if i1 is equal to N1 is equal to length of bar one and two is equal length of r two uh if I wanted to go to N1 then what happens then we're basically done right so we return zero otherwise um so basically we're trying to see that the two things we want to do right we're switching i1 with I2 or we're not switching right um yeah and let's have an infinity number here so we're switching with i1 with by two um yeah uh then it will be getting Min I one plus one I two plus one something like this but not quite right because you have to do some checks to make sure that it gets bigger and stuff like this um I'm trying to think right now a little bit right hmm do I need to keep track of the last number hmm this is awkward isn't it yeah uh basically you want to do something like um I think you need another dimension of uh last number is I from i1 or I2 right so something like blue you know something like this but that already makes it complexity really crazy so yeah so basically um how do you want to say so yeah last maybe I don't know that's terrible naming but um you can also do this in two different functions if you like meaning uh get one um where you know the last number is from yeah is of A1 of I one minus one or something like this um and then you can have like a gammin uh maybe you can win last one or something like this last two I want I2 same idea right just have to write more functions okay then maybe in this case uh let's see okay foreign friends I walked 20 miles today a lot of it hiking but I'm still out of shape okay let me know I need code uh but yeah so that's numbers right so then now or maybe the last number is a way of yeah someone like this and then okay and then maybe reframing it we can go sorry friends I'm struggling but yeah we're using i1 and we're using I2 right that's basically the idea um so okay so yeah so the previous is equal to away one of i1 minus one uh unless i1 is equal to zero I guess so yeah maybe this is sloppy right all right one right so if okay so best is to go to Infinity right uh infinity moves we're using i1 so if all one of i1 is greater than the previous number then we can use best as equal to Min best and then we the last number is going to get min last one of I one plus one and then I2 we just don't change right uh else if away two of I two is greater than previous and best is equal to Min best get min last two i1 I2 plus one do we ever want to skip numbers so we know well we can't skip I one we can't skip any indexes on a way on i1 so yeah and also in this case I got it wrong because we skip the number on i1 so then now we'll reduce the number from I2 but I one cell gets consumed so I think this is precisely and also in this case that we get plus one for the switches right yeah I think that's right uh we have to do some checks that I too is um that's the link we've got two I guess right and yeah so you never you can't Skip by one because that's the point of what you're doing and I too it never makes sense to skip well in this is the current number is bigger than you have to go to the bigger but yeah um in that case you can just model it by doing something like this i1 and I2 plus one right because basically this is just does nothing but skip I2 I guess in this case maybe if all two of I2 is less than previous uh then we do it this way um yeah so that's the I that's the when the last number is win one and we do it the same with uh I2 right so if i1 is equal to N1 then that means we're done um less is equal to Infinity same thing right well I too cannot equal to zero because that makes no sense so that's not a possible case so previous is just you go to um because you can't reach that from anywhere uh you can only yeah you'd only go last two after jumping one so previous is equal to R2 of I 2 minus one and that same logic so we're using I want right then that's fine then we go back get me last one I one plus one I2 right I2 instead then yeah same thing nope what am I doing I'm just writing like so you can see that the code is actually very similar uh so maybe I could have combined them but oh well it's too late I'm committed foreign I guess it just changes the previous so we could use the flag or whatever but uh but maybe this is better for teaching I don't know let me know in the comments if this actually helps at all uh yeah and then we started by getting in last one zero right that's the last number that's running real quick copyright as an infinity and apparently um it does return Infinity at some point oh wow that's fine it's just that you know result is equal to this if all is greater than infinity then we return negative one otherwise we turn uh it might still be wrong but at least it fixes that case um okay so we return negative one for everything that's not super good one third of the answers right but uh yeah that's basically the idea we have to fix some stuff uh hmm foreign memorization but hmm what am I doing well why is it not returning zero we don't even use N2 I guess I mean we could we just didn't all right fine oh this is wrong this is last two because we did nothing um with that we'll fix it that is a bad typo because that's supposed to be a no operator Skipper thing but maybe not still you place five of a two okay so this should go in here um I think this is also equal to that I don't know if that fixes it but that's definitely just wrong uh okay I mean it's one for other reasons so yeah uh okay hmm why are you oh the logic should be right oh is it oh what uh I mixed this up that's why okay there you go oh wow how did I mess that up all right so that looks good usually I do a little bit teaching about how to do caching and memorization again I hiked 20 miles today I knew I need to sleep so I'm just gonna go over uh caching another time uh if you struggle with what this is um I don't know uh I mean I'll make it up to you in the future with more dynamic programming things but today oh look today's actually worked out did they change to did I change the time or something like this uh it seems like I did this during the contest and I got my wrong answer is wrong answer but that time limit exceeded what did I do oh this is actually pretty much what I have now so this is contest code and give me time limit exceed it still time to minister until I use C plus so I don't know what to say I actually also re voted to be bottom up and still time limit that feels like a sad contest in the past in any case yeah this is going to end Square time and Squarespace sorting Square sorry it's n times m um and we do guess I guess if you will then it's gonna be n times M plus M log M for the Sorting if you want to be one to be precise and you should be so yeah let me write it out of n plus M or sorry of n times M plus M like M time and space is just n times m space um times two but obviously the Big O hides it I'm really tired sorry this is a crappy video um man hopefully I will get back to a regular schedule soon uh but for today that's all I have uh I promise I'll bring some good drone videos to compensate a little bit uh but yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Make Array Strictly Increasing
|
print-foobar-alternately
|
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9`
| null |
Concurrency
|
Medium
|
1203,1216
|
1,689 |
Hello Everyone Welcome To Our Channel Switch Sunny And Skill Develop In Talking About The Very Easy Problem Chopped Beans This Problem Through Synthetic Partition In Terminal Number Desi Boys Numbers Index Number 8 And The Problem Of Medium Time But It Considers It's Okay Solved Problems So 9th Basic Concept Was Happening Well What Is The Relation Between Davidson More Problems Very Easy And Simple Number Three Fatty Acids 000 To z10 Subscribe My Channel Subscribe 0 That If Stress Given A String And At Present Spots Decimal Teacher Returns The Minimum Number Of Positive Energy Numbers Needed Research A Sum Of Two And Okay Sorry For The President Of The United States Should Not Give Subscribe And Subscribe To Just Out Of School Has Been Given A Single Entry That Single String Gas And Specific Playlist Se 600 Your Thursday Subscriber 12512 subscribe to The Amazing talking to digit like subscribe and half forest officer dr scientist jersey i10 sportz vve fight 69 position in what is this what did it can impatient 12345 13151 appointed subscribe this Video subscribe 21 2012 person movie banner strings of 18101 time when 100 Talking ID Position Has Already Subscribe 1000 Modified Cars Subscribe Button Siro Withdrawal No Return Matching With His Wonders Number Is Not Meeting With This Term Point To Take One Extra Number Ok What Is The Number 100 Gram Paneer And Subscribe 100 Gram Paneer Subscribe To That Anna Future updates to streams and medical value of this true strength will get you dance register number recipe undhiyu subscribe 600 subscribe on this number and whatsapp number one official subscribe this number operations will be maxima and minima this number operations at my place to make 10 days slicer hormone impatient person subscribe and subscribe to subscribe Video position more number of minimum number of subscribe 210 present Indian original spring set you can see the arrival of aapko itni servi absolutely minimum desi boys appointment 12321 more subscribe The Channel subscribe our Channel Distic in more subscribe comment and subscirbe subscribe to ok sorry yaar par luta do it minute to comment section mein de video bana vela sabi aur silai this video share this video subscribe my YouTube channel latest updates thank you for watching this video jhal
|
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
|
847 |
hello everyone welcome to day 26 of every record challenge and i hope all of you are having a great time the question that we have in today's shortest path visiting all nodes after a very long time we are seeing a graph problem that you have hard category and i promise it's going to be an interesting solution for all of you so do watch it till the end here in this question we are given an undirected connected graph of n nodes what we need to do we need to return the length of the shortest path that visits every node also it is given to us that you can repeat the nodes repetition of nodes or edges is allowed in the graph traversal so here they have provided us with few examples i'll be walking you through these examples as well as the approach to go about it by the presentation so let's quickly hop onto it shortest path visiting all nodes lead code 847 so let's shoot for understanding the second example and then we'll move on to the first one here the graph is given to us are something this the shortest path possible would be from 0 to one to four to two and two through three how many nodes have we covered in this iteration we have covered all the five nodes specified in the question zero one four two and three and in this path how many edges did we visit we visited four edges as a result of which the answer becomes four one two three and four from the hint of it we can think of using bfs reversal but will that always work the answer is no we have to do some modifications to it what are those modifications and why are those needed let's walk to the next slide so let's go back to the first example because it is very interesting and it gives you a lot of hint uh here in this node we have zero and it is undirectedly connected with one two and three so what would be the shortest path possible so let's walk through few parts uh we can start from one from 1 we can go to 0 from 0 we can go to 2 from 2 we go back to 0 and from 0 we again go back to 3 how many edges have we traversed in this iteration 1 2 3 and 4. so the answer for this becomes 4 also in bfs typical approach we don't revisit a node however we are revisiting a node here in this iteration 0 gets repeated twice the path is something like this 1 to 0 to 2 then 2 to 0 and then 0 to 3 so this happens to be your actual answer path and here you can see that we are visiting 0 more than once in the iteration that simply signifies that the typical way of maintaining the visited array will not work let's walk through another possibility of the answer let me just change the color of pen and let's try to start the iteration from 0 instead of 1 so what would be the path needed for us to cover all the nodes we'll start from 0 and what do we go to 1 so 0 1 then 1 2 back to 0 then from here we go to 2 from here we go back to 0 because we have to visit 3 and from here we go back to 3. so in this iteration how many edges have we covered 1 2 3 4 and 5 which happens to be greater than the previous edge count that we calculated which was 4 that means in order to conclude the answer you have to start the iteration from each and every node we need to start the bfs iteration from each possible node given to us otherwise if we miss that will lead to incorrect result we will not cover all possibilities for of answer and among all possibilities that we generate we need to select the one that gives us the minimum count what is the next takeaway from this analysis the typical bfs approach doesn't work in typical bfs approach we treat and create a visited node set and once we have visited it we don't revisit it again so we have to avoid that because in the question itself said that we repetition of nodes is allowed and edges is allowed also we have to avoid in indefinite loops for example instead of going up till 2 here we could have landed upon one for example we could we started from zero we went up till one then again we bend back to zero then again we could have landed upon one so the whole recursive loop is getting formed 0 1 and we have to avoid this indefinite loops so these are the three takeaways and let's look at this solution for enhancing the bfs to actually come up with the appropriate approach here i have listed those three limitations you have to start bfa starting from all the input nodes that are given to you bfs with visited node will not work and you have to avoid indefinite loops we will be taking help of bit manipulation how let's have a look at it so what is the final state that we are trying to achieve we want to visit all the nodes so when we say we want to visit all the nodes can we represent this in a form of a integer the answer is yes let's hypothetically assume we are given three nodes zero one and two and what would be the final state that we are looking for we can keep track of all the nodes that have been visited in the form of a bit and the final state would be one that simply means when we achieve this integer value where in the zeroth bit is set the first bit is set and the second bit is set that there we can conclude that we have visited all the nodes given in your graph so the final state that we need to compare it with is something like this for this particular example if there are n nodes then first n bits should be set and that would be our final state so from the take away uh we need to start the bfs iteration starting from all the input nodes so what would be the initial state while starting uh the bfs reversal from zero the initial state would be zero one from here it would be zero one zero from here it would be one zero nothing rocket science we have been doing these kind of bit manipulations in the past also now let's look out for the last constraint how can we avoid landing up in indefinite loops and keep track of the visited nodes both of them can together be solved so let's look at one iteration so you start from the zeroth node you're starting from here and what is the current state of your bit number is 0 1 so let me just write that here as well and where are we going we want to go towards one so let's go towards one and here let's update the bit two 0 1 so it gets updated to 0 1 i think most of you will agree so far and where are we currently we are currently at 1 let's proceed ahead now again let's go back to 0 because so far we are having a valid state combination so let's go back to zero and what is the state now the state happens to be zero comma zero one 1 so the first number here represents the node that we have just reached or we are currently standing at and this represents the current state of your bit number and now let's again look out for all possibilities so there are two possibilities one we have to avoid and two we have to go for so let me just draw two graphs uh two parts and here what would be the next intended state we are going towards 1 comma what will be the state would be 0 1 and what do you see here that this total state has already been visited in the past which was 1 z comma 0 1 as a result of which we will avoid such a condition we need to keep check of both the state parameter and the next intended node that we are going to visit if the both the combinations have been visited in the past we should avoid it because if we go by this approach then it will lead to recursive indefinite loops what is the second possible state is you land upon 2 so when we land upon 2 what do we get 2 comma 1 which will lead to one possibility of the answer and here you can see in the past we haven't visited this state ever across these three possible states this is what we are going to do in the question we need to keep track of the nodes that we are visiting in the future and the current state value if its combination is already existent in the past we will not go for it otherwise we'll shoot for it starting from a next titration to conclude it further let's quickly have a look at the coding section if my graph dot length happens to be equal to 1 i simply return 0 because there is only one node in the graph otherwise then go and create the final state variable that i talked about in the presentation against which i'll be checking whether all nodes have been visited in the current iteration or not and it is simple we do what do we use a shift operation we do two rest about the number of nodes that we have minus one so uh in the example we had three nodes and the answer that we were looking for was seven so two raised to about three happens to be eight minus one will give you that final state going ahead i go and create the queue and here i have taken the generic type as array of integers and here uh it will have two parts the ith index and the bit state value what is the current bit state so we are going ahead and adding each node one by one into my queue so this is the id of that queue and this would be the current bit state where in the first case the zeroth will be set depe in the second case the first bit we really said in the third case the third bit will be set and the test will be zero and so on moving ahead here i have created a 2d array where the first index represents the ith node and the second index represent the current bit state remember in the presentation we had two variables when we were matching it the first one was the current node and second one was the bit state so this will help us keep track of all the bit states corresponding to each indexes that we have let's proceed ahead and now it's pretty simple and straightforward we will simply use the typical bfs approach that we usually write so i have created a shortest path variable that will actually help us return the answer and while q is not empty what do i extract the size and shortest path plus because we are going for the first iteration i pull out the topmost head from the queue this the first part will represent the id and the second part will represent the bit state of the visited node that we have been generated so far what do i go to the neighbors of the current graph i go and update my bit state value as uh given the fact that we are visiting the current neighbor and i perform the shift operation to update my previous bit state and generate the newer one if my visited map at the ith neighbor corresponding to this bit state so this is the same validation that i am currently doing that we showed in the presentation we had two very variables there the node id and the state value if the in the visited map it says it has already been visited will simply skip it up here i have provided us with you an example to walk through you can solve it by yourself otherwise if it has not been visited what do we set it up and once again we were gonna check if my new visited bit state happens to be equal to the final state that means we found out the shortest possible path value the number of edges that we need to visit and that will be given by the level of traversal that we are doing in the bfs transition moving ahead we simply go and add the neighbor and the new visited bit state that you have generated into the queue for the next citation in the end we simply return a minus one if you are not able to find any valid possible answer so let's try this up accepted it is 80 times 85 percent faster which is pretty good and in terms of memory it's also fine this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and if you are interested in more questions of the graph series i am attaching the link in the description below do check them out
|
Shortest Path Visiting All Nodes
|
shortest-path-visiting-all-nodes
|
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge.
Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\]
**Output:** 4
**Explanation:** One possible path is \[1,0,2,0,3\]
**Example 2:**
**Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\]
**Output:** 4
**Explanation:** One possible path is \[0,1,4,2,3\]
**Constraints:**
* `n == graph.length`
* `1 <= n <= 12`
* `0 <= graph[i].length < n`
* `graph[i]` does not contain `i`.
* If `graph[a]` contains `b`, then `graph[b]` contains `a`.
* The input graph is always connected.
| null | null |
Hard
| null |
404 |
hey everybody this is larry this is day five day four of the league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about this prom uh so is it four or four yeezy so okay i mean i found the problem okay but uh some of left leaves okay so yeah if you enjoyed this video so far uh well come to our discord channel come um do this month's problem with us okay so given the root of a binary tree we turn the sum of all left leaves what are the left leaves um like it's a little bit ill-defined it's a little bit ill-defined it's a little bit ill-defined is it just any leaves that is on the left node note okay i mean i think that's okay um yeah there are a couple of ways you can do it um i mean it's just recursion right and it's just depend the only thing that's uh tricky maybe is just figuring out how many if statements you want to write so yeah so let's just go maybe return go of uh and go i would say this is a node and if node is none just oops none just return zero otherwise we want to do okay it's not a left leave if no dot left is none and no dot write is none then we have to check whether this is left so return node dot value uh if left otherwise we return zero right otherwise we return go of node.left press go of no doubt go of node.left press go of no doubt go of node.left press go of no doubt right because by definition this is not a leaf right so yeah uh and here you may say how do i check this is left um well we can just add a variable for left so this is in the beginning this is if there's only one node it's true right i don't know if that's uh so left is true i mean just on the recursion this is going to be true and this is going to be false right i think that's pretty much it um i don't know if i got the one node case right up seems like one note you do not consider it true that's actually a little weird right because okay maybe not i don't know it's always a little bit awkward to kind of define some base cases sometimes in definitions especially when you're not really precise with what a leaf met um but this is good enough for me to give it a go because this is linear time linear space um maybe i have a typo but let's see and apparently i've solved it twice before so let yes i was gonna say okay i have a completion streak of 583 but we'll be sad if i broke this streak this time with um like getting a wrong answer i don't think i did it um but yeah but this is just basically what it sounds like you just keep doing recursion um it's linear time linear space or of h uh space where h is height but of course that could be linear in the worst case how did i did it a year and ago okay so i did it this a little bit differently i thought i would i thought i was thinking about doing it this way actually so that's why i was i'm curious uh and here as well huh i wrote exactly the same code the last two times but not this time so hey i wanted to mess uh mix it up a little bit i suppose but yeah that's what i have uh let me know what you think these are kind of a little bit easier i guess earlier in the month so this is a little bit short but definitely we're gonna do every prom this month hard or yeezy or everything in between so come hang out anyway stay good stay healthy to good mental health i'll see you later bye
|
Sum of Left Leaves
|
sum-of-left-leaves
|
Given the `root` of a binary tree, return _the sum of all left leaves._
A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 24
**Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
1,856 |
hey everyone welcome back and let's write some more neat code today so today let's solve a problem fresh off the leak code contest for today maximum subarray min product so this is a pretty hard problem even though it's categorized as medium and i'm just going to tell you that this is a problem that can be solved with a monotonic increasing stack basically we're going to use a stack data structure and it's always going to be an increasing order and let me just tell you that if you've never heard of a monotonic increasing stack basically you probably wouldn't have a good chance of being able to solve this problem on your own i've actually heard of this type of problem before and i still wasn't able to recognize that this could be solved with a monotonic increasing stack so don't feel too bad about yourself so we're given a definition a min product of an array is equal to the minimum value in that array multiplied by the sum of that array so for example this the minimum value is 2 and the sum of the array is 10 so we're going to take 2 times 10 then that's going to be 20. and so in this case we're actually given an entire array and we want to find what the maximum minimum product is of any of those subarrays of the given array so basically we have to try this computation for every single subarray of the nums that we're given and it might be a really large number so we're going to have to mod it by this prime number that they give us but this is just a minor detail we can worry about later and they tell us a sub array is basically a continuous part of an array such as this so let's start out with the brute force approach the brute force is actually big o of n squared let me tell you why let's just try every single subarray of this given input array so we're going to start here we're going to get the sum it's going to be 1. so far and the minimum number is 1. so we're just going to get 1 times 1. then we're going to add these two numbers right the minimum number is still 1 but the sum is now going to be 3 so 3 times 1 and so on we're going to add this number the sum is 6. minimum value is still 1 and then we're going to get the entire array but so far and we just did that in big o of n time right we were just starting at the beginning iterating through the end we did that in oven time but we didn't do every single subarray right we started over here now let's get every subarray starting at this value right so we'd have 2 is the minimum value so far and then we add another value 2 is still the minimum the sum is now six right and so on and then we'd get through to the end of the list then we'd want to get all sub arrays starting here so we'd start here and then go to the end of the list and so on and then that would be big o n squared that's not a bad solution but it's possible that this can actually be done in big o of end time and it's not actually going to be needing a sliding window you might think okay a sliding window will work we'll have a left pointer and a right pointer but no that's not going to work and let me show you why we're going to be needing a stack to solve this problem so as i mentioned we're going to be needing a monotonic increasing stack to be able to solve this problem in big o of n time that's also going to take big o of n memory because we are using that stack data structure but let me explain the logic the main logic that we're going to follow is we want to consider if each value in the input array like this 1 or this 2 was the minimum value of the subarray and then we want to make that subarray as large as we possibly can right considering if let's say 1 was the minimum value in the subarray how large can we make the separate if we expand outward and that's pretty simple right and we want to do that for every single value and once we've done that and then we get the maximum of all possibilities then we have our result right that makes sense so far so let's start at the beginning of this input array and keep iterating towards the right so first value we see is a one value right let's consider if this one was the minimum value of the subarray let's see how large we can make that subarray so we visited the one now let's get to the next value it's a two so notice that so far our input array is in increasing order right that's pretty important but why is that important because we're considering if one was the minimum value in the subarray we added another value in that value is greater so far our condition is true right we want to see how large we can make the subarray so for considering this one value so far we have a subarray right of width too but we don't care so much about the width of the subarray in this problem we care about the total sum of the subarray right so let's say our input array was still in increasing order let's say we had a 3 at the next position and even so this that three could actually be a two and we would still count that as increasing order because we're counting equal values as still considered as basically increasing order right and because for this one value we can continue to expand right why is that because one is still the minimum value of this subarray but what about two can we simultaneously consider this as the minimum value of the subarray as well technically we can't include this as the sub-array if this were the as the sub-array if this were the as the sub-array if this were the minimum value we can't consider this one as this as part of the sub-array but one as this as part of the sub-array but one as this as part of the sub-array but we can say that okay from where this two started the start value of the two so far of all the values that we added it is the minimum of the sub-array so is the minimum of the sub-array so is the minimum of the sub-array so this is very important for every value we're considering its start position as where the subarray for that value starts and so let's say this was the end of the input array how would then we compute what the possible result was because so far this is our stack and it technically is in increasing order well then in that case we would basically at the end we'd once again iterate through every single value of our stack this is what we would say okay for this one it started at index zero and it went all the way until the end of the input array right this was the largest subarray this value happened to be the minimum so we're going to get the sum of that subarray which is 5 multiply it by the value 1 and we're going to get 5 as a possible result we're also going to say okay for this value well it didn't start at index 0 it started at index 1 but it still ended up going until the end of the array because our stack was in increasing order so we're going to say that this was the subarray where this value happened to be the minimum and the sum of that sub array would happen to be 4 and the minimum value happened to be 2 so 4 times 2 is going to be 8 right so we actually found a value before we had five now our maximum is going to be a and technically we do it for one more value in this case but we'll see that this is going to be smaller right the minimum value this starts over here so the sub array happens to be this and the sum of that sub array happens to be 2 the minimum value is also 2 so we're going to get 2 times 2 that's going to be 4 it's not less than 8. so when our input array is in increasing order this is kind of how we can handle it but that's not always going to be the case what happens if our input array is in decreasing order let's take a look at that case and so remember what we're doing for each value we're considering if it was the minimum of that subarray so we're going to look at the first value 2. we're going to consider if 2 was the minimum of the sub array right and we know that this tube the sub-array the start of that sub-ray is sub-array the start of that sub-ray is sub-array the start of that sub-ray is going to be over here right because that's where we first encounter this two so now let's look at the next value one hold on a minute we were assuming that this two was the minimum of the subarray but we now have a new minimum we have a one value in the sub-array so what does one value in the sub-array so what does one value in the sub-array so what does that tell us that tells us that if we were considering this as a part of a sub-array sub-array sub-array that subarray has to stop before we get to the one so what we're gonna do in this case since our stack is not in increasing order we need to make it an increasing order so we're gonna pop this value from our stack we're gonna pop the two from our stack we're gonna we're and when we pop that two we're also gonna see that okay that the start value was at index zero right and we got to index one over here right this is index one so basically what we're saying here is for this two value which happened to be the minimum of that sub array it went all the way from index zero up until index one but not including index one right so really what we're doing here is once we pop this 2 we want to know what's the max sub array that it was a part of and then we want to compute what the minimum product of that subarray was so what we're going to do is then in that case what we're going to say is we're going to get the sum of the input array from index zero up until index one but not including index one and we're gonna multiply that sum by two because we already for this two value we found the maximum sub array that it was a part of and now we can we don't have to consider it anymore that's why we're removing it from our stack okay so we ended up visiting this one at index one and now we notice we have no more values right for this two we already considered if it was the minimum of a sub-array and if it was the minimum of a sub-array and if it was the minimum of a sub-array and we got that subreddit and we computed that total right but now we have this one right and since there's no more values left let's compute let's consider if this value was the minimum of a sub-array how large would minimum of a sub-array how large would minimum of a sub-array how large would that sub-array be well we notice we that sub-array be well we notice we that sub-array be well we notice we added this one at index one so can we just say okay this is the maximum sub array technically not because see we removed a value from our stack and that value was actually larger than this one so when we want to consider the max subarray that this one is a part of we're going to start extending it to the left as we pop elements right since we popped this one we're not going to consider this as starting at index one we're considering it as starting at index 0 right and that makes sense right because if you take a look at this sub ray 2 and 1 is the minimum value of this entire array so it makes sense that we would do that and what is the total that we're going to compute well when you take the sum of this sub array we get 2 plus 1 which is 3 multiplied by the minimum value of the sub ray which is 1 and we get 3 times 1 which is going to be 3 and that's not going to be the answer is going to be 4 that we computed earlier but this is just a little bit of the intuition behind the problem now let me actually show you what it would look like when we run through an example case like this and let me show you what exactly we're going to be doing with our stack data structure so this is the problem setup i have an input array and i'm going to have a stack but before i get into that let me just explain very quickly we know that for an arbitrary subarray like maybe this one we're going to need to be able to compute this the total sum of that subarray and we're going to be able to compute it quickly right because we're going to be potentially doing that a lot so there's a way to do that in o of one time what we're going to do is we're going to pre-compute the sum of every going to pre-compute the sum of every going to pre-compute the sum of every prefix so this is one prefix of the input area we're going to compute that sum that's one we're going to pre-compute the prefix we're going to pre-compute the prefix we're going to pre-compute the prefix like this which is sum three we're going to pre-compute to pre-compute to pre-compute the prefix of this which is sum six how is that going to help us potentially get the sum of an arbitrary subarray like this well we can take the prefix this that we computed and subtract from it this prefix right so that's just a little bit of the intuition of why we're using prefixes we'll get more into when i actually write out the code of this problem but for now we're just going to take that for granted that we can compute a sum of a sub rate and of one time so we're just going to be going from left to right in our input array so we're going to look at the first value it's 1 it starts at index 0. so what are we going to do we're going to go ahead and just add that to our stack so we're going to say okay what value are we adding to the stack we're adding 1 okay what was the start position of that value it was at index zero great and as you can see our stack is so far in increasing order so we're just going to go ahead and continue to add values remember an increasing stack is what we want since our input array is in increasing order we're just going to go ahead and add this value to our stack as well so we're adding the value two it started at index one and once again our stack is in increasing order so we're going to take three add it to our input array it started at index two so let's do that but hey now we finally got to a value that's in decreasing order so what are we going to do we want our stack to always be in increasing order so what are we going to do while the top of the stack while the top value in the stack over here is greater than the value we're looking at right now we're gonna start popping from our stack so we're gonna pop three from our stack and once we pop it from our stack we're going to compute since we now we know what's the maximum sub-array could possibly be a part of we sub-array could possibly be a part of we sub-array could possibly be a part of we know that we could not extend it any more to the right because if we did we'd find a new minimum value 2 and we know that it could not have been extended to the left because the stack was in our input array was an increasing order right so we would definitely not be able to make the sub array larger to the left so this is our entire sub array right so we're going to compute the sum of the sub array and of one time it's so it's just three right the minimum value of that sub array is basically the value that we just popped which is also three so three times three is going to be nine right so far i'm just going to put nine over here as our maximum so far now once again we're gonna look at our stack and see is the top value in our stack greater than the value that we're looking at right now it's not it's equal so that's perfectly fine if it's equal it can remain there but so now we're finally allowed to go ahead and put this value in our stack so we're going to add 2 to the stack and this value started at index 3 so am i going to add 3 as the start value to this stack we'll remember what we're trying to do here right if this value was the minimum we want to know what's the biggest sub array it could possibly be a part of if it was the minimum and technically it can be extended to the left right that's why we popped this value that's another reason why we popped this value because it tells us how far back can we take we know we're gonna as we iterate through the array we're gonna be extending this to the right if we're allowed to but we can also extend it to the left as we pop elements from the stack that we just did so since the last element we popped was started at index two right that's what when we popped it that's what we got the index two so what we're going to say for this value is it started at index 2 not at index three and technically you might think that okay well doesn't can't this actually be extended even one further over here right because this subarray also has a minimum value of two and yes you're technically correct but that's actually not necessary because that is actually already stored in our input array we see 2 1 is here that this 2 1 tells us that this 2 is the minimum value of a sub array starting at index 1 that's what the start value of the stack it tells us right it's at index one it started there and so far since that value is still in our stack what that tells us is so far this two was the minimum value and we were able to extend it all the way to the end of the input array so now you can see that we were able to actually iterate through every single value in the input array but notice how our stack is still not empty we only popped one value from our stack when we popped a value from our stack basically that told us that the subarray was complete for if 3 is the minimum value it started here it ended here and that's what the sub rate was a part of that's what we're going to compute for our result but since these three values are still in our stack and we know the start values of all of them for one it starts at index zero for two it starts at index one but what's the end value for these technically since we were able to get to the entire end of the input array the end is just going to be the end of the input array so what i'm saying is if we want to know for this one value if it was the minimum of the subarray how big is that sub array well it's going to be just the entire input array right that makes sense take a look 1 is the minimum value of the entire sub-array that does make sense entire sub-array that does make sense entire sub-array that does make sense what about 2 well we know 2 starts at index 1 so that's going to be the start of that subarray how far did it go it went until the end so when you look at this that does make sense 2 is the minimum value of this subarray so since all of them went until the end of the subarray let's start computing so let's look at the first value in our stack it's one and the start value was zero so we're gonna get the sum of the entire input array that's gonna be eight and the minimum value of the sub ray was just the value that we popped one times eight is eight and that's not larger than our current maximum we're done with one let's get to the next value in our stack so we pop this now let's look at this next value okay it starts at index one the value is two so let's get the sum of this sub array we know we can do that in o of one time and it happens to be two plus three plus two that's seven multiplied by the value the minimum value of the sub array we know that's two times four is going to be 14. so far our new maximum is actually going to be 14. so cross out the 9 put a 14 and we can see we have a single value left in our stack so we're going to pop 2. the first 2 tells us this starts at index 2 and the minimum value is also 2 so 2 is the minimum value let's get the sum of this subarray it's going to be 2 plus 3 that's 5. the minimum value is going to be 2. so multiply this by 2 that's going to end up being 10. it's not larger than our maximum but let me actually show you the code the way that i like to write it's going to be o of n time of and space let's get into it so we're going to have a single variable for our result remember we're looking for the maximum that we can possibly get we are going to have a stack which is going to be in monotonic increasing order and we're also going to have a prefix array where we compute every single prefix of the input array just so we can compute the sums of any arbitrary sub-array in arbitrary sub-array in arbitrary sub-array in o of one time so i'm going to just go through every single n in the input array so i'm just going to be appending every prefix to this so we're going to get the previous prefix basically the last value that was added to our prefix array and to that we're going to add the most recent value n that we're iterating through now for the actual algorithm let's go through every value in num so i n i'm going to use enumerate so we can get the index and the value in nums at the same time and i'm going to have a single variable for the new start and it's going to initially be set to i now we're gonna check if our stack is non-empty non-empty non-empty and the top value in our stack which we can get at the negative one index and remember we're adding a pair of values to this stack the that zero index we're gonna have the index that we add at index one we're gonna add the actual value that we added to the stack and if this value happens to be greater than the value that we're looking at right now which is n that's when we're gonna end up popping from our stack because we want our stack to be in monotonic increasing order and when we pop from the stack we're going to be getting a pair of values from it basically the start index and the value that were added to that stack and since this value is now being popped what we're saying is we just determined what the max sub array it could possibly have been a part of so now we're going to end up computing what the minimum product of it would have been so first we're going to get the total of the subarray that it was a part of so we know prefix of i is basically the sum of every value up until this value was popped and from that we're going to subtract prefix of star we're just getting the sum of the sub-array that this value was a part the sub-array that this value was a part the sub-array that this value was a part of so basically the sum of the sub-array of so basically the sum of the sub-array of so basically the sum of the sub-array from the start index all the way up until the i index that we just iterated to so now that we have this total we can potentially update our result we're going to update the result to the max of what it already currently is or update it to the minimum product that we're going to compute right now basically the value multiplied by the total sum of the subarray and last but not least what we're going to do since we popped a value this end value we're going to ultimately be adding it to our stack right ultimately we're going to say stack.append going to say stack.append going to say stack.append this value i n right because we're saying i is the start value of this n value but we see that we just popped a value from our stack so what we're actually going to say is the new start value can be pushed back by one so what we're going to do is say new start ends up being equal to the start value of the value that we just popped from our stack my words probably are a little confusing so you can refer back to the visual explanation that i drew a second ago so in reality we're not actually going to be adding i every single time we are initializing new start to i but if we end up updating it we're going to be adding new start to this stack as the start value of this n so by the end of this loop we will have added every single value to the stack but we won't necessarily have popped every value from the stack so we're going to go through every remaining value in the stack we're going to get the start index and the value of every single pair in our stack currently and again just like we did up above we want to be able to compute the total of the subarray that this value was a part of right the biggest sub array that it was a part of well we clearly have the start value of the sub array but what's the end value of the sub array up here the end value was the index i but in this case we know we went up until the end of the entire input array so the end value the end index in this case is going to be the length of the input array so we're going to say prefix up until the end of the entire input array length nums subtracted by the prefix up until the start value of this value that we popped the start index that we popped once we have that total we can again potentially update our result just like we did up above so result is going to be equal to max of itself and the max of the value that we popped multiplied by the total of the subarray that it was a part of so then finally after we've done this we've gone through every remaining value in our stack then we can finally return the result but remember they wanted us to mod it by 10 to the power of 9 plus 7. so this was a real doozy of a problem trying to get it from n squared to actually being a linear solution but we finally did it there's a lot of different ways to write this code but i think at least in my opinion this is the most intuitive by adding a pair of values to our stack so we can actually maintain the start index of every value that we added and of course we have to compute the prefixes and i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Maximum Subarray Min-Product
|
maximum-subarray-min-product
|
The **min-product** of an array is equal to the **minimum value** in the array **multiplied by** the array's **sum**.
* For example, the array `[3,2,5]` (minimum value is `2`) has a min-product of `2 * (3+2+5) = 2 * 10 = 20`.
Given an array of integers `nums`, return _the **maximum min-product** of any **non-empty subarray** of_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`.
Note that the min-product should be maximized **before** performing the modulo operation. Testcases are generated such that the maximum min-product **without** modulo will fit in a **64-bit signed integer**.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 14
**Explanation:** The maximum min-product is achieved with the subarray \[2,3,2\] (minimum value is 2).
2 \* (2+3+2) = 2 \* 7 = 14.
**Example 2:**
**Input:** nums = \[2,3,3,1,2\]
**Output:** 18
**Explanation:** The maximum min-product is achieved with the subarray \[3,3\] (minimum value is 3).
3 \* (3+3) = 3 \* 6 = 18.
**Example 3:**
**Input:** nums = \[3,1,5,6,4,2\]
**Output:** 60
**Explanation:** The maximum min-product is achieved with the subarray \[5,6,4\] (minimum value is 4).
4 \* (5+6+4) = 4 \* 15 = 60.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 107`
| null | null |
Medium
| null |
71 |
hello everyone welcome to day 14th of march eco challenge and i hope all of you having a great time i know it's monday views are back i still we have to maintain the consistency and solve daily lead code challenges i am doing it even before starting my day today's question that we have is simplify paths this question is based on string manipulation and to your surprise we have already solved this question in the month of february 2021 the comments speak for itself i'm attaching the link in the description below do check this out it's not a very complicated problem but yes it has a slight trick involved in it i hope you have a great time watching it up also if you are interested in more such string manipulation solutions then i'm attaching the playlist too and please guys don't forget to like share and subscribe to the channel it will motivate me further to continue this journey your friend your mentor your catalyst signing off sanchez take care sayonara
|
Simplify Path
|
simplify-path
|
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path.
| null |
String,Stack
|
Medium
| null |
1,637 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is widest vertical area between two points containing no points so in this question we are given n points on a 2d plane containing of a point with X and Y coordinates and we have to return the widest vertical area between two points such that no points are inside that area so vertical area of fixed width extending infinite along the Y AIS so it has infinite height and we have to find the widest vertical area so we have to find the widest area on the x- AIS so we find the widest area on the x- AIS so we find the widest area on the x- AIS so we are only dealing with the x coordinates for the points so let us take this example and see how we can solve this question so this is the Y AIS and this is the xaxis and we have to find the maximum distance between the points and first we giving the points areay 8A 7 so this is 8A 7 and this is 9A 9 this is 7A 4 and this is 9A 7 and this is infinite so you don't have to worry about the vertical distance on the Y AIS we have to find the distance between so you have to find out the distance along the x-axis and there distance along the x-axis and there distance along the x-axis and there shouldn't be any points between the distance so if you take this is the widest distance but there is a point here in between so you can't take this so this is the one more distance between the two points which is having one and this is having one so the maximum among both is one so one is the output so to check if there is no points between any two points like this in this case you if you want to check if there is no points between any two points we have to sort the array according to the values of the x-axis right so this is the input given x-axis right so this is the input given x-axis right so this is the input given to us let me write it again so if you want to sort it according to the values inside the x-axis you can write a inside the x-axis you can write a inside the x-axis you can write a comparator which will sort the input points according to the values in the x-axis so after sorting the final answer x-axis so after sorting the final answer x-axis so after sorting the final answer will look like this so first the smallest value 7A 4 so that will appear next the smallest value is 8A 7 because 8 is here and then you will take 9 comma 7 and then again you will take 9A 9 and here you can see the values in the X place so each point is represented by X Comm y right and the values in the X place are sorted in ascending order and now if you check any two points the distance between any two points if it is called X you can be sure that there is no point in between so that is why you need to sort the array based on x value so after sorting we start from I is equal to 1 I declare a variable Max initially zero now I will subtract 8 - 7 initially zero now I will subtract 8 - 7 initially zero now I will subtract 8 - 7 so 8 - 7 = to 1 so it will be updated to so 8 - 7 = to 1 so it will be updated to so 8 - 7 = to 1 so it will be updated to one I will move forward so I is equal to 2 so now it we will check 9 - - 8 9 - 8 2 so now it we will check 9 - - 8 9 - 8 2 so now it we will check 9 - - 8 9 - 8 is = 1 check if Max of 1A 1 will still is = 1 check if Max of 1A 1 will still is = 1 check if Max of 1A 1 will still remain 1 so max will remain one now I is moving forward now I is here check if 9 - 9 is equal to 0 check Max of 0a 1 it - 9 is equal to 0 check Max of 0a 1 it - 9 is equal to 0 check Max of 0a 1 it will remain one and now I is here is out of bound so you end the iteration because you started the iteration from one and you reach the end of the array and whatever is present inside Max will be returned as the output which is expected here try to do the same for example two and you will get the expected output now let's implement the steps in a Java program so now that we have seen how to solve this question let us code it this is the function given to us and this is the input 2D grid and we have to return int which is the max width so let's start off by sorting the array and now we have to sort the aray based on the ascending order of the X x coordinates of the point we are sorting according to these values for every Point given in the points array so these x coordinates will be sorted in ascending order so to solve that I'm writing a comparator where I'm declaring two objects A and B and then using the compare method to compare it to sort it according to the ascending a should appear first and then B so integer do compare a of 0 comma B of 0 so we have sorted the points array with ascending order of x coordinates now I'm declaring the output which is a integer so I'm going to name it Max width and initially it will be zero right and now I'm going to iterate through the points array from I is equal to 1 so that we can compare the previous element in each iteration now I have to keep updating the max width each time inside the loop so max width will be updated using the maximum value of the current Max WID and the distance between x coordinate so we start with i is equal to 1 so this and this we find the difference that will give you the width points of 0 points I of 0 minus points i- one of zero so this of 0 minus points i- one of zero so this of 0 minus points i- one of zero so this for Loop will happen for all the points inside the points array and finally it will be updated inside Max width which I'm going to return as the output now let's try to run the code the test cases are being accepted now let's try to submit the code and the solution has been accepted so the time complexity of this approach is of n again because we are sorting the array and the space complexity is constant o of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
232 |
welcome to my uh legal service session this is called the incredible queue uh using stack okay so uh the queue is basically uh our first thing for now the stack is amazing unfortunately and that's out okay so the problem is uh so the key points that we need to use the stack to import so stack looks like this suppose you have one two three and then you call pop and you go back to your properties okay so let's take the process that basically if i add one at the two and three and the pop i will get three so basically it's the first in so the first is one and then the next house one so first it mess out the stack okay so the key points that we need to use stack to improve the queue the idea is that we used to stack uh bluestack one says one or it says two okay another keyboard is that uh okay so suppose you have two s1 and s2 and then you first add one then it's very easy that you that is when you first add two and the problem is that it i mean if you add to it here then i call pop up too so which is not correct so the key is that i want if i want add two then i first pop one uh publish one piece here and i put through here and i then i place one to here and then after that when i so i want to put one here one three here and then you will have these three and then after that you pull please back you get two and one so when you pop then you will get one when you pop you will get one okay so this is the iterative process this is a iterative process so one two three will upgrade as you okay one two three basically is the same as the this is the same as the incoming okay so once you understand this then you can solve it so start initialize to uh bluestack and the push is just what i said if s wonders now you just first need us use s2 to append the ros one then your s1 open that number then you go back then you pull rs2 into one so this is the process for a description of what i described before but then pop obviously it's very easy because now i already shop for the all of s1 so i'm just pop s1 and the peak is just it will just give the front element so it's very easy just get the final element okay and it's empty it's the correct then uh you just return now of not of s1 so if s1 is empty then this is true okay and if s1 is not empty then you are returning false okay so all the difficult part is this push part so once you're understanding speech part and address is just trivial okay and i will see you guys in our next video be sure to subscribe to my channel thanks
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
145 |
how's it going guys today we're going to be going over another problem this problem is called binary tree post order traversal I just want to point out too that this is a hard problem according to leak code some people have been asking me to do medium or hard problems so things that are just generally harder than what I've been doing and I want to point out that I think this is a good example of why leak codes kind of like difficulty tag isn't necessarily the best indicator as to how hard or how challenging something is so personally I think this problem is rather easy compared to a lot of the other problems that I've done it's really just like your basic post order traversal of the tree which is very important to know but I don't think it requires much thinking it's kind of like your bread and butter of computer science it's something that you should know it's kind of like your ABCs that's not the you know the little anyone who thinks it's tough like it's hard to learn and that sort of thing but I do think it's something that's very common and I don't think it really requires much problem-solving it's more requires much problem-solving it's more requires much problem-solving it's more come it come and kind of just comes down like do you know how to do a post order traversal of a tree or dog so going forward I really just want to do things and I've always wanted to do things that are just the most helpful for you guys so if you guys have problems that you guys need help with or you guys have problems you don't understand or would just generally want me to solve be sure to let me know leave a comment below and I'd be happy to try and do that problem generally what I try and do is I try and do problems I think are interesting or important to know or asked often by large companies so with that being said let's jump into this problem but going forward I really don't want to focus necessarily on the difficulty but more how relevant these problems are to you guys and I want to give you guys problems that are going to be the most helpful and probably are the most important to actually know so let's get into it so literally it just says given a binary tree return the postorder traversal of its nodes values so for anyone who doesn't know a post order traversal is basically just traversing a tree structure it could even be a graph technically but semantics right so we have this tree and we need to do a post order traversal and a post order traversal is basically just grabbing all these nodes values but we have to process them in a specific order so the order that we have to process them in is you process the entire left subtree of the current node and then the entire right subtree of the current node and then you add the note itself so here it's three to one because we process the entire left subtree of one which is the root which actually has no left subtree then we process the entire right subtree so once we come to two we have to process its left subtree so once we get to three it has no children right it has no left or right nodes so we processed three we added to our list our recursion pops back off to the stack to our recursive call from two so we add two and then we've processed the entire right subtree of the root so we just add its actual value which is one so the code for this isn't too crazy they actually want us to do it iteratively because recursively it's kind of intuitive they think so what we need to do is basically just a standard DFS so I always like to have error checking personally I think it's a good thing to have I think all your interviews you should have some sort of error checking if you don't I think it kind of looks a little naive like maybe you're not considering all cases so it's good to have a checking so the first thing I like to do is just have error checking but I also like to return or initialize the return value so I'll just say list because right we need to return it literally on let's just point at the screen and we need to return a list of integers so list integer and we could just call this it's just call it values right because these are the values in the tree equals new ArrayList integer so if our root is null meaning we have no tree to process we could just return our values which will be an empty array list now this is very interesting so DFS we're just going to use a stack so we'll make a stack so we'll say stack and it's gonna hold three nodes because we're gonna process the tree nodes will call it stack and set equal to a new stack oops not integer tree node cool so now what we need to do is we need to start processing the tree right so we need to add to our stack so stack push root so now that we know that our route isn't null we a node to process so we push it onto our stack and now what we want to do is traverse the tree while our stack is not empty so I'll say wow if I can spell our stack is not empty we have some kind of processing to do right so the processing that we need to do is we need to get the current node right so we could pop that off the stack so we'll say tree node current equals stack pop and that will give us a note that we're currently on so what we need to do now is add its value to our result I know it's gonna sound a little weird because we just had media processes entire left subtree and right subtree we could use a little track trick so we'll say values add and we're gonna add it at the 0th index by saying add 0 and then we'll say current Val so what this is gonna do is it's gonna put the current value at the first index in the array so anytime we process any of its subsequent nodes it's gonna basically shift the root value all the way to the back of the array so that will save us a little bit of a headache so we'll just insert it at the 0th position every time so now that we've added the value we're done with that work for that node so now all we need to do is check its left child and right sub child sorry left child and right child and see if they're actually existing if they are we just want to put them into our stack so we'll check if current dot left is not equal to no we just want to say stack push current dot left so easy enough so if there is a left child to process the left child and same thing for the right shot so if current our write is not equal to no whoops we'll say stack push current right cool so basically what we're doing again is we're traversing this tree and trying to push its left child it doesn't have one go to the right child right process its left child doesn't have children and so we kind of just constantly are adding to the stack so once the stack is empty right because we're pulling from the stack here stack top hop we will have actually to our values every single nodes value in the tree and because we're inserting it at the 0th position it's going to shift the entire array over so by the time we're done processing this we've actually the last thing we will have added is the roots value and now we can just return our result except we named it value so return values awesome that's so it's as helpful guys be sure to leave me like and subscribe this is how to solve binary tree post order traversal and Java again if you guys have questions you guys can you help with or would like to see me solve please leave them in the comments and I'd be happy to help out hope this is helpful and I'll see you guys
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
235 |
foreign welcome to my channel coding together my name is vikar soja today we will see another lead code problem that is lowest common ancestor of a binary search tree LCA so it's a medium level question and it's a very popular question as you can see from the likes so let's read the problem statement we are given a binary search tree BST uh we have to find the lowest common ancestor LCA node of two given nodes in the BST right so we are given with the two nodes and we have to find the lowest common ancestor so what is the lowest common ancestor the lowest common investor is defined between two nodes p and Q as the lowest node in t that has both p and q s descendants so whichever is the lowest node having p and Q as descendants that is the LCA and we allow a node to be a descendant of itself so a node can be a descendant of itself also so if you see this example like this is a BST binary search tree right and we are given with P equal to 2 and Q equal to 8 and we have to find the LCA lowest common ancestor so 2 and 8 are the descendants of six so six is the lowest a common ancestor right for this again if you see we have given with P equal to 2 and Q equal to 4. so now if you can see here the two is the root of 4 right 4 is the descendant of 2. so now this statement where we allow a node to be descendant of itself so here uh so 2 is also a descendant of itself and 4 is a descendant of 2 so that's why 2 is the lowest common ancestor for 2 and 4. right so some constraints that we have to remember that P and Q will exist in the BST so always p and Q will exist in the BST right and all the node values are unique right now let's see uh how we can solve this uh problem so we will use uh so we will use recursion right we will use recursion so for the recursion uh we will use recursion on trees and we are given with BST binary search tree so there is an important property of BST that is left value should be smaller than the root value and the root value should be smaller than the right value right left child or left descendant must be smaller than the root and root must be smaller than the right child or the right descendant now there are there can be four conditions approximately like the p and Q The Descendants that for which the LCA we need to find it pnq can lie on the left subtree right they can be smaller than a root node right so we have to move left then we'll move left in our for our recursion and now if p and Q can lie on right sub tree right so we'll move right also third possibility is p can lie on left and Q can lie on right or vice versa right so what we will do will return our root element so because this is our favorable condition because whenever this is the this will the root will give you the LCA root is the LCA because root is the LCA for this p and Q whenever this third condition meets or also if the fourth condition when whenever one of the value one of the P or Q is equal to root then also will return root because then in this case also root will be LC so it will be LCA so let's see these conditions with an example right so if you if we have like suppose p is equal to 3 and Q is equal to 5 here and we so we will start with the root notes and we'll compare that if you see p and Q are smaller than 6 so we'll move left meeting the first criteria so we'll move left now at 2 again we'll check so they are p and Q are greater than 2 so it's meeting the second criteria will move on right now at 4 we will check so 4 is greater than 3 and smaller than 5 right so it is the third condition that is moving so what we will do at the third condition will return the root right so if we see here 3 and 5 so 3 and 5 are The Descent descendants of four so four is the lowest go lowest common ancestor for three and five right because three and five are the descendants of four so it is meeting this third criteria and will return root right three lies on the left subtree and five lies on the right substring so we'll return group 4 from here and then it will return four and return four okay so now suppose we take the same example if you take the same example and we change Q we change p is equal to 2 and Q is equal to 4 so here you will see it will meet the fourth criteria how we'll start with 6 again so 2 and Q4 2 and 4 are smaller than 6 so we'll move on the left right the first criteria right now again it at two now here's you can see that two root 2 is equal to one of the P or Q so p is equal to root node so fourth Point whenever one of the P or Q is equal to root will return root right we'll return root because 2 will be The Descent do you will be the ancestor for four and two is an ancestor for itself so we'll return 2 and finally from 6 it will return 2 when we backtrack right so this is the uh recursion this is how we solve this problem with using recursion using considering the properties of VST and some conditions so let's see the code part of it's very simple what we design whatever our conditions was so if P dot well is less than the root dot well or Q Dot and Q dot val is less than root dot 12 means it's in the left subtree right if it is in the left subtree we'll go again recursively call the method with the root dot left right we'll move to the root left part else if the P dot well is greater than root dot well and then Q dot well is greater than root dot well then we'll move on the right part so we'll call again the same function and cursively with root dot right else in either of the case like it will be 3 or 4 will return the root element let's learn this solution so your test cases are accepted it means the solution is working fine so let's see the time complexity uh for this is algorithm so the time complexity uh is dependent on the uh the nature of the tree the BST that is given so BST if the BST is given as uh you know balanced BST right so for a balanced BST the p and Q The Descendants for which we have to find the LCA would lie on the left subtree on the right sub tree and whenever they lie on the left and right both or vice versa we return the root as we saw in the third and fourth point so the we are not traversing each and every node in this tree so the time complexity will be Big O of H where H is the height of the tree which is the height of the tree now what is the average height of a tree we know is Big O of login right we go off login that is the average height of the tree so the term complexity will be big of log n for average case that is for balance PST and for the worst case when the BST is unbalanced EST is unbalanced right or what we call as queued so means that all the nodes are on the left side or all the roads are on the right side the these for these the worst case time clock strictly will be uh order of L as the height of the tree is Big O of n for this so that worst case time computer will be big of n so for the space time complexity for the space time completely it will be the same for the average it will be order of login right and for the worst case we go of n so I hope you like this video If you like this video please share and subscribe it will be keep me motivated to bring more such videos in front of you thank you guys bye
|
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
|
815 |
hello guys and welcome back to lead Logics this is the bus routs problem for lead code it is a lead code hard and the number for this is 815 so in this question we are given with an array Roots representing the bus routs where roots of I is a bus root that I bus repeats forever for example roots of I roots of 0 equal to 57 is this means that the bus will go from bus stop 1 to bus stop 5 to bus stop seven then again to bus stop one then five then seven then again one so this will repeat forever and we will be given with two bus stops source and a Target we can travel between bus stops by buses only and we have to also tell the minimum number of buses that we need to uh take to travel from source to Target so the problems involves the finding the least number of buses one must take to travel the uh distance from the source to the source bus stop to the Target bus stop and uh each bus travels in a repeating sequence we know this and we can Al only travel using buses between bus stops so the task is to determine the minimum number of bus rides needed to reach the target bus from the t uh Target bus stop to the source bus stop so let's see an example first suppose we have this example so root = to 1 27 and example so root = to 1 27 and example so root = to 1 27 and 367 so for this the source is given as 1 and the target is given as six so you can see we can go to 1 2 7 and then from 7 we can go to three and six so that's why we need to uh go through two bus stops uh so let me just tell you uh how we are going to solve the question now let's see this was the given routes so the bus one like the bus one will travel in this sequence go goes to stop One Stop two then seven then again one then two then seven and uh the second bus uh involves 3 6 7 and then again 36 7 so initially we can what we can do is that uh we can take a minimum something table known as a minimum buses to each and we can Define it with infinite maybe and we'll fill it with infinite values initialize the array initialize this with infinite and then when we'll iterate we'll try to minimize the minimum number of verses and fill the table accordingly like minimum number of verses to reach so you can see two can be reached from this but bus itself and seven also so that was done as one now we'll call for two and seven both so when you call for two there is no more buses but when you call for seven the three will become as two and the six will become as two so this table is updated finally and the table becomes like this sorry for that and now the table is uh Final Table will look something like this 0 1 2 and one and the final buses to reach after both we can return from here only so we wanted to return from the bus stop zero to the bus stop six so the minimum number of buses to reach the target was stop from the stop was 2 actually so in this we are using a sort of modified bman for algorithm so let's start with the coding section but before that please do like the video subscribe to the channel if you are new to the channel and also share it with your friends now first of all we need to check if Source equally equal to Target then we simply return zero because in that case we do not need to Traverse any of the bus stop and otherwise we Define a Max toop equal to minus1 if uh we'll Define maximum stop because if the maximum stop is less and the target bu stop it means there is no route to reach the Target and we return minus one so that's why we need to keep a maxtop and we initialize it with minus one then we'll iterate to the roots array and uh in that weate on the bus stops and we'll do the max stop equal to ma do Max stop and the stop so this will store the maximum of all the stops from the max stop so the max stop should be always greater than or equal to the Target it should not be less than so that's why we have taken the step so we need to write that also if Max stop is less than equal to less than Target return minus one otherwise we'll Define uh the table what we have shown uh now we need to Define this table so this table will uh Define but first take the length of the roots because we are going to need it down and then this table minimum versus to reach this will be of the size Max stop what we have taken plus one because it will contain all the stops that's why we are taking it Max stop plus one and we need to fill it with the let's fill it with minus one no we need to take an infinite so let's fill it with n + one and we'll put minimum versus to reach of the sord The Source will be zero and uh then we can apply our modified bman algorithm on this belman for algorithm let's take a flag while we write use the flag do itate flag equal to false again iterate through the roots take a stop no minimum equal to now in this part we are actually trying to uh take a minimum value for a particular stop and at the end we'll update it in the table this table uh the men is actually taking the minimum buses and then at the last we'll update it in the table so this and after doing this we need to do a Min Plus+ because in going through this we Plus+ because in going through this we Plus+ because in going through this we have actually moved one of the through one of the bus buses so we need to do a men Plus+ and then we'll again go we are going to update the table minimum copies so this will run until the table Remains the Same that's why we have done this and at the end now we can simply return the minimum number of buses to reach of the target so table value from the target if it is less than our maximum value which was n + value which was n + value which was n + 1 otherwise what we have to give a minus one else we will give the target itself let's try to run this seems fine time to submit it fantastic current time good memory just move it down here so this was my solution now let's talk about the space and the time complexity for this solution is n cross M because the outer Loops run outer loop runs until no more updates can be made and in each iteration we iterate through all the roots so it is n cross M where n is the number of roots and M is the average of average number of stops and the space complexity is O of Max stop so the max stops which we are taking uh o of Max stop is the space complexity because we are using this array of the size Max stops plus one so this was my solution which uses a modified version of bman Ford algorithm I hope you like the algorithm uh let me explain it once again so what we were doing that we were taking a table initializing with maximum values and then we'll try to minimize the part to add value and update the table and at the end we simply return the value from the table so this was my solution I hope you like the video so do subscribe to the channel like the video thank you for watching the video have a nice day
|
Bus Routes
|
champagne-tower
|
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106`
| null |
Dynamic Programming
|
Medium
|
1385
|
400 |
Hello friends, in this video we are not going to solve this problem, basically we have been given one wait, one more wait, what we have to do is to return to digital, one infinite wait sequence, now what does it mean? Sir, this means that we have been given an infinite waiting sequence and a number has been given to us which is N which we have to return digital like we have a sequence from one to infinity so if the value of N is three then If you have to return the third digital then what will be the third thing 1 2 3 If n = 11 then what is the 11th digital, pay 1 2 3 If n = 11 then what is the 11th digital, pay 1 2 3 If n = 11 then what is the 11th digital, pay attention here give 11 not 11th number then what will be the digital 11 123456789 and the one which is our 10th digital and which It is zero, that is 11th, so you have to pay attention to it digitally, so let me explain the question method to you, before that please subscribe to the channel and like the current video also so that you do not have the hassle of liking the talk, then there are some questions. No, we just have what to do, what do we have to do, if the value of n is three, then you know who is the third digit, if the value of n, then what will many people do, will they return the 11th number, no, if the 11th digit is of digital, then first. Digits Second Third Fourth Sixth Seventh 8 9 This is our 10th digital and this is our 11th digital so we have to return the zero. Okay so look like you know, this is our 11th digital and not the number if we have to return the number. If it has started from Rahat and One, then I return this number from the gate. If you want to return digital, then you will know one thing that from one, if I talk about one digital number, one digital is from one to 9. How many numbers are there in total, if I talk about the meaning from 10 to 99 then from where to where, from 100 to 999 means 900, similarly if I talk about 4 digital numbers, how many four digital numbers are there, from 1000 to 90099 means 9000, then what is there in this? Got to learn this Sir, the single number is 9 and the digital number is directly multiplied by 10, the 3d number is directly multiplied by 10 and in the same way, what is the meaning of multiplying by train? What does one digital number nine mean? So how will I do it? Do you understand what sir you are telling me and how to do it? So see what we have to do is to find out the length date. 11th digital number means what if I check 11 then what is 11? There are 2 digital numbers, you are the digital number, if I have to find out the 11th digital then in which digit will I do the 11th digital number, then is it necessary to check it in the 2nd digital number, give me one number, no, otherwise if I calculate the number linearly, then from the beginning till the end Let's check. If we have to check then what will I do? When the value of the other is 11 then what will I do? How many numbers are there? If it does not fall in the range then what do I do? I will have to skip them. Is this one in digital number ? How many are you in digital? A1 in ? How many are you in digital? A1 in ? How many are you in digital? A1 in digital is not in digital, you are in digital, when you are in digital, it means what is the number of digital one before this, from one to nine, you will have to skip them, it is not necessary to check in these, it is okay when it is not necessary to check in these. So after that we have to check when the value of N is 11 and out of that number nine has to be added no means two number went back two number and what do I have to do for number two which is the first number pick it up after nine. It will be necessary because two of them are digital and I want 11, so what will I do, I will catch the train, I will catch three, I have caught the train and there are two kids, so one number is ours, this is our 10th, this is ours, so now I will catch the 10th, how and its How will the index value be found out that our answer will be zero. Okay, so we have to understand that the value of N is 11th 5 6 7 8 9 10 11. Okay, which digital range is the 15 in? 1 in digital, you in digital. 3 In digital, I am seeing that you are coming in digital. When you are coming in digital, then is it necessary to check the number of one digital which we have 9. If not, then what will I do? So I What will I do directly 15 minus nine I will do six means after skipping 9 from here, after skipping nine I want six digital what will happen like our 10 11 12 13 14 15 I want you ok so what will I do I What will I do, I will finalize this number that before finding out the digital number which is our 6, I will have to find the number, so I will finalize this number, okay, whatever I do, understand, now after finding out the number. I will find out its index value, then I will see that its index value will be zero one, its 50 inch digital will be 15th digital, its index value will be one, then I will return 2, so let me tell you the solution, look in a very good way and I am driving here and see, what will I do, I will keep a digital name available whose value will be one and we have not kept the base, you can see here that everything is multiplied by 9, if I am here only nine and then 9000. So what will I do, take 9 base mother, I will keep it like I am writing here, like one, three, four, 11, 12, 13, 14 = our kitna hai zero basic, how much is 9 date, how much is N, meaning in nine list, if we take 15, yes li. What to do in the total? What is the total? What will be the value of the base? Okay, what is the condition of that water? Now what will be the condition of the water? So what will I do? Here now what will I do in the value of N? The value of N which was earlier 15. So the value of N which was 15 is the total out of which means we have checked 9 and if I drop the nine then A will be how much I was doing in six and one. I was doing the same here, we checked 6 here. Okay, everything is understood, six again six, now what will I do, the number will come out, what happened like 6 digital, so I want it, meaning from which number I want it, then I will have to get the number, then what will I have to do by getting the number, power of body, like I am writing the number here. 10 and digital - 1 writing the number here. 10 and digital - 1 writing the number here. 10 and digital - 1 z value how much was here tu tha minus one how much will it become one means power of train one means number our 10 is gone ok now what will I do whatever number is number I will add n - 1 what will I do whatever number is number I will add n - 1 what will I do whatever number is number I will add n - 1 /dt to it then n What /dt to it then n What /dt to it then n What is the value of N? Here how much is our child. Six is how much is five child. Six is how much is five child. Six is how much is five digital. What is its value? What do you mean? It will become 2 meaning 10 + 2 means calculated in number. Okay, so find out the number of N - 1 So what is the value of N - 1 So what is the value of N - 1 So what is the value of N? Value of N is our six was six so one reduced to 5 model tu means four modules tu one minute ours was six so six minus one five means index value our one a will go so which number is our number. Our index value is 12. If we have to return one then zero one what will we get? 2 What should I do with this? If I have to return then I think if it does not come then what should I do? Try run and catch an example like N = catch an example like N = catch an example like N = Grab 13 and do the solution here only if you need it, you will understand otherwise you will not understand, so if I talk about time complexity then how much will be added, meaning how much, look like I am skipping 180 at a time, then I will do 2700. Our time will come to the people and its space will become clear to the community. And if you have not subscribed to our channel, please subscribe to the channel, like the video and share it with your friends if you want to read. Are
|
Nth Digit
|
nth-digit
|
Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`.
**Example 1:**
**Input:** n = 3
**Output:** 3
**Example 2:**
**Input:** n = 11
**Output:** 0
**Explanation:** The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Binary Search
|
Medium
| null |
139 |
Hello viewers welcome back to decades and this video will see what problem which from list is number 139 and this problem has service five different solution so I will be planning for this video and the video of the problem subscribe share also problem Problem Solving Your Interview Subscribe Our Everything You Need For Your Interview Subscribe Interview Preparation That Swift Six Months And Contains The Intelligence Unit For Interview On With Machine Coding System Design And You Can Also Give Water Ship Or You Can Schedule Mock Interview To Get Back Your Preparation And According Preparation Strategy To Register For WhatsApp Only No Problem Given String Subscribe And Use Dictionary In Dictionary This Problem Is A String Gas And Word Dictionary And Goal * Find This Can Be Sent * Find This Can Be Sent * Find This Can Be Sent Into Words Present In The Dictionary Ok Know The Constraints Of Loss The first woman president world must be present in every secret must be present in your dictionary in this might be or and pigmentation responsible for the industry must be present in this for example a string events in Delhi and 1000 possible and a that they can reduce the dictionary Words I have seen times are possible so let's like NSS Type OK Sorry Fruits Ka The second example in this case you have noida string and dinner is mine in this year two different words so it is possible to take medicine in all school present international situation like this end subscribe 4,320 possible through use subscribe 4,320 possible through use subscribe 4,320 possible through use spring from the question as well and will not represent will not possible to partition this into a set of words for the worst representation in this case e will return for sudhir and will not possible to enter into subscribe 100 Most effective approach for solving problems by using back to know the Tarzan in the different Possible to enter into the award was presented as you can see a will to partition was partition point sweater possible partition points after each character you can have on petition point OK All the characters will be a living in Lutyens and in increasing order to partition will be left with no idea about future subscribe The Amazing Number One must be present in the picture and a has but you can see but this is not present in the dictionary so will Be useless to partition in between and proud of politicians for all the possibilities starting from white display quizzes viewers initiated after making this partition will avoid this petition in the world which will make subscribe to partition points which creates strs 10th 12th this point partition point Creative They Do Not Know About That Weather This Is Pain In My Hidden Letters To Proceed With Answers For This Problem Railway Station At This Point Between India And Will Not Be Possible Subscribe Now To Receive New Updates Will Not Be Possible To Partition In Between And Jain President World Twenty20 Series Page 4 Thousand Na Dhi 10 Latest Partition Will Not Be Possible Station Superintendent Three That We Are Back Positive Present In The Dictionary Sources Also Well And So Will Recover For The History Of The Rings Basically Do Not Attempt To String In Veer Getting Rid of Partition in To-Do Veer Getting Rid of Partition in To-Do Veer Getting Rid of Partition in To-Do List Subscribe 4,320 subscribe Video List Subscribe 4,320 subscribe Video List Subscribe 4,320 subscribe Video then subscribe to the Page if you liked The Video Petition Only Vendor Current Stringers Valid This is the most important observation for this OK Sudhir and also in the Board of Directors of Ninth Present in the Mind and for All the Possible Partitions and Forestry Individuals Possible Partitions Point to Five Inch This Channel Subscribe Position subscribe our Channel Combination Time Complexity Approach Will Be The Quadratic Representation For The Best Web Designers Containing ABCD Will give nine allotted in 2 and by repeating problems antiseptic according structure you can c a d w basic elements wwe straight are this straight forward problem subscribe solution for smaller problem solution subscribe my channel like this is a problem se possible to partition this Problem * possible to partition this Problem * possible to partition this Problem * Subscribe Quite possibly because you can partition and it's ok sweet special It's true that they can have a party from this point Note for solving the problems that you can solve this problem from Se Intact 123 45678910 Politician from this 327 Does it is possible to Make it easier to partition between to the thing will come true for all possible subscribe and subscribe the Channel and Share Decentri will also be possible to partition subscribe the structure is aware and care for you will apply dynamic programming in this so let's look at the Reception Code Were Placid At Top Down Rough Edges And Its 100 Co Cost For Ignoring Pink Lips Basically The Amazing First Tried To Solve A Position In Position Will Start From Village To Avoid Dictionary In To-Do Village To Avoid Dictionary In To-Do Village To Avoid Dictionary In To-Do List Check The Vice President And Set The Thing Every Student Spring That Means All The Letters Which They Have Passed Through Left Over In Partition Will Only When The Partition Subscribe Another Country Will Take All Possible Partition Subscribe Position And Going The Distance From All Possible Partition Subscribe My Position Which Will Be Possible Politicians From This Is Page Set to Tried This Petition OK Now Nobel Prizes Were Given Partition and See What This World Which Has Been Created A String Subscribe Position Two Minus Plus One Characters This World Which Already Present in This Present in the Missions Valid And Can Be Created Nor Will Go To Do And Plus One Will Dhaval The Problem Returns Through All Present In The True Subscribe Possible To Enter Into A Jhal Vice Chief VK Bhatt All Possible Partition Points And Wooden Tax Relief For Partition In Toilets And streams will return to set before returning from this is the problem periods problem from absolute position on that and I will be storing the solution for this cases position OK so I will be storing matter position Sudhir with its possible to partition Distic Subscribe Into Its Own When Politicians Are Doing For Me To 10 Of Problems From Position And Answer From 0245 Video then subscribe to the Page if you liked Videos From To The Power And 2ND Year * Videos From To The Power And 2ND Year * Videos From To The Power And 2ND Year * Okay Gift In This Observance Complexity Of Creating Subscribe To Is so where the opposition in the previous subscribe to present in the center dictionary before making the partition and call only when the creative way were to give position from the giver position subscribe position to and events from 0001 this point position subscribe thank you will Get and through return for the petition from position to and will win the inter given string will be id the return from where you will get rid of problems and subscribe button solution from this point to subscribe to hua tha ok so having no about the memorization That Was Preeti Thi So Let's Look At How To Do The Tabulation Soft Latest Rock On Logic And Listen Study-Teaching's 106 Possible To The Point But Will Have To Subscribe My God Are From 6th Id A Break From 020 Edward Break From Sector-12 6 Best Servi Se Commented On That Sector-12 6 Best Servi Se Commented On That Sector-12 6 Best Servi Se Commented On That Nav I Can Write To Recall Se Will Check The Small And Quite Right To Use The Next Partition Will Be Free From 2nd T20 Against Partition 102 Sure Different Possible In Its Possible 123 456 subscribe to the Page if you liked The Video then subscribe to The Amazing This Is Made In Partition Reduce Partition Will Be What Is 12345 6 Partition Will Be Ours 1206 E Know This Will Create Partition Will Create Par 108 Par 1690 Quality Presented To The President Rule 10 123 456 Video then subscribe to the Page if you liked The Video then subscribe Karo Husan Two For Physically APN And Five Strict Basically Michael Nobbs And Different Sudhir And Subscribe Now To Receive New Updates Reviews And Want To Know The Solution For Class Seventh Solution Subscribe Quality Mal Structure Property Assigned Understood S Jaswal Simple Example Which Can Withdraw Pre-2005 Tune In Airtel Can Withdraw Pre-2005 Tune In Airtel Can Withdraw Pre-2005 Tune In Airtel Point Between That Kepler Swine Fever Partition 1020 Plus 2 End Partition Will Be The Solution Class Ninth Time Table 2012 Possible Thursday A No-nonsense Already Sent Will Be The Solution A No-nonsense Already Sent Will Be The Solution A No-nonsense Already Sent Will Be The Solution Bottom of what will be the smallest partition size when molestation size will give one and what will be the largest producers partition says pe 900 female for the solution for partition his attention deficit between politicians and jan-2012 and jan-2012 and jan-2012 a solar street light from zinc like share and Subscribe In A Reader Partition Will Leave Petition For The Validity Is This What Is This Is Not Present In This Petition 100 Number To The Self Made In The Mid-1960s These 10 Celebs Obscene Cigarettes They Have Created A Partition Of Science One And Discuss Only Containing Spring from Index One to Index One Reduce Celebrating It's Only This Word Switch of the United Dictionary and Also Single Character Not for the Audition Single Character Not Withdraw All the Partition Was Not Present in the Dictionary by bab.la Dictionary by bab.la Dictionary by bab.la Hello How is Coming This will look at this falls and singh binttu ward boy in the starting index is starting point mother and descending order subscribe to the Page if you liked The Video then subscribe to the Page Qui also develop console on this table water cells which celebs headed for one to create partition Vice President 2323 you liked The Video then subscribe to the Page if you liked The Video then subscribe to the Page Quid also possible that Was Presented In This Present Separately In Two Different Words So Will Participate In 2.5 12323 Words So Will Participate In 2.5 12323 Words So Will Participate In 2.5 12323 To Two To Three Is The Chief Of The Subscribe Must Subscribe 602 Latest Film The Window and Partition Deficit Between And Subscribe Station Between P&G 122 Is 125 One To Three Station Between P&G 122 Is 125 One To Three Station Between P&G 122 Is 125 One To Three Layer First Of All You Need To Sacrifice My Presentation Are Not Present In The Present My Parents But In Its Party What Is The Difference Between And Already Subscribe What Is The Meaning Of S One To Three one to three idiots say three little make a call from word grade one to one should make a call word back to three look at the end of this year does not care about the latest to three subscribe partition will also from 12345 servi not destroy All way what is the different between this cream and tours and partition in two different set of partition points 108 basically singh world track one to three will give me some information relative 12323 ok subsides way raw two three one two three four one does not 12323 like This Channel Subscribe And Operation Of True And Partition Benefits Facebook M Y P Singh And Bewakoof 125 Back Present In The Dictionary It Is Not Present Some Will Try To All Possible Petitions For Partition Points Payment Voucher 12121 Android 24900 Between Boys Page Will Give One Does One Two Three Four Three Two Four Wheel Chair For All Possible Station Superintendent 2012 Air Force OK Simrely Then Check It Will Be Falls For This Is It Will Be Falls On The Same For This Is Well No Problem Liquid 512 You Will See The President Patil At This Point Raised Through This Petition Points From Two Different This Person Subscribe The Amazing 69 Partition In Windows 7 64 Bit And Partition Will Be Id Lord Nor For The Last Ring Will Ask In My Mother's Pride Possible Partition Or Swap Partition Vice President Dictionary subscribe Problem 123 45678910 Delhi will give one does not give you problems and subscribe to quote this will also be true or not to find it's possible to take part in the string into a valid subscribe The Channel subscribe for values 12120 subscribe for values 12120 subscribe for values 12120 subscribe not as you can see What is the time complexity table subscribe button subscribe break point from this point to you to ante 09 Video give petition from 21 to withdraw from one to three the number of partitions will give time to time subscribe to the Page if you liked The Video then subscribe to our Channel subscribe Thank you in this video
|
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
|
461 |
hey everybody this is Larry this is day fifth of the July daily legal challenge I had like button hit the subscribe button join me on discord ask questions and all that stuff yeah so today's question Hamming distance we're having distance between two integers is just a number position in which they're different bits so basically what I mean there are a couple ways to do it there's an XOR method see if you could up solve using that later if you like but the idea is that the way that I'm per man is just way naive because I wanted to keep its symbol but basically yeah basically two binary numbers something like that I don't know I'm just banging on the keyboard really and then we just do it one at a time from the lowest bit we check okay are they differ are they different if yes then we just increment and then we met and then we chop off both x and y's we come one point and move the point are they different gasps keep the counter that's pretty much it and you just do what the prom tells you in that way and this is my code give or take and yeah again if you like you could see if you can figure out with XO or maybe even use some library functions but uh but this today seems like a pretty straightforward form so if you have any questions leave in the comments deeper in the discord or whatever yeah watch the live portion mine about now I suppose hey everybody this is Larry hit the like button to subscribe on this is the live portion of the explanation for today's take coach on that go for it hemming distance okay I'm understand between two integers is to know more precision in which the corresponding bits are different come on to and edges X&Y calculate Hamming distance okay so X&Y calculate Hamming distance okay so X&Y calculate Hamming distance okay so basically you just have to do it one bit at a time there's just a couple of ways that you can do it there's a fun tricky solution with just X or in the two numbers and then counting the number once and dad I'm just going to do it a little bit sub explain why one bit at a time and you know they'll be easier to understand I think because it's okay to do the other way as well but basically we just do it for in range of 32 I haven't 31 is fine too but basically every time we just count whether the last bit and X is your two last bit in Y so you can even use my two of you one but just to kind of keep it to Matic I'm going to do the n1 if this is you go to Y N 1 which is count which is increment and then at every time will shift to the right one I just divided by 2 I know that the way I make it just returned Cal and we chose to fix 32 because it's easier to understand maybe and because we know that's gonna be our max case anyway there is two them of different so whoopsie yeah so then you can play around with some big numbers I mean that may be too big I just banged on the key for a little bit but yeah we could submit it I mean I think this is pretty come from your body understand negative numbers for whatever reason I know that's it okay yeah so that's pretty much it just count a bit by bit we can go over a binary or in the explanation portion or you already done it I guess but I yeah that's pretty much it and this is all one if you want to count it that because this is always takes 32 operations so that's pretty much it and the space we're gonna use any much more space so yeah today's forum seems pretty straightforward so yeah let me know what you think hit the like button to subscribe button and join a discord and I will see ya later bye-bye
|
Hamming Distance
|
hamming-distance
|
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.
Given two integers `x` and `y`, return _the **Hamming distance** between them_.
**Example 1:**
**Input:** x = 1, y = 4
**Output:** 2
**Explanation:**
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
**Example 2:**
**Input:** x = 3, y = 1
**Output:** 1
**Constraints:**
* `0 <= x, y <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191,477
|
215 |
all right so let's talk about okay largest element array so you're giving the initial real numbers and then it's a k so you have to return the k largest element inside the array and this question is really simple so uh again uh let me join so uh if this is a red and then the k equal to two which is the second largest element inside the array right so what do you mean for the largest one so the k largest element so again you can have a p cube so priority queue so this is going to be what's on smallest graders right and then whenever single whenever you try versus follow i mean sorry whenever you try to traverse the in array right you add to the pq and then you check the pq size you check the size if the size is greater than the k which mean what uh which means there is an element that shouldn't be shouldn't stay inside the pq right so you will just pick with a pole right so whenever you pull the minimum value inside the pq and this is not the k element this is definitely not a k element in the journey inside the inside of the array right and then basically this is pretty much you pull when you have greater size inside pq and then you peek at the end for the return value so which means this one is going to be the k element inside the pq right all right so um this is this should be simple so priority q and i have integer right p q to the mean pi or t q and then i'm going to traverse the nouns all right i'm sorry and then i'm just keeping the num and then if p two the size is which is greater than k so someone has to be removed and then at the end i'll just say okay so this is going to be the element that you need to return all right so submit all right so let's talk about the timing space this is going to be a space and what do you think uh this is a party q right party q is all of k says okay right if you clear if you build it and that's okay this is going to be what only have k hit allocation memory inside the priority queue and this is going to be a time for the for loop and definitely this is going to be all of n but the problem is when you add to the pq this is going to be what uh logan right so uh sorry log k because only f k l m inside the vertical so it's going to be all of n times uh log k all the time so this is my quick note for the timing space and this is the solution so if you feel helpful subscribe like and i'll see you next time
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
1,926 |
hi friends uh welcome to my channel let's have a look at problem 1926 nearest exit from entries in maze so in this video we're going to share a solution based on breadth first search so here our main goal is to emphasize the treatment to avoid repetition in the traversal so this problem requires to return the number of steps in the shortest path from the entrance to the nearest exit or an negative one if no such path exists so here are some examples for example in example one so the output is one so he can move the person can move one step upwards so in the second example the output is two and the person can move to the right two steps so notice that in this problem the entrance is in the boundary and less in the boundary so the exit cannot be the same as the interest position so in example three so this is a very special case so because the person lies in the um boundary or the entrance that's in the boundary so there's no other boundaries so the output is negative one so the constraints on this problem are mainly on the um on the sides of the maze so the number of rows and number columns are m and n respectively and both of the two numbers are bounded in between 1 and 500. so in this problem the dot means empty and plus means wall so the entrance will always be an empty cell so this finishes the main statement and assumptions in this problem now let's look at the method so as we mentioned the method is breadth first search and here the breadth first search is single source the source is actually the position tuple corresponding to the entrance position so in this problem actually the logic is relatively simple so the stop condition is easy to recognize that is when we meet a boundary empty cell notice that when the entrance lies in the boundary so the exit cannot be the entrance so here in this video actually we want to emphasize the treatment to avoid repetition during the traversal typically if we use breadth first search or depth first search we will use a set data structure as a helper to avoid repetition and here in this specific problem what we are going to do is the following so as we visited an empty cell starting from entrance position we're going to reset the mid value corresponding to that position to be plus that is a wall to mark its visited so with that said i guess we are ready to look at the short code so first i'm going to make some preparations like tracks and information for the number of rows number columns and then we're going to write a heifer function to do the breakfast search so in between we're going to track the distance information and finally we call the hyper function and do the return so first let me get m and n so m is mis of length and the second is made 0 right so that's the number rows and number columns so next is the breadth first search hyper function so in this function we're going to accept a position as a tuple as a argument so this is going to be our entrance tuple so in the function call so we're going to return a distance so for this purpose we're going to use a queue to as a container so collections deck i'm going to use this container as a hyper for mimicking the crew behavior so this is and also we need to return the added distance so what i get is this so let me make it a tuple so let's see this is the right and this empty break there's a breakage it's also rate so what we return actually uh what we store actually nothing but rc and distance so for the entrance we set the distance is zero so with that said let's do the uh iteration so it's a well loop so well uh well q so notice that we didn't initialize a set here so as we mentioned in the atom 2 here so what we are going to do is that we first get the position and distance we are looking at pop left the first thing is that i want to mark this rc to be a wall because this is visited and then we are going to check if this position rc corresponds to a valid exit so if um let's see i'll use r in 0 minus 1 or c in 0 n minus 1 so this is the condition for the row and the co or column index for position rc being like being in the boundary right so this is one condition and also we need to check this position is not the interest so we're going to check add not so this the r equals entrance zero um and see echoes an entrance one right so if this is the case uh we found at exit which is valid so we're going to return the distance otherwise we're going to look at the four directions let me push this a little bit to make it easy to observe and then we're going to check the four neighbors so for x y in r minus 1 c r plus 1 c r c plus 1 r c minus 1. um we're going to check if this position is inbound at not visited yet so if 0 less or equal than x less than m and 0 less or equal than y less than n and so this position is not visited in other words it means this one not equals positive so this actually serves as two purposes first it checks um because if this position does not equal to um positive it means that it's either not visited or it's a empty cell right this empty cell is what we are going to uh include so we're going to equal this position x y with the distance incremented by one and here one thing that is important is we're going to change this x y to be a wall after we add we enquire it so this is going to be important to avoid uh repetition so once we done this one if nothing is returned um during the while loop we're going to return next to that so that's the second step so the third step actually is the return this is routine we're going to return bread first search we're going to pass a tuple corresponding to a position to the function so that is the entrance here and then that's it for this problem so before we analyze one more point let's do a special case check oh yeah it passes a special case now let's look at the generic case so it passes uh all the generic cases so here is one thing so in this one because actually because we have changed this here we can comment out this one so if we check it pauses all the cases so but logically i would like to add this here the reason is um i want to change this position entrance also to be a ball so that's just a personal preference yeah so with that said i guess um that's about it for this problem so you're welcome to check out other videos in my playlist or channel thank you so much
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
771 |
I will be doing almost m71 because which is to called Jules and songs the body fat be given a string of J representing types of stones that are jewels and as representing the stones that you have each character and s is a type of stone you want to know how many stones you have our also tools the letters and K are guaranteed to be distinct and all characters in J and s are letters our case on this case sensitive so a is considered to be different capital e so for example in this example one if you have the jewels lowercase a and capital A India the stones a capital a BBB fee and there will be three jewels because the first three will be chose an example to the jewels is Z while the stones are capital T capital Z so then I know these are not jewels because they're uppercase so one way to do this is you can leap over your stones and you have and then check it if they are jewels by doing in search to see if exists in the J if you were just to do a search like an index L then this would the search would take as much time as the number of tools that you have because we have to look at all jewels sequentially but if you change the jewels into a set then the look of time would be constant so let's get let's try to admit that so let me put this here so let's have a function call Jules what num Joseph's sons and we're given a list of rules and also times so we want to loop over the stone or something comes we want to see if this stone is in the tools so this works because stone is a character and Jose is a lists it's a word and you can search for a character and a word use them and offer yourself if stone is in the tools then we want to add one to our account we don't have a count yet so let's set it to zero so this is the count is the equal to the results so let's retry and count let's see if this works num Jasmine stones and then if we have a we have this input and we should expect so you have resolved great and we did so this works but there's one optimization that we can do is that we can convert the Jews into a set of tools so that the lookup time will be faster so because they're set we can see that this line actually doesn't have to change because we can still search a letter within a set using the in operator and when we run this we will see that it did also have the right results and that's it
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
1,604 |
hey what is up guys this is my new video uh hey what is up guys this is my first video on my new channel abroad does software engineering um today we're gonna be doing a leak code problem this is the first video on this channel so if you don't know i used to make leak code videos on my old channel called abrar share and you could check out some of the older videos there but i'm going to be moving all tech related software engineering computer science related videos and career related videos to this channel um a new a video is going to be coming out soon maybe like a week or under a week where i have a full intro video to this channel explain what i'm planning to do and some of the projects i'm working on and some of the ideas that i have and future goals for this channel specifically so that's going to be coming out soon just stay on the lookout for that and hit the subscribe button if you haven't already but let's get right into this video okay so we know we are now back we're going to be doing problem 1604 alert using same key card three or more times in a one hour period first time looking at this problem i'm gonna try to do an uncut video but it has been two weeks since i worked on a leeco palm so this might take a while and i might have to do a cut video but let's see how it goes uh leco company workers use key cards to unlock office doors each time a worker uses your key card the security system saves the workers name and the time when it was used isn't it coveted why are you going to work this thing emits an alert if any worker uses the key card three or more times in a one hour period you're given a list of strings key name and key time with key name i kita mike responsible personal name is having the keycard was using a single date acceptance are given in the 24 hour time format hour mm such as 20 50 109 50 40 49 return list of unique worker names who received an alert for keep keycard use throw their names in ascending order alphabetically and notice that 10 to 11 is considered to be within a one hour period while 23 51 to 10 is not considered to be within a one hour period hmm okay so we got this impulse daniel then damn daniel rowe louis louise let me go 10 40 11 9 11 13 15. so he definitely got some notification because in this one hour period he did use it three times at 10 a 10 40 and at 11. daniels uses the keycard three times one hour period 10 40 and 11. yes okay so alice house alice 1201 12 c so it's not ordered okay we already got that because look over one and about 12 okay and then 21 20 21 30 23 00. five years ago three times in one hour period 21 20 21 30. okay so why not alice oh because it's like six hours later uh okay we've got john 250 2059.01 okay so this is a little special 2059.01 okay so this is a little special 2059.01 okay so this is a little special case because when you move from 24 to well you don't really have a 24 way from 2059 to 00 then it's considered out of the one hour period so that's something we need to keep in mind let me just write that down going from 24 59 to 0. it's no longer considered a one-hour it's no longer considered a one-hour it's no longer considered a one-hour period so maybe we can consider the p time between 2059 to o to be 61 minutes i guess something like that or infinite whatever right okay so now what we want to do is find the ones who have a notification that one hour period okay so we have the key names in the key times let's see how we can do this well we know we need to go over the key names and over all the key times and hmm so what if we took all of daniel's names oh daniel's times and we put them in order and we inserted them into some kind of ordered um list right over here so i put like 10 then 1040 then 11. let's do 10 40 and 11 okay and then every time i go let's see let's say we had more we got like i don't know like 11 30 3 o'clock right so now i'm thinking is that i need to keep track of three at a time right three time three at a time and keep checking if they're within the one hour period so maybe some kind of shifting um array sub array over here so maybe something like so i started the third one i took it two times before so it's ten four and eleven and now i see at the time between this one and this one so i can skip the middle one it looks like i can skip the middle one because if i know this one and this one is within a one hour period then i'll know that um this one is obviously within the one hour period so this one is one thousand period and they are that means whatever's in between is obviously within it so that means we have three that are within the one hour period and i can move over here and then i can check this one and check if this one is um uh yeah this and this is within our running period that means all three would be considered one okay so this is simple i think i got it okay so what i'm gonna do now is i'm convert uh to sort these times i'm going to convert all the numbers not the numbers but all the hour uh minute format to num seconds right so like one uh oh 1 34 is going to be um 01 times uh i'll cover it in a minute so i'll do like 60 plus 34 which would be 94. hey what's up converting all the rmm forward onto num things okay so now let's go along let's try to do this so let's make a hash map and we'll store all the names to a list of um ins which will be the times right that he entered i'll just call the hashmap now okay then i'm gonna go through all the times right and then what do i do oh yeah i'm gonna do i'm gonna get the name um there's gonna be a keyname i same thing then i'm gonna do hashmap if uh hashmob does not contains key name i'm going to insert in so i'm going to have dot put name new array list string no integer bang this is going to be if it doesn't contain the name then you put the list in so we keep track of the times and then oh yeah so then i'm going to do get that list and i'm gonna add this time but i'm gonna convert this time add convert time converted let me just convert here i was gonna create a helper function do the conversions i'll do right here so i'll do so key time will look like 23 51 so i got to do and total mins i'm gonna do it one line i'm gonna do key time dot split bang split it on the colon zeroth one dot split it splitted 0 would be the hours times 60 plus which that happens first plus d splitted one i don't think you would even need parentheses but whatever here so the minutes hours times 60 will give you the minutes and then plus the leftover minutes and that would be totalmins and then i'm gonna add the names and i'm add the total to mins oh um should i keep some kind of sorted list i'll just sort it at the end yeah whatever so add the total mins and then that's it so now each name will look something like this in the hatch map with the times put a number of minutes and then i need to sort them all so i'm gonna go through um entry for map dot entry for list of integer in h mob dot get what is it like keys or something oh i see this what was it key list i don't know i've been working with a lot of c sharp at work i'm just i'm lost bro get value list hash map java no bro i just want the list no those values i think that's it remember correctly okay and then well dot collection bro sword val bang okay once again map dot entry no what am i doing i hope that's what it was called man string to list of integer val list integer times was entry dot get value string name is equal to entry i get key functions that sort times go through for into i equals two start at two remember times that size and then i want to um check the one two before and say if times don't get i minus times that i get i minus 2 is greater than 60 meaning it was or no it's less than 60 wait so less than it equals 60 right because in this case 11 minus 10 the time difference would be 60 right so one hour difference you get a 60 minute difference so less than or equal to 60 then you'll do answer so list answer dot add name then it'll return the answer and answer would be string list string answer new let's check this out ah what do you mean you expected a cha see i've been working too much in c sharp and c sharp the string class lowercase i think it's like a primary type in c sharp 2. what is it like though once again this shoe sharp it takes a car was it splits this whole string oh damn ah okay yes and then dividing running uh integer now of course and split it of course and yes work now what is this crap i added one oh yes work tle right here what is this out of order it's the same no you want to fight me don't you what account for duplicates manage the edge cases okay anyways this tells me i'm a fight okay now we sort the final one yes work what was the ah i've been working so much in c sharp this is not good yay i'll see you guys in the next video oh why'd i click that i'm using this
|
Alert Using Same Key-Card Three or More Times in a One Hour Period
|
least-number-of-unique-integers-after-k-removals
|
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used **in a** **single day**.
Access times are given in the **24-hour time format "HH:MM "**, such as `"23:51 "` and `"09:49 "`.
Return a _list of unique worker names who received an alert for frequent keycard use_. Sort the names in **ascending order alphabetically**.
Notice that `"10:00 "` - `"11:00 "` is considered to be within a one-hour period, while `"22:51 "` - `"23:52 "` is not considered to be within a one-hour period.
**Example 1:**
**Input:** keyName = \[ "daniel ", "daniel ", "daniel ", "luis ", "luis ", "luis ", "luis "\], keyTime = \[ "10:00 ", "10:40 ", "11:00 ", "09:00 ", "11:00 ", "13:00 ", "15:00 "\]
**Output:** \[ "daniel "\]
**Explanation:** "daniel " used the keycard 3 times in a one-hour period ( "10:00 ", "10:40 ", "11:00 ").
**Example 2:**
**Input:** keyName = \[ "alice ", "alice ", "alice ", "bob ", "bob ", "bob ", "bob "\], keyTime = \[ "12:01 ", "12:00 ", "18:00 ", "21:00 ", "21:20 ", "21:30 ", "23:00 "\]
**Output:** \[ "bob "\]
**Explanation:** "bob " used the keycard 3 times in a one-hour period ( "21:00 ", "21:20 ", "21:30 ").
**Constraints:**
* `1 <= keyName.length, keyTime.length <= 105`
* `keyName.length == keyTime.length`
* `keyTime[i]` is in the format **"HH:MM "**.
* `[keyName[i], keyTime[i]]` is **unique**.
* `1 <= keyName[i].length <= 10`
* `keyName[i] contains only lowercase English letters.`
|
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
|
Array,Hash Table,Greedy,Sorting,Counting
|
Medium
| null |
1,352 |
and welcome back to the cracking thing youtube channel today we're going to be solving lead code problem 1352 product of the last k numbers before we read the question prompt just want to ask you guys to subscribe help my channel grow i can make more videos and you guys can get those jobs in fang all right let's read it design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream implement the product of numbers class which will be initialized with an empty stream it's going to have a method called add which is going to take an integer number and appending that number to the stream you're also going to have a get product method which is going to be passed in integer k which is going to return the product of the last k numbers in the current list and we can always assume that the current list has at least k numbers and the test cases will be generated such that at any time the product of any contiguous sequence of numbers will always fit into a 32-bit integer without always fit into a 32-bit integer without always fit into a 32-bit integer without overflowing okay now that we've read the question prompt let's think about how we might solve this so we read the question prompt but now let's look at an example so we know that we don't want to be storing the numbers directly but we want to just be storing the product so that way we don't have to recompute the product every single time so in the beginning our product is just going to be one obviously if we set it to zero then we'd just be multiplying everything by zero and we wouldn't get anywhere it would just always be zero and we're gonna store all of our products and we'll call it data so in the beginning we're gonna get our five we're gonna multiply it by the current product and we're gonna store that in our data right then we get a four so this now becomes 20 and we're going to store that 20. and now we get a 2 so now it's 40 and we're going to store that 40 and on so times 3 this becomes 120. store that and then we get a four and this becomes 480 and now we have 480. cool so now let's look at some examples right so if we have k equals one we just want to know the product of the last k integers in the stream right so if k equals 1 it should just be the last integer here so how do we get that right what is the different how are we going to get 4 well we know that to get to our last product here the 480 we had to multiply the previous product by some value right and that value is four so the way that we're going to do this is we're always going to take the last value that we have so in this case 480 and we're gonna divide it by whatever one minus k is in this case so k is one here so uh right so this is going to be minus two so we're gonna look at in the array what is the minus 2 element so obviously the minus 2 element in python is going to be this one because it's the second from the end so we're going to take 480 divide by 120 and we're going to get four so that is the last element now let's erase this and look at the example of what happens when we have k equals 3 right so that should be the product of 2 3 4 which we see is 2 times 3 which is 6 times 4 we expect this to be 24. so again we're always going to take the last thing we have so 480 and we follow the simple formula of 1 minus whatever k is so three so this is going to be minus four so we wanna look at the minus fourth element so this is minus one here this is minus two minus three minus four so this twenty here so we wanna do 480 divide by twenty and that will give us what 24 right and that is our solution so essentially 20 what three values did we have to multiply to get to 480 right so we needed to multiply some things to get 24 right so what do we multiply by 20 to get to the last element so that's the reason why our formula works so essentially this is how we calculate it whatever it asks us we want to divide the last element in our you know data here so it's always going to be data of minus 1 divided by whatever data of minus 1 minus k is right and this value will be the element that we want to divide by in order to figure out the difference in between them of those products and this will work for us and we don't have to worry about you know k not being a valid one because the problem stipulates that we'll always be given a valid k here so we don't have to worry about it being invalid and getting a wrong answer so that is how you solve the problem pretty straightforward working off of you know how we multiply these things as we go along and as you can see we don't have to recompute things we can simply do a division which is going to save us time so let's go to the code editor and type this up it's really not that much code at all we are back in the code editor let's write this up so remember that we need to basically store uh the number of products that we've seen so far that way we don't have to recompute them so we're gonna say self.product is gonna be an empty list self.product is gonna be an empty list self.product is gonna be an empty list we also need to keep track of the current product so we're gonna say self.product is going to be equal to one self.product is going to be equal to one self.product is going to be equal to one now let's do the add method so there's two cases that we need to handle for the add method what happens when number is actually a zero and the case when number is not a zero so we'll do not zero because it's simpler so we're gonna say if num what we wanna do is we want to say self.products we wanna multiply it by self.products we wanna multiply it by self.products we wanna multiply it by our new number and then we wanna say self.product.append self.product.append self.product.append uh this new product oops self.product uh this new product oops self.product uh this new product oops self.product right simple enough okay if it's zero then obviously we don't want to be adding it to our products because when we get you know get product it could be the case that the denominator actually becomes a zero and then you have a divide by zero error and that's not correct so in this case what we want to do is we actually just want to reset our product uh to be equal to zero so we're gonna say self.products we're just gonna reset say self.products we're just gonna reset say self.products we're just gonna reset it to be an empty list and we want to say self.product is now going to be say self.product is now going to be say self.product is now going to be equal to 1. and you'll see what we do in this case when we do the get product method so if we're asked to get product obviously if we saw 0 we reset all of our products and if we're asked to find get product and we actually don't have more than k elements then that means that somewhere we accidentally had well not accidentally we basically had to get rid of our progress because we saw a zero so in this case we know that the previous k elements there was somewhere a zero in there and that's why uh we're asked to find k elements but we actually don't have k elements because we reset our products here so we're going to say if the length of self.products is actually less than k self.products is actually less than k self.products is actually less than k when this was called then we know that we saw a zero somewhere and we actually had to reset our products so we're going to return zero because somewhere in those k elements there was a zero okay so that's kind of handling the zero edge case what about the case where we have uh the amount of k we're given is actually equal to the length of our product so that basically means give me the product of all of the numbers that you've seen so far so in this case it's super simple so we're going to say else if k equals to the length of self.products equals to the length of self.products equals to the length of self.products in this case what we want to do is remember the product of all of the numbers that we've seen will always be stored at the last index of our products array or it's just going to be whatever our self.product is so we're simply our self.product is so we're simply our self.product is so we're simply going to return self.products going to return self.products going to return self.products in this case otherwise we actually need to do the division and see that we actually want to be returning an integer here so it is possible for us to get a float number so we want to just cast it to an integer so we're going to say return int of whatever remember the formula is always going to be self.data formula is always going to be self.data formula is always going to be self.data of whatever the last index in our value is or we could just use up i use self.data sorry self.products self.data sorry self.products self.data sorry self.products the last index and then we're always going to be dividing it by whatever self.products self.products self.products of minus 1 minus k is and that is how you solve it i just want to make sure that i didn't make any syntax errors and it looks like oh boy where did i uh minus 1 minus k solve dot products oh this should be self.product whoops oh this should be self.product whoops oh this should be self.product whoops okay when we run this that should be fine okay perfect yeah same variable different okay cool so we submit that and we can see that it works excellent what is the time and space complexity here well obviously for the init function all we're doing is setting up two variables this is going to be a constant time there's nothing here so for adding all we're doing we're multiplying a number constant time appending to the end of a list constant time or just setting a variable that's constant time so add this is also constant time get product obviously accessing the last element in an array by index that's constant time same here so all we're doing here the entire time complexity is going to be big o of one at no point do we do any operation which is not big o of one this was the reason that we use products uh we store the products instead of the numbers because if it was just the numbers then we would have to actually multiply them out each time and i'm pretty sure you'd get a time limit exceeded here so that is your time complexity what is the space complexity obviously you need to store the products here so the amount of products you store is just however many numbers happen to be in the stream so we're going to say o of s where s is the length of the data stream so we don't know what that is so we're just going to say we're going to end up storing however many numbers you give me in this uh data stream so that is your time and space complexity big o of one for the time and big o of s for the space where s is the length of the data stream that's how you solve this question pretty straightforward i think you see this pattern um come up in a lot of questions i think um what is a product of array except self uses a very similar um kind of solution to this so this is definitely not something unique you will probably come across this on leak codes so knowing that you can do this is definitely one to know otherwise if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to help my channel grow please drop a sub click that bell button so you get notified when my videos come out and thank you so much for watching have a great rest of your day
|
Product of the Last K Numbers
|
maximum-profit-in-job-scheduling
|
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
**Example:**
**Input**
\[ "ProductOfNumbers ", "add ", "add ", "add ", "add ", "add ", "getProduct ", "getProduct ", "getProduct ", "add ", "getProduct "\]
\[\[\],\[3\],\[0\],\[2\],\[5\],\[4\],\[2\],\[3\],\[4\],\[8\],\[2\]\]
**Output**
\[null,null,null,null,null,null,20,40,0,null,32\]
**Explanation**
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // \[3\]
productOfNumbers.add(0); // \[3,0\]
productOfNumbers.add(2); // \[3,0,2\]
productOfNumbers.add(5); // \[3,0,2,5\]
productOfNumbers.add(4); // \[3,0,2,5,4\]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0
productOfNumbers.add(8); // \[3,0,2,5,4,8\]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32
**Constraints:**
* `0 <= num <= 100`
* `1 <= k <= 4 * 104`
* At most `4 * 104` calls will be made to `add` and `getProduct`.
* The product of the stream at any point in time will fit in a **32-bit** integer.
|
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
|
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
2118,2164
|
316 |
hey guys welcome back to another video and today we're going to be solving the lee code question remove duplicate letters all right so when you just look at the title uh the question seems pretty simple right but there's actually a small catch in the question which makes it slightly complicated all right so in this question we're given a string s and we want to remove duplicate letters so that every letter appears once and only once you must make sure that the result is the smallest in lexical graphical order so this small line over here actually changes up the question quite a bit okay and among all the possible results okay so let me just show you what does this line mean over here so over here we have a string so this is b c a b c so first our first step would be what over here are the repeating letters so the letters that are repeating are the letters b since we can see b two times and the other letter that is repeating is the letter c is also there for a total of two times but a on the other hand is not repeating so we have that so now what we want to do is since we have two b's and we have two c's we wanna remove one of each now in this case let's say we remove the first b and then we remove the first c so in that case our output will be a b and c and that is also the output which they gave us over here so that's correct but one more thing that we could actually do is we could remove this b over here and this c over here because there's nothing stopping us all the condition is that we just want one of each letter so we can remove this b and this c over here and that actually gives us the value of b c and a but why do we choose a b and c over b c and a and the answer to that is because abc is closest or actually in this case it is exactly the same as the lexicographical order and what is lexicographical order mean well in simple words it's just a through c in that order so in this case abc is closest to that so that's why we end up outputting that uh this is another uh example over here and the answer that they output it is actually this over here and in order to kind of show that to you a lot better uh what i did is i just wrote a small program over here and what this program does is it does not consider this over here but instead what i made it do is it removes everything up to the last instance of that letter and i'll be going through how the code works later on so in this case i gave the two same two test cases bc abc and this one over here okay and let's see how our program uh perform so you can see wherever there's a hash those are the letters that the program removed so it removed the b and c over here and we got a b and c so we just got lucky right so we ended up outputting a b and c but over here we got a d b c but that's actually not the answer that's incorrect the answer which we're supposed to uh give out is acdb so hopefully you see the difference between adbc and acdb is closer to the lexicographical order so in this case after a we have c which makes sense and after c we have d both of them make sense but after d we do not have b that over there is slightly incorrect so you can kind of think of it as like these three letters in the right place but over here when you go over here after a you have d which is correct but after d you have b which doesn't make sense b comes before d and so in this case you can kind of think of it as just being two letters that are in the right order so which is why we would prefer to output this value since it's closer to the lexical graphical order so hopefully you understood that small difference in the question because i think the question itself is a little bit tricky but now what i want to do is i kind of want to go over how can we actually solve this question and what are the steps we're going to take all right so this is what we have over here and i actually don't have my drawing board with me so i'm just going to be using this okay so anyways this over here we'll just kind of look at this as our input so we have c b a c d c b c so you can just kind of look at it and tell there are a few repetitions other than the letter a i think okay now our first step over here is that we're actually going to build a dictionary now what exactly is going to be the purpose of this dictionary so what we're going to do in this dictionary is we're going to be iterating through our input over here and each time we iterate over it we're going to update whatever letter we're on with the current index so what exactly is this going to give us so let's just go through this so first we're going to give it c right and where do we find it at an index of zero so we're going to add that over there then we're going to give it b so we have b and where is b well it's at an index of one and then finally we have a which is at an index of two and then again we have c so now in this case what's gonna happen is we don't create a new instance of c but instead what we're gonna do is we're gonna go back to our instance of c which is right over here and we're going to update this with the new c value and in this case the new c value is nothing but 0 1 2 3. so this is telling us that the so you can kind of understand that when we keep doing this by the ending of this what's going to happen is we're going to have a dictionary over here which where it has each letter and the last index of it so the last index where that certain letter was found so what i'm going to do is i'm just going to fill out this completely and show you how the end result looks like all right so this over here is our completed dictionary so let me just show you one example so let's say we go to b and then b has a value of 6. so what that's telling us is that at the sixth index which is right over here that is the last instance of b we're not going to have any more b's after that value over there so we can actually use this to our advantage in order to build the answer so now let's just look at it naively and let's not actually consider uh this condition over here that we had the smallest lexicographical order so in this case uh in order let's just think of removing all of the letters so when we just want to remove all the letters a simple thing we could do is we can iterate through our strings and each time we iterate so we would go to c we would check the value of c in our dictionary it's seven and we're going to compare that with the index we're currently on so if we were at c over here we would be at index 0 and index 0 is less than index 7. so in that case we're going to end up removing everything which is less than 7 because what we're doing is we're removing everything but the last instance of it so doing that actually makes sense and that's exactly what i did over here and that gave us adbc but again that does not follow the lexicographical order that we have so in order to also account for that we're going to add in a small condition which makes this a little bit more optimized but before we do that i just want to show you something so i opened the python over here and i actually didn't know that you could do this but it's pretty cool and we can actually use this to our advantage for solving this question so over here i'm going to have the letter a and what i'm going to do is i can compare it with the letter b so a and we're going to check is a the letter a greater than the letter b so enter and it says false and that makes sense because b comes after a and just to kind of show you what i'm talking about let me remove this and i'm going to say is b greater than a and technically this should be true and it is so hopefully you kind of understand how we can use this in our questions so this is a pretty important tool that we're gonna use and i honestly did not know that you could do this okay so now that we have that let's see how we can build our answer so we're gonna start off with an empty results list over here and the reason we're using the list and not a string is because it's easy to manipulate our values inside of a list okay so the first step that we're going to be doing is we're going to go and iterate through our inputs so we go to c and when we're inside of c we're going to check is does c exist instead of our results it doesn't so if it does not exist that means we want to add it to our results but before we add it we're going to go through a few conditions but one of the conditions is do we have an empty list we do so in that case we're just going to skip that and we're directly going to add c i'll be going over the conditions shortly okay so now we have c and now the left next letter is b so the first thing does b exist inside of our results it does not exist then in that case we need to add it before we add it we're going to go inside of our little while loop now the first thing that we're going to check for is we're going to check is this value of c greater than b over here in other words is the last value greater than the value we're about to insert in this case the answer is yes c is greater than b so in that case what we're going to do is we're going to get rid of this value over here the reason for that is because since it is greater that means it would be better for us to have the smaller value go before the greater value since we do want it in lexicographical order so that's what we're going to be doing but before we do that we have to check a few more things we're going to check is this value of c the last iteration we're on and to do that we're going to check what index are we currently on so we're currently on index one and the last iteration of c is at index seven and that's basically telling us that hey this is not the last time you're going to see c at least one more time after adding b so because we know that and we're guaranteed that according to our dictionary over here we're going to remove the c and in place of it and we're going to actually keep doing that for all the elements so let's say after c we had the letter d then in that case we would remove d uh if all the other conditions match as well so in this case we actually ended up with an empty array and since it's empty what we're going to do is we're just directly going to add b so i'll go through this a little bit faster and now what we want to do is we're going to go to the third letter which is a so now we want to go through our checks before adding a so the first thing is b greater than a it is b comes after a so in that case what we're going to do is we're going to get rid of b but before we can do that we want to check is the instance of b does it does b come up again later on and the answer is yes b comes up again at least once so because the last index is six and the index that we're currently on is actually zero one two so we're currently on index two so that means we can remove the b and that's what we're gonna do so we're gonna get rid of the b and in this case again we're actually going to get stopped because and now our list is now going to be empty and that means that we need to add a okay so um now finally we have the next letter which is c okay now once we come to c over here you can kind of see why we're doing this condition so c does not exist over here and now we're going to go to the a and check for a over here so a over here is at the index 2. that's the last instance of a and but we're currently on index three so what that's telling us is that if we remove a over here we're never going to have that in our result but the thing is we want at every letter at least one time so that it's not correct so because of that we're not going to do anything to our list over here and we're just directly going to add c okay so we add c perfect now we're going to go on to the next letter which is d in this case what's going to happen real quickly is that d is just going to get added so we're going to have d over here and after d over here we have the letter c okay so now we have b and since we have b we're going to do the check so can we actually uh clean up our area furthermore and we cannot because uh we already went through the last instance of d and we're way past the number four index four so in this case what's going to happen is the area doesn't change but we do have to add b so we're going to end up adding b and the reason that we have to add it is because b already it does not exist already okay so b does not exist already so we're going to be adding that over here and that's really the ending so technically after b we will go to c but c already exists over here so nothing's going to happen and this over here is going to be our result and what we're going to do after this we're going to use a join function and we're going to combine it into a single string so we're going to have a then c and then d and then b and if you want to go down to our answers or let's just go up uh over here that's the answer a c d b okay so hopefully that all did make sense i try to go through it as fast as possible and now i'm just going to go through the code which should be pretty simple all right so let's start off by creating our dictionary that we had and i'll be using comprehension in order to do so over here we're going to have our character and to that we're good the value of it is going to be the last index so to that we're just going to have the index and how do we get this so to do that we can do index comma care and to actually get the values we're going to be using enumerate so in a numerate and we're going to enumerate the value s and if you don't know what enumerate does it's going to give us a tuple value of the current index that we're on and the corresponding value so in this case that's going to be a string so that's going to be our dictionary over here and now that we have our dictionary we're going to go inside of a for loop we're going to be iterating through each of the characters inside of s and one more thing we're going to be doing is we also want the index so we're actually going to be enumerating it again okay so to do that all we're going to do is we're going to do 4 and then we want the index comma the current character inside of enumerate s so enumerate as perfect so now that we're inside of our for loop we're first going to check whether the current character so if this character is already inside of our current results so if it is already inside of our result then in that case we don't need to do anything and speaking of results we actually create our results array over here so i'll just call it res and it's just going to be an empty list okay so if our character is not inside of res only and only then are we going to add it to it so let's just directly do that so let's do res and we're going to append our characters so let's append and then care perfect but before we actually add it to our results we had a few checks right we wanted to clean up our results eric and that's exactly what we're going to implement over here using a while loop it's a while and let's just go through each of the conditions that we have so first we're going to check if the current index we're on is less than whatever the value that we're getting out is so in this case the value of our concern is going to be the very last value and how do we get that well we can just use negative one so the index negative one refers to the very last value okay so what we're going to do is we're going to check for this value inside of our dictionary uh in other words actually i should be saying we want to check for the key so this over here corresponds to a letter and we're going to go to the dictionary and check what is the last index the dictionary is at and if the index is greater than whatever that value over here is then in that case that means we cannot go and remove those about that value inside of our results so that over there is one of our conditions and then since we have several conditions we're going to be using and the other condition that we have over here is we want to check if our current character is actually less than whatever this value over here is the last letter instead of results so let's just do that real quickly so if our current character which is care if that is less than whatever the last value is and what exactly is the last value well did they get that again we get a res and then we go to the last index negative one okay perfect so those are two of the conditions and one more condition we actually had is what if we have an empty list so we want to consider that as well and rest so saying and rest is the same as saying if res has a length so as long as res is not none or empty okay and that should be it for our three different conditions and each time what we're going to do is if we go through this we want to remove that last value and how do you remove it inside of a list well you just use rest.pop list well you just use rest.pop list well you just use rest.pop and it gets rid of that last value all right perfect so that's really it for the uh if loop for loop over here and after the ending of this we're going to be getting a results array uh which has all everything that we need and uh the problem is it's a list so finally we want to convert that into a string and to do that we can use the dot join function so dot join and what are we joining we're joining all the results inside of our string so let's submit this actually a small thing over here so what's happening is so in the while loop we go through the conditions one by one and the problem over here is what if our results list is empty and we end up going to one of these conditions so in that case we're actually not actually we're not actually going to get a value because results is empty in the first place so in order to kind of fix that what we're going to do is we're going to check if results exist and if it's not empty in the very beginning so in that case we're not going to get an index error so let's submit that 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 thank you
|
Remove Duplicate Letters
|
remove-duplicate-letters
|
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
|
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
|
String,Stack,Greedy,Monotonic Stack
|
Medium
|
2157
|
1 |
let's solve lead code number one to sum this is the most commonly asked coding interview question in this question we're given an input array and a Target value we need to find two numbers that add up to the Target value in this example 2 plus 7 is equal to nine and we return their indices the index for 2 is 0 and for seven is one so return 0 1 as the output we know that there's exactly one solution so we don't have to worry about finding multiple Solutions or not finding a solution so the most logical intuitive way of solving this problem is to check any combination of the numbers to see if their sum is equal to the Target value let me copy the example two over here let me also add their indexes so my Approach is to create two pointers the first pointer at the first value of the array and the second pointer J would be I plus one we check three plus two does it equal to six no it does not so we increment J now we check three plus four does it equal to six no it does not so we start over and increment the eye once we increment the idea would automatically increment it because J is I plus one so we check two plus four does it equal to six yes it does so we return there and this is one and two as shown here okay so let's uh code this real quick we'll create a for Loop I equals to zero I less than nums dot length I plus we create another loop with J equals to I plus one J is less than nums dot length J plus now we check F numbers at I plus nums at J equal to Target if it is equal then we return the indexes I and J if I run the code we see this is a valid solution uh let me also submit this and this is you know it's a valid solution it's working solution it gives the job done but if you get this question your interviewer would ask you uh to come up with an algorithm that is less than o of N squared time complexity as you can see the solution is not very efficient the time complexity for the solution is O of n square and we can do better there is a smarter way of solving this problem we can just do it in one Loop by utilizing a hash map okay so the way that we can solve this problem by using only one Loop is to iterate over each of the elements so our Loop will start here we'll check Target minus the current number so 6 minus 3 is equal to 3. do we have a 3 in our hash map we don't have so we will store its location I mean its index at in our hash map then the loop goes to the second element six minus two is four so we need a 4 that we can add to this current value it would give us a Target value of 6. we know that we have it in our array we can because we can see that but we don't already have it in our hash map so what I'm going to do is store the index for the 2 and our hash map and then we move to the next element in our array four so what number do I need that we can add to this current number would give us the target value we know that Target 6 minus 4 is equal to 2. so we needed two and since we already have two in our hash map so we can return the index for the two and the current index for the four and that is our solution all right let's go to our optimal solution first of all I'll create a hash map and I can set it to an empty object and I'll Loop over each of the elements let I equals to zero I less than nums dot length I plus okay current number because that's what we use in our example current num equal to nums at I and const num to find equal to Target minus current num and then here I'll check f for hash map has num to find and I'll add uh greater than or equal to zero because we know that the arrays are 0 indexed so here you see the index for 3 is 0 and if I don't have this check it will fail because 0 is a falsy value and so if there is already a value in our hash map we return that value from our hash map along with the current index if we don't have the value that we need then we can add the current numbers index to our hash map so that would be hash map current num equals to the current index let's run the code as you can see it's been accepted let me submit this working perfectly this was our solution our time complexity is um of n which is better than the O of n Square in our space complexity is also off and due to the hash map foreign
|
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
|
841 |
Everyone welcome to my channel, so today I will do question number 5 of my Grahas Palace, this is also long term, this is open which you can open from zero number three, okay then you will start from room zero, okay if you can open room van then room. You go to the van, there are 30 and 1, which means you can open three, you can open 0, you can open the van, okay, so in this way you will do more and see whether you can open all the rules or not, okay, do you have any room? That only then you can open it, so you just have to check whether you can open all the rooms or not, okay, room number zero is open, so I went here, I saw that there is a van, so van means you can open it, so it is okay. I have opened the van, open, ok, room number 3, this is the room number, ok Room number 3 has opened, ok, room number is zero, ok, so this is the Roman number on the van is also already open, ok So we have explored the van which is where we came from here. Now let's see its three. Three is also open double ready. Okay, so see the rule number of lock is left locked. So let's see how to use it. So you one. You are paying attention to the thing here, which is zero thundex, the room number is zero, where can you go from this, where can you go to the van, you can go to the three, which is the van, the room with van index, on the room with zero. It is okay for the van room. Similarly, from the one room, you can go to the one room. It is okay and from the 3 bar room, you can go to the zero room. Pay attention to one thing, you must be feeling this. What is it that I had told you yesterday that you can go to 0123012 in the graph Find Path Existing, so today also we have to do the same thing, it will be done with BF, but today I will tell you only DFS and it is okay for you to do BFS yourself, that much. If you have understood, then we will solve DFS and what will we do? Just travel. Okay, how many rooms do we have? Four romances, zero, one, you will mark three. Okay, if all of them are true then my answer will be true, meaning. We have visited all the rooms, if any one fails, then the answer will be false. If any one fails, it is fine, as it will be in this case, so simply what we have to do is to write a simple DFS [ what we have to do is to write a simple DFS [ what we have to do is to write a simple DFS It is fine till here. It is clear, there will be a simple code. What did I say that we will take a code named 'Visited'? named 'Visited'? named 'Visited'? Okay, and we will write ' Okay, and we will write ' Okay, and we will write ' Zero Van Tu Three' in starting, all will be false, no Zero Van Tu Three' in starting, all will be false, no Zero Van Tu Three' in starting, all will be false, no one has been visited, right now, let's write a code named 'DFS'. Okay write a code named 'DFS'. Okay write a code named 'DFS'. Okay DFS, what will I send in this, which is given by our rooms and where can we start, okay and we will send widgetized, this is in the function, we will keep populating it, so now we have the source, so first of all, obv. The source is open for me, so we will make the visited source code true, after that what I said, where can we go from the source, they figure out where they can go, they see the end and where they can go. Let's take note of that, okay, what will I get from Rooms of Source, what will I get here from Room Sub Zero, I got van and three, neither of them will die one by one, DFS will die in van also in three. Also DFS will die and will keep on visiting every time. Okay, so let's write the further code. It is simple that if this note which is visit in room source is not there then this time there will be note. It will be populated, it will be updated, it will be widgetized, okay, this is my DFS finished, that's it, when it is finished, we will check after that, our answer will also be there, it is simple, you have to keep the widgetized one in your mind, then a simple one. There is a for loop whether it is from the note or from the source. Wherever you want, where can you go from there? Okay, let's visit there, let's do DFS, if it is not visited, how simple it is and like the graph every time. What is the time complexity of BF? Okay, let's go straight to coding. Okay, first of all, what did I say that first of all, brother, I should go to the start side of the room. How many rooms are there? Okay, and make a vector on which you will keep the status of all the rooms. Neither vector nor rule, if not visited, we will also send a visit, we will call, then what did I say, what will we check, i.e. i.e. i.e. van room is found, if any one is required, we will do NOT false but it is not so, then we will return through, i.e. all of them are visited. OK, now we i.e. all of them are visited. OK, now we i.e. all of them are visited. OK, now we simply write our wide DFS, OK, we are sending the room, OK, we have visited it, OK, after that where can we go to this source, how did it know by applying a for loop, so where? You can go to Rooms Off, what will you get where and where else can you go, okay, if not off, West End Note, if this note is not widgetized, then visit it, DFS is not there, once the note goes, it is storing it as widgetized, ok. Our DFS was just so small, let's run it and see. Submit and cipher able. You pass all the data. I hope you have understood. If you have any doubt, please visit comment section. Always remember graph. Don't be afraid of easy graph. Ok, I am going to start the graph in the playlist today, ok today or tomorrow also I will start and will put topic wise theory one by one and will also put base questions on it, ok so wait for it any doubt section video thank you
|
Keys and Rooms
|
shortest-distance-to-a-character
|
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_.
**Example 1:**
**Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\]
**Output:** true
**Explanation:**
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
**Example 2:**
**Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\]
**Output:** false
**Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room.
**Constraints:**
* `n == rooms.length`
* `2 <= n <= 1000`
* `0 <= rooms[i].length <= 1000`
* `1 <= sum(rooms[i].length) <= 3000`
* `0 <= rooms[i][j] < n`
* All the values of `rooms[i]` are **unique**.
| null |
Array,Two Pointers,String
|
Easy
| null |
880 |
Hua Hai Song in MP3 Tu Yeh Question Hai Decoding Arvind Act Ko Deputy Friends Basically Director Nirkhyou Hai Ek Train Hai And Got From Main Side That Train We Have To Write A Temple Tubelight Straight To Take Off To One Any Other It is for the media industry and they have to decode the rate setting and we do not have to add tempered glass edit. Okay, if we have guava in decoding, then what is the first rule that readable character time, read one tractor at a time. Okay, late here, 10. If there is input, then first once in one character, fatu, it is okay, it means it is school, okay, if you subscribe to it, then it is considered entertained, okay, I am late, so my input spring, do not take even one seat given to me. This is my decode, this incident is Singh's, this is the liquid state, the important thing is ABCD 2, if you want to write half of it, then you will read it at one time, first director, ghee acid, now as soon as the to-do list is done, at acid, now as soon as the to-do list is done, at acid, now as soon as the to-do list is done, at this time, you are blind - 110 as many as we have appointed in ours. this time, you are blind - 110 as many as we have appointed in ours. this time, you are blind - 110 as many as we have appointed in ours. One, it will be final, okay, so one question, one way, you are free to solve this question and ask me, when it goes to our Sunday, then which character is placed on the required position, that is our answer, okay, so Amit. For example, by placing ABCD 2 and someone asks us which character is hanging on one, then we will see that this is two, this is three, this is phone and this is fiber, then our answer will be a complaint about this, our answer is this. We have to return which character is placed above the decoding strain on you, so one way to do it is that brother, if it is mc2 then copper should be done directly, also make a string, this is C, we put it in that time, first withdrawal, then Kerala. Like if two came then it was copied to two minus one tidal one time and that it will ask for submerged position only if it asks for more then it will be able to keep it on four and will return as soon as possible after the limit exceeded table that then memory should be used in your program otherwise I am not saying that the size of the spring can be increased a lot in it, so I will come in printed form and you will be ganged up and attempting question 2. Okay, so we can make this on friends, so many stars and things are there till date. If you cannot make a train, what will you have to do? Now see what is there in it. What is the thing that late ABCDEF input screen is ok then what will we write from MP3 FROM ABCD This is our fist hit and we need it. Next number is 3456789 depth. Okay, the input I am going to give is ABC, it is okay, there is no seven position in it, so I will record the message and make it like this, so the stand is kept in the premises, it is given, so now the thing is that if you do not decode the message. And I would like to see in my original print which places are kept corresponding to the seventh, then you will see that the one who is kept at the worst position, then the one who is kept at the fourth position, the one who is kept at the first position. Keep it okay, whatever is kept in the praise and position should be yours. Keep it in the seventh position because spring is restored. Talk to normal as it is written below. If it is written in such a way, then that condition should be suppressed and best of all, this is made from a good to-do list. So now it is 1234. this is made from a good to-do list. So now it is 1234. this is made from a good to-do list. So now it is 1234. If I am asking you what is kept on the phone then it is kept on four or you have kept it on and I was asking but if it is a factor then the problem is that it must have been kept there which is kept switched off, it is a common sense thing because If you are fitting it at that time, then basically I do not need to decode my friend. Yes, why is it? Because if I extend my SIM from the line and turn on its Ashok Singla Satish Power Match Saver mode, then what will come from that? If you make it then the one which is placed on one is placed on this edge, someone is saying brother tell me if you have placed the pipe then I will do 5.3, I will be stopped again, 5.3 will come do 5.3, I will be stopped again, 5.3 will come do 5.3, I will be stopped again, 5.3 will come that it is placed on 2532, keep it upwards, ok then There is no need to decode what to do now, what is the day, now what is the thing in this that if my ke veeron jaata mai a mike ke a begum 040 will go, then the character on which my change has happened, my cases have happened on this character. What is the meaning of saying that character, my answer is 16 that exit there dates, you will record it and write it HP will go midding like this 123 45678910 objects deeper than you are on fluid ok then what will you do also you will spend hours at et mode how much is the lens of best color You need gram flour so that it remains the best Indian till you. My uncle became red, so what will we do in 1984, so this is zero, now it is zero, we are holding our index hostage, so it means that what is kept at the end, this is what I used to sell, which is now a trick. That character is placed at the end and will be my answer. If I somehow do the Gujjar words 'K' and 'K', how will I do the Gujjar words 'K' and 'K', how will I do the Gujjar words 'K' and 'K', how will I request that an object 'K' mode request that an object 'K' mode request that an object 'K' mode is on the keyboard which is the length of my best friend, I will keep doing that. I am fine, so what should I do? I have to do some electrical cases and the position at which my K becomes zero should become my answer. How many times will I press the side? So what do we do first? What do we do? So I am late because I am kept alive A B C D2 Send this video to me so that I can take a print out after decoding it because at that time I will put limited in it but after decoding you will want its length. What will be the deposit length so that I can put it without media, it is b2c to ok. This will be withdrawn, we will take one side, we will add that it has been motionless for days, then if we start traveling and this trick is next, then if a character is coming, it was lowered in acidity, it will increase by one of ours, so we will go here. This holy place will be done from the side, then what is this to come, you will say that if it is a digit, then as much as your last size is, taking its tips, then the mediator who came here is 490, so he has come here and given fight, sex and this tattoo to edit and If there is skimming but then it will go to the toilet. Okay then A B C D A B C D2 Max Decode The Amazing So its length will be so Android that now what I have to do is this trick that this trick has been decorated its length I will consider the extra oil added middling as the best. Suppose it is being done, then what will I do, I will use it on the side in some way. Okay, and the benefit of using it on the side is that I should keep it somewhere, remember the mode size. So that it does not happen anywhere, see how it will happen, I will take one form and as a friend I request to end what length and breath and it is our input that these are the first time, whatever length it is and I will come to Uttaranchal with torch light for days. On the left city, this will be right click on it - - click on it - - click on it - - and there is a deposit singer in the science academy extract side, twelfth it is the comment spring, put your best reminder, I will take bath that you will do it in the middle of the night, that mode side of an object, this has to be done every time, good. Okay, this is what I have to do for every thing and the mode of the object will end, so what to see after that is that if Meerut becomes zero or opposes that and just on the opposite character, draw a character that dot s one. T-shirt, one. T-shirt, one. T-shirt, flash lights, this rice character here, what I try to do, is to test that Bittu, this character, then take that character seriously, that it is an Android character, tiles, starting from the tree, if its source is known. And the character on which I am is not edited. Voucher is ok, so what will happen to me, the same answer will be there, then I will put it in this case, if this is happening, then I will answer my and return. What will I do, I will return that character to CH. Okay, so this is done, it is mine that on 10 and on that character which will be under that character, but we will try on our own that if something has to be done in this fort then that. If you have become a poet on your own, then what will we do for this, who is my friend, this Bittu Sidhi 21, I am traveling from here, so his side is traveling, it is fine, it is 12000, that is, when I am standing here, standing on the di, if How correct will it be for my screen, as here it is divided into two, because of this, whatever length is given, because you can see here, friends, now if I come here, if only one character is reduced, then its length will increase. 5 Printers If I go back to the store, I will meet one more character. 1124 Now this episode is double here, when I am here, its length will increase. You and everyone are here, I am here, its length will increase, so what will I do? Which is my loop that from end minus one to I greater nickel 205 - - 205 - - 205 - - ok what will I do in that one which is my character this is the four these trick objects in chat you my character is that one digit character dot sid that digit Scene I remember you, whatever my side is, I will divide it by the side which is the interior audio of that character. What I mean to say is this is 12.the so 12.2 will go to mean to say is this is 12.the so 12.2 will go to mean to say is this is 12.the so 12.2 will go to my side now I will reach here okay and if that is a tractor Ne does not mean one digit of Apps or sites - - then maybe it will become of Apps or sites - - then maybe it will become of Apps or sites - - then maybe it will become one, then what is the turn digit is not there, here means it is referred to the affidavit is less when Bigg Boss is going back or still from. By doing this all around, this is my size, this work is being done, so what is the size difference, and every time what I am checking is the mode side of an object, so now whenever one of my objects will go to 520 and juicy, what is it? If there is no digit then I will return the happy character. Returns are. Now let's look at the triangle to see how it will be done. Now these to-do's are see how it will be done. Now these to-do's are see how it will be done. Now these to-do's are its length. Deposit in this is for Leo. Is the recording label okay? So when 12:00 If he recording label okay? So when 12:00 If he recording label okay? So when 12:00 If he comes here for the first time then there will be an object quarter that our duty is that I ca n't do anything, it's a qualified fee, you only Bheem has taken that Bigg Boss 252 today, you have taken 5000, then you should do it here. But instead of the size, I will be fine here. Okay, now I will do it again that this is also not received by the most significant teachers of an object, like this in front and then I am here that instead of Salman's here, my time. You will go to the side of 5.5, what is 202? time. You will go to the side of 5.5, what is 202? time. You will go to the side of 5.5, what is 202? This is the answer that I have kept here, it is not a customer answer, in what way I have grown it by reducing the side and then you can subscribe. This is Mintu Situ, so if you open it, this will also happen. A B C D2 and opening it will be A B C D and this is what the whole family needs because the point to free is 455 that our head is placed so it is working very well in India Papa so Now let us fold it and see, let's say it is two digits, so what will we do now? First of all, we will determine the size, then what we will do is, I will use this trick of ours, I will add it to its life, it will travel, we will repair it. Now let's see what else is wrong on the channel. Okay, if I have this character which I have taken out in the string, just two that is one digit, yes, what do you have to do, these are literary items, which was special, the old one * interior which was special, the old one * interior which was special, the old one * interior dot print. If it is okay to make a straight and A plus switch for the one who is not an actor, then if life is in counter, then definitely read or make this part and what to do with multiplication from some sides, take this tree plus and make it A friend, then this is here. If I come, I will get my - then what will I do, which is get my - then what will I do, which is get my - then what will I do, which is my hours, which is the track, which is the list, which has been given from da2 cells, I will contact the travels, from behind, that this fort, Kayan tower equals to a, good thoughts were the land, a minus ONE IS GREATER THAN EQUAL TO 08 - - a minus ONE IS GREATER THAN EQUAL TO 08 - - a minus ONE IS GREATER THAN EQUAL TO 08 - - Okay, now here I will keep the chart at the back so that if I have to write in the bar, then s.no will go on the right side. Now and every time what s.no will go on the right side. Now and every time what s.no will go on the right side. Now and every time what I will do is whatever I say, the mode cycle of an object. A milk che delete its size according to the one that is only the character that has been taken now a character dot this digit sub character will be done soon subscribe that divided by that in teachers dot parts king a plus b h a good okay apps if If there is no digit then it will be nothing, size - - etc. Okay, will be nothing, size - - etc. Okay, will be nothing, size - - etc. Okay, so here I have handled my size decrease till inside the Android, so here what will I do, I will check only the question, Mera has become zero and the character of 'Ha' is dot. S digit, character of 'Ha' is dot. S digit, character of 'Ha' is dot. S digit, which request for time will I make, I will return that character of mine because I have to return tax, money, this will have to be done by you and if it comes out of the room, which is heavy, still I will return, I am free at this time. So what I did here was run the loop from zero to the length of my screen, break the I plus character C2 h5 and add this character to the string and if the character is a digit, then the back side of our side is as much as till now * Value of Posted Key End The is as much as till now * Value of Posted Key End The is as much as till now * Value of Posted Key End The size will not go, then we challenged, I came a little behind the length minus one, from the extra to the end, history EACH as my character, after that with an object and anywhere else the person is unemployed and the character David means so I do I am staying and subscribed means the letter which is a desert on a cigarette is ghee, then the jawara of size will be divided by it size - - so it remains inside size - - so it remains inside so all this is done let's see what verdict comes ok so one This is our coming festival and so at some places its size is becoming zero, so there is a guide in this, basically, here, what I had kept in play, it was overflowing because that was the length of this system, it had increased a lot. So I had to cancel it and send this model here so that there is no problem with type casting. If I try to do all this after submitting, then the summit gets lost. Well, I submitted. The time is free milliseconds. If so, please let us know if you liked it and whatever you think, you can put it in the comments below.
|
Decoded String at Index
|
rectangle-area-ii
|
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
* If the character read is a letter, that letter is written onto the tape.
* If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total.
Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_.
**Example 1:**
**Input:** s = "leet2code3 ", k = 10
**Output:** "o "
**Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ".
The 10th letter in the string is "o ".
**Example 2:**
**Input:** s = "ha22 ", k = 5
**Output:** "h "
**Explanation:** The decoded string is "hahahaha ".
The 5th letter is "h ".
**Example 3:**
**Input:** s = "a2345678999999999999999 ", k = 1
**Output:** "a "
**Explanation:** The decoded string is "a " repeated 8301530446056247680 times.
The 1st letter is "a ".
**Constraints:**
* `2 <= s.length <= 100`
* `s` consists of lowercase English letters and digits `2` through `9`.
* `s` starts with a letter.
* `1 <= k <= 109`
* It is guaranteed that `k` is less than or equal to the length of the decoded string.
* The decoded string is guaranteed to have less than `263` letters.
| null |
Array,Segment Tree,Line Sweep,Ordered Set
|
Hard
| null |
1,759 |
hey everyone today we are going to solve theal question count number of homogeneous substrings okay so seems like we have a lot of patterns for this question right so when I feel that I usually think about output with small input so let's think about the input is only a in this case there's only one pattern right single a so that's why output is one and I look at the input is a so in that case we can create a two single a and uh like a combination of like a and a so this is a one pattern so that's why output is 2 + one and why output is 2 + one and why output is 2 + one and C so uh let's focus on input is a AA in that case we can create three single a and uh um a we can create two AA and we can create one a AA so that's why output is 3 2 1 and six so now you can guess um so input is a so in the case uh we can create four single a and 3 a and 2 a and one a and then total Four 3 2 1 and 10 right and uh input is a in that case we can create five single a and 4 AA um 3 a 2 a and then one a so total should be 15 yeah so seems like we have um solution pattern right here I summarize the main point so every time we find the same character we can accumulate the current length of substring to Output so we will add the number of from bottom to top so 1 2 3 4 5 so because when we iterates through the input string so length of string start from minimum to maximum so we use two pointers for length of string so let's say left and right so what I'm trying to say is that so in the previous um examples so we create like a five single a like a four AA and three AA something like that but uh we start from um like index zero to um last index so length of substring is a um minimum right at first so then um iterates through one by one until we find a different character or end of string so in the case um length of substring is getting longer so that's why we uh we will add like a from bottom to top like one two three four five so it's like a reverse of like 5 4 3 2 1 but the result is the same right 5 + 4 + 3 + 2 + 1 = 1 + 2+ 3+ 4 + 5 so + 4 + 3 + 2 + 1 = 1 + 2+ 3+ 4 + 5 so + 4 + 3 + 2 + 1 = 1 + 2+ 3+ 4 + 5 so that's why no problem okay so let me demonstrate how it works now we have 5 a and we use two pointers left pointer and right pointer start from index zero and this is a result so initial be zero and first of all we find the first a and this is a one pattern right so how do you calculate it's simple so right minus left + one so why plus one so that's left + one so why plus one so that's left + one so why plus one so that's because this is a index number so if we don't have this one so 0 minus 0 is z right but uh we find one so that's why we need to plus one so in this case we add one to result variable and the as I told you this is a um we have to accumulate the length of substring so that's why plus equal here so in this case result is one and then move next so again we find a so in that case two not two 1 minus 0 plus one so in that case total two right so add plus two to one so total three and then move next so again we find one and now right pointer is two 2 - 0 + 1 is three right so that's why 3 + - 0 + 1 is three right so that's why 3 + - 0 + 1 is three right so that's why 3 + three and six and then move next we I find the a again so right pointer is now index three 3 -0 + 1 is pointer is now index three 3 -0 + 1 is pointer is now index three 3 -0 + 1 is four so that's why 10 and then next so now right pointer is index 4 - next so now right pointer is index 4 - next so now right pointer is index 4 - 0 + 1 is five right so that's why result 0 + 1 is five right so that's why result 0 + 1 is five right so that's why result should be 15 so in this case output is 15 very easy right okay so let's see the another case so what if we find a different character so let's iterate through one by one so until index one I think it's same as previous example so in this case uh left and right is zero and zero so that's why result is now one and then move next so now right pointer is one so 1 - 0 + 1 is two so three 1 - 0 + 1 is two so three 1 - 0 + 1 is two so three right and then move next so now we find a different character so a versus B so in that case so we know that this B is the first uh different character right so in that case um we need to start from here so that's why output uh not output update left pointer with right pointer so now left pointer is here and then um before we iterate through next character so this is a new first character so add plus one to result so in this case um four and then move next and again we find P so in this case our right pointer is index 0 one 2 three so three and then right pointer should be index two so 3 - right pointer should be index two so 3 - right pointer should be index two so 3 - 2 is 1 + 2 so that's why um add plus two 2 is 1 + 2 so that's why um add plus two 2 is 1 + 2 so that's why um add plus two to um uh four so that means six and then move next so again we find B so index number should be four 4 - 2 and 2 + one three should be four 4 - 2 and 2 + one three should be four 4 - 2 and 2 + one three so that's why result should be nine and then finish so that's why in this case output is nine so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all ins left pointer v z and the result variable v z and then let's iterate one by one for so right pointer in range and the length of string and then if so left character equal right character so in that case we find the same character so just result plus equal right minus left + one and if plus equal right minus left + one and if plus equal right minus left + one and if not the case we find a different character in the case um so before we move iteration next iteration add plus one to result variable for current uh different character and then update left point with right pointer and that's it after that just return result and uh so description said so output should be huge so that's why divide um 10 to the power of 9 plus 7 yeah so let me submit it yeah looks good and the time complexity of this soltion should be I think a order of n where N is a length of input string so that's because we iterate all characters by one so that's why and the space complexity is I think one so we use just simple variables like a left result right so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Count Number of Homogenous Substrings
|
find-the-missing-ids
|
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "abbcccaa "
**Output:** 13
**Explanation:** The homogenous substrings are listed as below:
"a " appears 3 times.
"aa " appears 1 time.
"b " appears 2 times.
"bb " appears 1 time.
"c " appears 3 times.
"cc " appears 2 times.
"ccc " appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
**Example 2:**
**Input:** s = "xy "
**Output:** 2
**Explanation:** The homogenous substrings are "x " and "y ".
**Example 3:**
**Input:** s = "zzzzz "
**Output:** 15
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase letters.
| null |
Database
|
Medium
|
1357,1420,1467
|
105 |
the most important part about this problem is to understand how you can relate to different traverses and then combine them to create a unique tree and that is what makes this problem so very important for your interviews because it helps the interviewer to understand that you are understanding the tree traverses exactly how they are meant to be so you're given two traverses a in order traversal and a pre-order traversal and a pre-order traversal and a pre-order traversal and you have to somehow combine them to find a unique tree correct so let's see what we can do about it Hello friends welcome back to my Channel first I will experience a problem statement and we'll look at a sample test case going forward we will see how do you even begin start to attempt this problem and what do you do with these two travel techniques how do you combine them and find a unique tree Once you understand the concept we will also do a dry run of the code so that you can understand how all of this is actually working in action without further Ado let's get started first of all let's try to make sure that we are understanding the problem statement correctly in this problem you are given two integer arrays that are representing the in order and pre-order representing the in order and pre-order representing the in order and pre-order traversal of some particular binary tree right and then you have to construct the actual binary tree that is possible with these two given traverses now an important thing to notice over here is that there can be several different trees which have the same inaudible and there can be several different trees which have the same pre-order traversal but if you're given pre-order traversal but if you're given pre-order traversal but if you're given a in order travel at a pre-order a in order travel at a pre-order a in order travel at a pre-order traversal both of them then it will always point to a unique binary tree you can never have two different binary trees which have the same in order and the same pre-order traverses so keep the same pre-order traverses so keep the same pre-order traverses so keep that in mind and if you're new to pre-order and in order server so pre-order and in order server so pre-order and in order server so techniques I would highly recommend you to stop this video right over here and first check out those explanatory videos first you can find the link in the description below so for this particular problem you are given two tree traverses this is the in order traversal and this is the pre-order traversal and the resultant pre-order traversal and the resultant pre-order traversal and the resultant unique tree that will look something like this if you check out this tree what will be the in order to vessel the in order to referral will be left then the root and then all these right elements correct and if you see what I have in the input that is the left that is 9 the root that is 3 and all of these elements that are on the right Factory correct and even in this sub tree if you once again apply the inorder traversal you will get 15 20 and then 7 and that is what you see over here correct and similarly you can check the pre-order similarly you can check the pre-order similarly you can check the pre-order traversal also for the pre-order traversal also for the pre-order traversal also for the pre-order traversal is root then the left and then the right so you get root then the left and then all the elements in the right so you see how for this particular input case you can only construct one binary tree and this is your answer correct if you feel that you have now understood the problem statement even better feel free to stop the video over here and first try the problem once again on your own otherwise let us type into the solution to understand things better let us take up a bigger test case so I have this sample test case with me that has some elements right and these are the two given traverses now the most important part or you can say the most difficult part of this problem is to understand okay where do I even begin you cannot just start creating any random tree right you cannot just say that okay I will take one as my node and then start over there right that won't work there will be so many different combinations and that will not give you any optimal result at all so you have to start to think of an optimal solution and more than that you need to think okay where do I even begin for to begin things first of all we need to go back and realize what does the general structure of a binary tree looks like a general binary tree will have a root and then it will have a left subtree and it is gonna have a right subtree correct and what comes next you are given a pre-order traversal and you are given a pre-order traversal and you are given a pre-order traversal and an inaudible right so if you have this tree and I ask you okay what is the pre-order traversal the okay what is the pre-order traversal the okay what is the pre-order traversal the pre-order traversal will be simply the pre-order traversal will be simply the pre-order traversal will be simply the root that is just a single element then you will have your entire left subtree and then you will have your entire right Factory correct for now forget about all of the elements that are present over here you just need to Focus what will be the order of these three components right and next what do you have to find out how does a in order traversal look so for the same tree if you have to find out the inaudible what will happen first of all you will get your left subtree then you will get the only finger element that is root and then you are gonna get the right subtree correct so this tells me a very important thing and that is if you are doing a pre-order trial no matter however your pre-order trial no matter however your pre-order trial no matter however your tree looks like the first element will be the root correct because you can see that this is a generic structure and root is the very first element that you will encounter so this certainly tells you something it tells me that when I look at my pre-order traversal 8 is the look at my pre-order traversal 8 is the look at my pre-order traversal 8 is the root element in fact right so I can safely say that for my resultant tree it will be in fact the root element this gives you some sort of a starting point correct you check the pre-order correct you check the pre-order correct you check the pre-order traversal and the first element was the root right so you know that okay you have identified the root and now you are gonna identify all of the remaining elements now check once again in this sample tree Once you have identified the root what happens in an inaudit reversal in your in order traversal the root separates the left subtree and the right subtree correct so what you can do is in your in order traversal try to locate this root element where do you find it you find this root element somewhere over here right so this tells you a very important piece of information it simply means that all of the elements to the left of root they belong to the left subtree correct and all of the elements to the right of your root they are gonna belong to the right subtree right so in a way what you can say is I have identified the root and I have identified the left and right subtree elements as well right now you do not know how to arrange all of these elements but you know for sure that okay these will be the elements that are present in my left Factory and the right Factory I hope you're getting the idea now right so now try to think once again try to look at all of these elements in your pre-order traversal again you find these pre-order traversal again you find these pre-order traversal again you find these three elements in your pre-order three elements in your pre-order three elements in your pre-order traversal over here and you find these three elements in your pre-order three elements in your pre-order three elements in your pre-order traversal once again over here so do you see what is happening you have identified a recurring property now you found one more problem where you have a in order traversal that looks like seven to one and a pre-order like seven to one and a pre-order like seven to one and a pre-order traversal that looks like two seven one right and similarly for the right subtree you have in order traversal that says 396 and a pre-order traversal that says 396 and a pre-order traversal that says 396 and a pre-order traversal that says 9 3 and 6. so once again being a tree it has a recursive property so once again you have to identify the root correct so looking at the pre-order correct so looking at the pre-order correct so looking at the pre-order traversal you see that okay two is the root and this is where you find a two so in my left subtree I can write down a 2 over here and to the left I have a 7 and to the right I will have a 1. and similarly I identify the root as 9 over here and based on this I can populate my right subtree as well as you can see we were easily able to identify the unique binary tree that can be formed using these two given traversals you may also notice that being a binary tree at every step you can split the tree into two separate problems right as soon as you identify the root you have a left subtree waiting for you and a right subtree waiting for you and once again you can apply the same technique on this left subtree and on this right subtree once again identify the root and then split your tree into two parts so just based upon exactly this idea we can come up with a dry run of the code let us quickly check it out and you're going to remember this technique for the rest of your life on the left side of your screen you have the actual code to implement the solution and on the right I have these two arrays pre-order and in I have these two arrays pre-order and in I have these two arrays pre-order and in order that are passed in our input parameter to the function build tree oh and by the way this complete code and this test cases are also available on my GitHub profile you can find the link in the description below moving on with the dry run what is the first thing that we do first of all we create a map and this is the in order index map so you realize right for example when you found out that okay three is my root you need to quickly identify where does three exist in my in order array right this map will help you to identify it what you just do is you create an index map so in this map all my key values will be the elements of the array and all the values will be the index so as soon as you find out that okay 3 is my root value you can quickly look up in this array and identify that okay three lies at index 1. as soon as you find this out you are able to split your problem into two halves so that is why this map becomes essential you do not have to iterate through your in order array again and again so this is saving you time at every iteration correct once this map has been initialized I now have a helper function that will split the tree into two halves at every instance so let us check out how the split tree function actually works you pass in several parameters first of all you pass in whatever your pre-ordered you pass in whatever your pre-ordered you pass in whatever your pre-ordered reversal is and next I pass in this index map because I have to quickly look up where does my root lie so that I can split the left subtree and the right subtree next I pass in the root index which is 0 at the moment because root is the very first element of your pre-order the very first element of your pre-order the very first element of your pre-order traversal correct and then I pass in a left bound and a right bound So currently you have the entire array for left is at 0 and right is at the very most end of your array correct once you are in the split tree function what happens you have to create a new tree node right this is where the construction of your tree starts and what do you populate it with a root Index right the root index is 0 so you populate it with three so I start creating a tree now that looks like this both of its children are null right now correct moving on you have to now create the left subtree and the right subtree if you remember our technique what did we do with the root if we looked up a root in the in order traversal to identify that okay this is my left for tree and this is the right subtree so I look at this root value in my index map and I will get the value I get this value as 1 so this is how I know that I have to separate it over here and then once again I will split it when I split it I do root dot left and I pass in my pre-order array again the in order map pre-order array again the in order map pre-order array again the in order map once again the root index now changes and I will look at the next value and then I pass in the left bound and the right bound and similarly for the right subtree I will pass in both the pre-order array will pass in both the pre-order array will pass in both the pre-order array and in order index map but this time I will change my left boundary and the right boundary so the left boundary starts at 15 and the right boundary ends at 7. so you can see that what will happen in the next iteration this will once again behave as a fresh problem and you're gonna populate your left subtree and the right subtree in a similar technique that the wavy Jeff discussed once all of this is done this Loop ends and you simply return root as your answer this is how you are able to uniquely determine what is the binary tree the time complexity of this solution is order of n where n is the length of your pre-order array and the space complexity pre-order array and the space complexity pre-order array and the space complexity of this solution is also order of n because you need an extra space to create your map with your indexes right I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that in this particular problem you were given a pre-order traversal and in order given a pre-order traversal and in order given a pre-order traversal and in order traversal you use both of them to uniquely create a binary tree correct what happens if you are given a post order traversal and in order travel cell can you still create the binary tree and what happens if you get a pre-order what happens if you get a pre-order what happens if you get a pre-order traversal and a post order traversal are you able to create a binary tree then so just try to get a piece of paper and plot out all of these different traversals and try to come with a binary tree using the same concept that the Jeff discussed because you can be damn sure that as a follow-up question you sure that as a follow-up question you sure that as a follow-up question you will be asked this in an interview so just get out your pen and paper and let me know what you think let us discuss all of it in the comment section below and I would love to discuss all of it with you also let me know if you faced any problems while going throughout the video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
94 |
and take a look at a legal problem called binary tree inward traversal so for binary treatment or traversal the order goes something like this where we're traversing the left side first and then the current node then the right side okay so let's say we have an example like this where we have the current node the left side is null the right side have subtree so first we're going to traverse the left side so that left side is null so then we're going to get the current node value which is one so we that's why we have a one here and then we traverse the right subtree so same thing for the right subtree we traverse the left side first and then the current node and then the right subtree so the left substrate only has no three so we add no three onto the list and then in this case we're going to add the current node which is node two and at add two uh value two onto the list and then we'll traverse the right side so right side is null then our job is done right so we traverse the entire tree using in order traversal so let's say we have another example like this same thing here we are traversing the left side first then the current node and then the right side so in this case we have two one and if the left side is null then we're going to traverse the current node and then the right side or the right subtree and for the right subtree we follow the same procedure so left side first then the current node and the right side so to do this using recursive approach right in this video i'm going to show you how to do this using recursive approach as well as the iterative approach so to do this using a recursive approach basically the idea is that we're going to have a result list which basically keep track of all the notes that we have right we add all the notes that we traversed and onto the result list that we're going to return at the end and we're going to have this dfs method which takes the root node and then what we're going to do is we're going to traverse the left side first right so we'll traverse the left side and then we take and we basically once we're done traversing the left subtree then we're going to take the current node value add it onto the result and then we're going to traverse the right subtree and our base case is that if the current root node is null we can just return because in this case the current rule is null then we can we don't have to continue to do the deferred search anymore this path is null right so if we were to run this code or submit you can see we have our success so to solve this using a iterative approach basically we're going to use a stack data structure so because what we can do is we can use a stack data structure to keep track of the last element that we inserted onto the stack so then what we're going to do is we're going to use this data structure like this as well as we're going to use a root a variable that keeps track of the current root node and then we can be able to traverse its sub tree first once we're traversing its subtree we're going to be able to use um take the top element that we get that we inserted off the stack and then we're going to get its parent node of that subtree which is traversed which is going to be the top element that we have on our stack and then we're traversing its subtree once we're done traversing its sub tree we're going to take the top another top element off the stack then we're going to traversing its subtree so what we're going to do is initially is we're going to have node 4 right this is the root and we're also going to have a result list that we're going to return at the end and basically this is going to be the root so what we're going to do is we're actually going to start here so in this case we're just adding all the elements on the left side all the left subtree in this case um or left subtree root node i'll add it on to the stack so we add node 4 so no 4 is the root so in this case we have a left child for no 4 so in this case root is equal to root the left so we have 2 here so we add 4 onto the stack and we add 2 onto the stack as well then what we're going to do is we have root is equal to root left so in this case we have 1 so we add 1 onto the stack so root is equal to root.left which in so root is equal to root.left which in so root is equal to root.left which in this case is null so in this case what we're going to do is we're going to take the top element that we have on our stack which is going to be one so we take that off so now we have a so now we have the root is going to be node one and then we're going to do is we know the left side is null so then what we're going to do is we're going to add the current element and then we're going to traverse the right side right subtree so then we're going to do is we have a result we add one onto it and then we what we're going to do is we're going to get the root is equal to null because the right subtree is null right for right subtree for this node right here is null so in this case if it's null then we're going to take the top element that we have on our stack off of it and assign it onto the root so now we have node two right so in this case we have node two right here so we have node two and then we are going to add the current node because we are already traversing we're already done traversing the left subtree so we are going to get the current node which is going to be node two so we add no two on where node two's value onto the result list and then what we're gonna do is we're gonna traverse the right side so we're going to get the we're going to assign the root is equal to node 3 right so in this case we're going to first add node 3 onto the stack and then we're going to say root is equal to root of left so in this case rudolph left is null so we're going to take the top element that we have on our stack off of it and then assign it on to the root so that's going to be no 3 right so in this case what we're going to do is we're going to add though 3 onto the result list and then the we're going to get root is equal to root.right equal to root.right equal to root.right so in this case it's going to be null and rudolph right is null so we're going to take the top element sorry we'll already take this element off already but basically what we're going to do is we're going to take the top element that we have on our stack off of it so now we have four right so four is going to be our root so basically we already traversed this one and this one already where basically i should say the entire left tree is traversed now we're going to get the current node right the root node in this case node 4 we add node 4 onto this the result list right onto the result list and in this case root is equal to root dot right so in this case it's gonna be the five we add no five onto the stack so what we're gonna do then is we're basically just going to um keep traversing the left so in this case the left is null so root is equal to the left where the left is null we take the top element off the stack so that means we have five right so in this case we take this off we assign it to root because we're done traversing the left side is null and then the root in this case is no five so no five uh we're going to add it on to the result list and then what we're going to do is we're going to get the root is equal to ru dot right so and then in this case it's going to be node 6 and then we're going to add node 6 onto the stack because in this case the root is not null then we're going to continue to see if it has a left child in this case root is equal to the left it says null and in this case we have null we're going to take the top album of the stack so we have no 6. and no 6 we're going to add it on to the result list and then we're traversing the right side so right side in this case root is equal to that right so it's null and then basically we already pulling this element off because the left side is null already so we're done that and then what we're going to do is because this is null then we're going to take the top element of the stack but the stack is already empty then our job is done so we have our result list right so pretty much this is how we solve this problem using uh iterative approach using a stack data structure we're going to do is we're going to have a list of integer which is equal to result new link list okay and the idea is pretty simple we're basically just going to have a stack data structure that stores the tree node and we're going to have a tree node called current root which basically points to the current root that we're going to first traverse right so in this case current root is root and what we're going to do is we're going to say while this is true we're going to basically adding first we're going to add the left subtree right we're going to add the first the very left node onto the stack and then we're going to do is we're going to uh once we're traversing the left side first then we're going to traverse the current node and then the right subtree right so in this case we're going to say while right so while the current root does not this curve root does not equal null we're going to get the current root add it on to the stack so curve so stack dot add current root and then what we're going to do is we're going to get current root is equal to current root dot left right so we continue to add a left node and then once we add a very left node and at the end we get the current root is null then we're going to get current root is equal to the top element that we have on our stack dot pop so once we've done that we're basically going to add the current node onto the result list and then we're going to traverse the right side by getting the current root is equal to current without right so we repeat the process but because we set the while loop to true we need to have a base case in this case the base case is that if we have the stack that is empty is equal to true right we adding no elements onto the stack true then we can just break the loop because at the end we want to return the result okay so once we take the top element off the stack we're going to add the current element onto the result so it's all the add current root value and then we're going to get the current root is equal to current root dot right so we're traversing the right subtree and then we're going to continue to do that until we get all the elements that we have in our binary tree onto the result list so if we were to run the code and let's try to submit and you can see we have our success so this is basically how we solve the this legal problem using recursive and iterative approach
|
Binary Tree Inorder Traversal
|
binary-tree-inorder-traversal
|
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
98,144,145,173,230,272,285,758,799
|
7 |
foreign with the lonely Dash and today we're going over lead code question 7 reverse integer which says given a signed 32-bit integer which says given a signed 32-bit integer which says given a signed 32-bit integer X return x with its digits reversed if reversing X causes the value to go outside the signed 32-bit integer to go outside the signed 32-bit integer to go outside the signed 32-bit integer range which is negative 2 to the 31st power all the way up to 2 to the 31st power minus 1 then return 0. assume the environment does not allow you to store 64-bit integers signed or unsigned so 64-bit integers signed or unsigned so 64-bit integers signed or unsigned so this looks pretty darn complicated but we're going to break it down so right off the bat let's just go over what we mean by a reversed integer right so we're going to be returning the integer x with its digits reversed so let's come down here to the concept we're going to get into the whole 32-bit thing in a get into the whole 32-bit thing in a get into the whole 32-bit thing in a little bit but for right now let's go over this concept so we're given an integer whether it's positive or negative it doesn't really matter we're going to use this negative 4567 integer as our example and we got to make sure our answer starts at zero okay and on the right side I have kind of written down my own little steps of how I am going to reverse this integer and be able to return the reverse so obviously looking at it if we know that the integer is negative four five six seven the answer will end up being negative 7 6 5 4. so we've got to figure out how that's the case and I mean if it was a positive then it would just be without the negative sign and that's all we're doing here okay so we're just reversing those digits so on the left you'll see our steps so the first step we have if we're given this integer is to find its absolute value so for us an absolute value is just saying if it's negative we're going to make it positive if it's positive we don't have to do anything to it so the absolute value of negative 4 5 6 7 is just four five six seven so we have found in our case the absolute value of our integer next we need to identify its last digit so this last digit here is seven and the best way for us to do that is to give it a modulo 10 which is asking hey what's 4567 divided by 10 and the module gives us the remainder so that divided by 10 is 4560 and the remainder is of course 7. so that modulo 10 is equal to 7. then we need to add the last digit which is 7 to our answer so if we're not starting with anything bam answer now equals seven then we need to remove that last digit from the integer with which we are working and we're going to do that by subtracting our current last digit and then dividing it by 10. so we've identified that the last digit is 7 so we're going to go minus seven and then we're going to divide by 10. so four five six seven minus seven is four thousand five hundred and sixty and then that divided by 10 is just equal to 456. so that's our new integer that we are working with okay now we do it all over again so the we know this is already an absolute value we only need to do that once we find our final digit by modulo 10. so the final digit here in this case is six and now we need to add 6 to our answer key now if we just did 6 plus 7 we're not going to get the correct answer right 7 8 9 10 11 12 13 that would end up being 13. but we want to add the digit so what we're really going to do up here is multiply our answer by 10 and then add our digit right so if that's the case 7 times 10 is of course 70 and now we're adding our last digit which is 6 which makes it 76. and in this case down here we've found that our last digit is 6 so we are subtracting 6 and then dividing by 10 which gives us 45 and that is our new integer we're working with okay so we're going to go all over again find the last digit is just going to be modulo 10 which equals 5. awesome we need to add 5 up to our answer so how do we do that we multiply it by 10 so that's going to make it 760 and then we're going to add our last digit plus 5 makes it 765. okay now we just need to remove the last digit here which of course we are doing by subtracting 5 and dividing by 10 which means our answer will end up being 4 and we do all over again so obviously our last digit here we don't really need to do the modulo thing but we can it'll end up being 4 and so we are going to go up here multiply by 10 so times 10 that will give us 7650 we're going to add four to it and that gives us our number and we're going to remove this and now it equals zero so we're going to stop uh because there's no other number to deal with so we'll talk about how that's going to end up being a while loop so this will be while our integer that we're dealing with is not zero or if it's greater than zero we're going to continue through all of our steps as soon as it reaches zero we're going to break out of our while loop and we're going to return what our answer is now the question is now did we come up with the correct answer well no we successfully reversed our integer and if our initial integer had been a positive number we could just return this no problem that would be great but we're going to have to do a comparison so we're gonna have to ask ourselves hey was our initial integer positive or negative if it was positive we'll return the answer if it's negative then we're going to return our negative answer and that is how we're going to solve this problem by following the these Steps step by step and then whenever we have to add a digit to our answer integer we have to remember to multiply it by 10 in order to create an extra spot to add the digit we're adding Okay so Ah that's the process but we have to consider that if we're reversing X and it causes the value to go outside the 32-bit the value to go outside the 32-bit the value to go outside the 32-bit integer range which is this range here we're going to have to return zero so this section is really going to depend on what language you're coding with so with python it's super simple with Java it's a slightly more complicated concept so let's go over that now so in JavaScript there's only really one more step to add to our steps here in order to make the 32-bit integer order to make the 32-bit integer order to make the 32-bit integer um thing work and that is every single time we run through this process we need to evaluate whether the number that we're dealing with deviates outside of this range Okay so we've started with our answer we've gotten to seven and six and five so 765 as we go through instead of returning the answer we're just going to add an extra one in here and which just says actually we're going to really replace do it all again we're going to ask ourselves if answer is and again here we go we're in absolute value which means we're only dealing with positive numbers so in that case we're really only trying to figure out if answer ever deviates between 0 and this number which is 2 to the 31st power to minus 1. so we're going to ask ourselves hey is this number so if this number or this answer is out or is not in range of 0 through 2 to the 31st power really minus one so if it's not within those two things we're going to return one or to return 0 as the question asks us to so that's just one extra step we're going to add in uh in this code in our while loop every single time we go through we're going to say hey is this number too big if it's ever too big we return 0 if we get all the way through the loop then we can continue on without any worry so that's just the extra step we need for JavaScript we'll talk about that a little bit more clearly when we start writing the code but for now let's see if there's any edge cases to consider the symbol answer is no there are not really any edge cases to consider all the constraints basically say that they're going to be provided numbers which are going to be integers that are going to be already within the range we are required so the only Edge case we really had to consider was given in the question which was what if we're given a number well I guess we could be given a no we can't even be given a number that's outside of that range so it'll already be in that range there's nothing else to consider let's move on to some pseudo code so for our pseudo code I'm just typing into the python work area of the lead code website and so the first thing we really need to do and what we talked about was our part of our steps was to find the absolute value so we need to find the absolute value of the integer we are going to be reversing right then we need to create a variable whether that be answer I think we're just going to call it variable we could call it answer right we could call it answer and initialize it to zero because we need to start with absolutely nothing uh then we need to start iterate we need to go through each um each integer or each digit so we need a while loop so we're going to create a while loop that will continue through each digit until um our integer is zero is equal to zero right because we're just going to be eliminating the last digit each time until it's gone once we have done that we need to identify or well at least within this Loop we need to identify the final digit or the last digit I'll call it last digit once we've identified the last digit we need to remove um the last digit from the integer that we're dealing with right we need to update um the answer variable by multiplying by 10 and adding the last digit right we talked about that and then this is sort of the The Edge case that we need to consider if um the answer right that we're dealing with is outside of bounds so if it's greater than 2 to the 31st power minus 1 which means it goes outside of the 32-bit area we're goes outside of the 32-bit area we're goes outside of the 32-bit area we're just going to immediately return zero right otherwise we're going to continue right we're going to go back and start all the steps all over again once the while loop completes once the while loop is complete right here we know we've had a reversed integer it should be all ready to go but we need to remember that one of them could have been negative so once the while loop is complete um if like the original or original integer was negative then return the answer as a negative right if the original integer was positive just return the answer the way it is and that's it that's kind of all of the pseudo code of what we're going to be doing so let's take this pseudo code and start coding foreign so as you can see I've just copy and pasted our pseudo code into the JavaScript work area of the lead code website and we're going to follow line by line and basically figure out this code together so the first thing we need to do is find the absolute value of the integer that was given to us and so for us right now that means I'm going to create a variable we're just going to name it y for argument's sake and we're going to use the math.abs going to use the math.abs going to use the math.abs I read omath.abs got to think about I read omath.abs got to think about I read omath.abs got to think about while I type not a-n-s-a-b-s there we go while I type not a-n-s-a-b-s there we go while I type not a-n-s-a-b-s there we go absolute value of x and all this does is it takes if a negative number and turns it into a positive number or if it's already a positive number it keeps it as a positive number so great thing to know when you're using JavaScript then we need to create a variable and initialize that variable to zero and all that's going to do is store our answer so we're going to let it a variable and we're going to name it answer and we're going to initialize it to zero right off the bat because well we got to start somewhere so that's the first two lines of our pseudocode and we're going to erase those now we're going to create a while loop that will continue through each digit of our integer and that is now y until it's zero because remember we're going to be removing the last digit of this integer and as soon as we remove the last digit it equals zero so that's going to be while and as the case is While y is greater than zero what are we going to do well first we need to identify whatever the last digit is so we're going to let LD for last digit that is going to equal Y modulo 10. and remember this is a this modulo gives us the remainder of a division sequence so if our integer was 789 and I'm sorry if it's a little hard to see being too small but if our integer was 789 and we divided that by 10 of course we would end up with 78.9 end up with 78.9 end up with 78.9 nine and so what this modulo does is it just gives us that 0.9 so it's telling just gives us that 0.9 so it's telling just gives us that 0.9 so it's telling us that the last digit of 789 is 9. that's all we're doing there so once we've done that we need to remove the last digit from the integer we're dealing with okay and so essentially we're doing exactly the same thing we're going to create a variable oh no we've already created the variable so Y which is the integer we're dealing with and we're going to change it to equal y divided by 10 right so again if we had 789 divided by 10 it becomes 78.9 we had 789 divided by 10 it becomes 78.9 we had 789 divided by 10 it becomes 78.9 but we still have this 0.9 left over and but we still have this 0.9 left over and but we still have this 0.9 left over and we don't want it there so instead we're just going to turn this y divided by 10 into an integer and we can do that by parse hinting it in JavaScript and so all that's going to do is say oh I'm going to ignore that 0.9 and we're just going to return 78. 0.9 and we're just going to return 78. 0.9 and we're just going to return 78. so if that's what this parse int does it just converts whatever is within into an integer so y equals part int y divided by 10. so we're done there next we need to update the answer variable by multiplying by 10 and adding that last digit and that's the way that we're going to basically just add a digit into answer so answer is always going to either what it or sorry equal whatever the answer was times 10 which opens up an extra digit spot and then we're going to add our last digit to that spot so that's exactly what that line does and just for readability I'm just going to remove those three lines next and this is the important part this is where we make the determination if what we're currently holding in our answer variable is within the bounds of those 32 bits if right if our answer is greater than um and what we're really looking for is if it ends up being greater than 2 to the 31st power right so 31st power and in order to write that in JavaScript we're going to use math again just like we did math for absolute value power we want to know if it's greater than 2 to the 31st power right and not only that both to the 31st power minus 1 if our answer is greater than that meaning it's outside of its bounds we're going to return 0 as the question requests right otherwise we're going to continue so we don't need an else statement or anything we can just move on from that position right so we are done with our while loop so I'm going to go up here find the end of our while loop and move on next we're going to have to figure out if the original integer was positive or negative right because our while Loop's done so we have something in our answer variable so we need to figure out if it needs to be positive or negative again and that's all we're doing so if the original integer was negative so if x was greater than zero what are we going to be or if sorry X was less than zero what are we going to be returning well we are going to be returning negative answer whatever the answer was but negative otherwise else that means X was greater than zero so it was positive or equal to zero I guess to be fair then we're just going to return the answer and that should be all of the code we need to solve this problem and so I'm just going to scoot up so we can see it all in one go I'm going to make sure I didn't make any mistakes and hit run and we'll see how it worked and it does work runtime was 88 milliseconds I'm going to hit submit to do a comparison uh between everyone else and all of the test cases and as you can see it beats 88.61 percent in run time see it beats 88.61 percent in run time see it beats 88.61 percent in run time and it beats 96.32 percent in memory so and it beats 96.32 percent in memory so and it beats 96.32 percent in memory so this is a simple straightforward way of solving reverse integer using JavaScript foreign
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
1,011 |
hey what's up guys John here again so this time I want to talk about another problem 1011 capacity to ship packages within D days okay let's take a look at this problem the comfort of description of the problem so you have a comic-con ver the problem so you have a comic-con ver the problem so you have a comic-con ver but has packages that must be shipped from one port to another B's in D days right so at the ice pack a tight package on the conveyor has a weight of which I and each day we will load the shape from packages on a conveyor belt right we may not load more weight than the maximum weight capacity of the ship and you need to return the least way the capacity of the ship that will result in that will make basically that can deliver and ship all the other packages on the conveyor which indeed A's alright so this is a very similar problem as the some other like binary search problem in the it's called the other one is the things number 800 and this 807 74 I think something like cold cocoa eats banana so there's a like up there that I cook monkey called cocoa and he/she cook monkey called cocoa and he/she cook monkey called cocoa and he/she likes to eat bananas and you need to find the minimum speed she can eat our bananas wheezing within reasons certain eight hours right so very similar to this problem right and so let's take a look so foot okay so same thing for binary search we need to find all the other minimum the minimum lower bound upper bound right so what's the lower bound for this problem right so what's the lower bound basically what's the lowest or capacity of a ship right so as you can see here we may not load more weights than the maximum weight capacity on the ship right so our lower bound has to be the max of the weight right because if this law if the capacity is smaller than the higher than the maximum weight of this of these packages so that let's say for example we are we try to tie seven let's say the capacity of seven right then eight nine and ten they will never be able to be shipped right so that's why the lower bound of the capacity has to be the maximum of the weights so that we can make sure at least we can ship all the other weights so how about the upper bound all right so what's upper bound in this case the upper bound is it's the sum right some sum of the weights right because upper bound is that the capacity can ship all the packages within one day all right basically that's our upper bound all right because you even though you can ship even though you can use it at huge numbers but doesn't it's a kind of waste right we don't need that many that much capacity all we need is there all we need is the ice hires there's the total weights of the packages right okay with that we still two lower bound upper bound and we can try to solve this problem we can write the working rights the binary search code cool let's start writing I still recording here so saving left it's going to be max up the weight right and the right is the sum of weights right like what we just discussed and then why our left also right then middle equals to left class we do a middle point from the left and right and then I simply do if you can shape right basically if we can ship all the packages within I mean not with it now within D days with this current capacity right then we know okay we might be able to find the answer but still we can see we're trying to find the minimum of it right that's why we will be moving because this middle then we know okay no I think we can just try to like decrease the capacity a little bit because it's a car in the middle we can shape all the packages within D days but we want to see if it's the minimum value or not right then which is the discard the right half and then we just do a middle here right left plus you know class one right so again the reason we do a middle here not middle minus 1 H because with current Meadows weak and weak it can satisfy the condition which means the middle might be our final result right which we don't know that's why we can now simply these discard this middle here we have to keep it right but if it if we cannot shape and then we know this middle is definitely not our answer so we can just safely discard this middle by just simply safely moving this left cursor forward right and now it comes down hug how can we implement this shape right the kinship and Harbor functions basically it's kind of shaped powerful functions it's simply what's this it's gonna be the test the capacity right capacity see ya so here we're trying to check is that with this current capacity can we ship all the packages using D days right and remember we can only ship the this like these packages from left to right in the in a sequence right so which define the taste needed right you constitute let's define two one first because at least we'll be needing one here right because at least we'll since word with this capacity the minimum value will be 1 so that's our starting point and yeah i'll show you how do we use that starting point to do the following calculation here and then i'm gonna have like current weights right current weight is equal to 0 and then for weight right in weights basically every time we which is accumulate this weight right until we until what until we see okay if the current weight is greater than then the capacity here path capacity then we increase this then we increased a needed by one right and then we'll also be selling this weight to the top a table here right so see that's how we do it so because at the beginning every time right we only increase the states needed only when this current weight is has exceeded capacity right that's why we are so for the first few ships for the few packages we only added one until and when we see the next one that will be cannot be effaced into the current ship right that's why this one will be needed it will be set to 1 because in the end we know ok so that whatever left in the current you know current weights will be shaped in the last ship yeah if you guys think this thing is kind of confusing you can also do that you can also start with 0 right 0 and here and but in the end here right in the end let's say you start with zeros and then we always add 1 whenever we see ok so basically this day's needed it will be that the ships today's we need to shave the previously the previous packages right but in the end when we reach the end after of this array here right so there's gonna always be alike a packages laughs in the current weights right that's why we've been we'll just do a days needed plus one for the last shape right so we can either do this or we can just to add the one at the beginning so we can just to save you don't have to add this thing at the end right and in the end we simply just return sorry check today's needed if this one is not greater than the D right so that's this helper functions basically we check with the corner of capacities curvy ship to me ship all the packages within D days right if it can then we simply just try to look for me as basically are more optimal answer otherwise we know the corn one is not the answer which need to increase the occupied capacity right and in the end which is returned the right here either left or right but I prefer right because we're using the right to store the answer here right so this right corner is to me is more like a pointer foot for the real for the last answer not the left one okay so let's run it hmm yeah I don't know what's going on with lead cold seems like this cold is it cold dot-com is not responding come on okay I'll pause the video for a while and until wait for that to the website to come back hey guys so seems like late called website it's not going to come back anytime soon so yeah so I think I'll just stop here yeah okay cool I think I pretty much cover everything I want to talk about this problem so yeah I think so much for watching the videos and I'll be see you guys seeing you guys soon bye
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
189 |
I am your everybody, how are you all? In today's video we are solving the problem of rotation, so there is 189 problem, what is the problem on your list court, I will tell you as you must have read, only then you can see the solution. Coming in the other way, let's go straight to the discussion, okay, first of all you should know that its code is very simple, let me tell you, once you have understood the logic, you will not give the crown for a while, now let us see that if It has been said, okay, I am saying this, hey, I have given you 123 and the value of 5, 6 and 7, now he gives us Hey, rotate it and give it, you have to rotate it, write the meaning, understand this time. How does rotation happen? What does it mean? Let's not do this. Let's assume that we have given the link the value of one. We will have to rotate it one time. Okay, so what will the notification of one mean that all the values will be one mean that all the values will be one mean that all the values will be shifted by one place. So this is the value, it will come to the worst position. Okay, how about finding a solution for our seven 123 456 numbers. There are many possible solutions. We have to find a solution whose time complexity is equal to no. For these, let's talk about time space complexity. If it is a matter of space complexity, then soak off one, it is okay that it will happen in these places, first of all, okay, the account is cleared, one thing, would I have got angry, sorry, one of our problems, it will happen, we will be one straight for. Let's put a loop and one will shift the value, okay now it says equal to three times, okay, so what will we do, we will put another loop on the outside, the year will move the people inside us, okay, what is this potato doing? It will be the Swift one, okay, and this one will be the one of the people, this one will play the playlist, the one inside will keep shifting and let's run the time of these three times, so shift it three times, okay, that one three times. It will be accepted, the same thing falls on the spot, okay, this type will solve our problem, this is our case finished without fear and square, okay, if mine has to be solved in a soaking oven, then let me tell you a simple thing, we have. Is 123 456 ok if I say you have equal to two three ok one is 123 then what you have to do is rotate the tiles ok no put your foot and nickel tell this quickly you will have 560 and ok And this is given to you in the problem, you can see it is okay in example 1 which is f5 67 1234 okay see how to get angry but it is very easy friend what will we do for something more difficult that is given to us okay we first of all Let's reverse this whole thing. If you agree, then what should I do with the whole thing? Reverse it. Ok, I will do the whole thing. F1, Ok. F1, I am going to reverse this whole thing. 4654 Three, then you are ok, I will do it. Tattoo Maker. I said that. I will make him first second and third 13021 last practical - 1 ok now what should I do reverse them - 1 ok now what should I do reverse them - 1 ok now what should I do reverse them ok mine will become abe mine will become pipe and check seven for your she is going to make it 432 21 hai Meghnad hai what will happen in MP3 The step is complete in reverse. In the chapter, the next K in the chapter was tabled from zero to K minus one and in this it is complete. Now we have to do the straight in the last. Our organizer from K to the last Audi is ok till the last. Till what has happened to us, reverse it, how is it okay, so this time which one of ours is going to go on this train, this one and 321 will be lying on the Taliban, our end is at minus one, the size is at minus one, what about this will become mine. 500, 600, 800th Urs, keep in mind and match both of them, they were entitled to 40 flavors, from chapter 250 onwards - it is okay till now, we have done this year in this manner - it is okay till now, we have done this year in this manner - it is okay till now, we have done this year in this manner and then what will we do after this, hey, how will we We will constrain the value till the end, that's all the work, now let's code it quickly, it is very easy. Okay, now in this video, let me tell you the record of the reverse. Just tell me, then you put the coil, put two points, start and It's okay, stars and will be have been replaced through points, if you want the answer in full detail, then the video is already on the channel, in the play list of the address, so go and check it, okay, now let's talk about what I have done here simply. He said, first of all reverse says it is saffron, I will give you code in a week, okay, Maruti has already stepped in, first specific waves, last in the whole year, minimum - must be lying on your mind, but length minus one, minimum - must be lying on your mind, but length minus one, minimum - must be lying on your mind, but length minus one, okay, now let's warm it up. Then I tell you further things are perfect, our is accepted, the code is running great, okay, now I tell you, second is the size of tomato, here the values are 12345, we have size, okay, now let me values are 12345, we have size, okay, now let me values are 12345, we have size, okay, now let me tell you here, if I add Let me do it, okay, stay graded from the side, let me see Ajay, MP4 index, out of country, accept, why, because we had seen, minus one, okay, now it will not go, because it is more green and the size is seven, okay, you can add a line. That line will be foaming in this cold reminder of this, our name is fennel length, which is our length, its length is just now, what's happening in this, what's happening that western aspect, what we are doing, we are inside this Ka Rahman ke chalo ke's value is free with me and assume their value size of this we have advocate reminding by reminding me how much will be the lie then reminding 227 what is this show reminder is ok then die reminder's 13 now values if big Want a reminder values if big Want a reminder values if big Want a reminder 227 Now shall we today Reminder One Look at this, let's assume that it will do only one thing, Strict Reminder 227 Okay, if you look carefully, if the size becomes equal, then it is okay and if you try to rotate it, then it will shift seven times. It will be fine, that is, every value will be there at 707 times, it will come to the same position, okay, so this is a reminder that these will be rotated, no rotation, okay, so this was it, I have a small problem now, let us support it immediately. And let's see if our question is correct, now you can submit it directly, I know from here you can see that the runtime can get zero and faster than hundred percent, okay then you have solved the problem in a great way, memory is overused. It is not happening, I told you that it is go for a certain time and it is okay, this video of space is also available, I will get you this video immediately with the next video, you take a screenshot of it and yes, more videos are needed, keep adding more questions in it. If you keep getting it done, you will get it in a list of the court and if you get the strings length and topic wise then go and start that also on the channel, okay everything is free of cost, go bye, best of luck.
|
Rotate Array
|
rotate-array
|
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3,4,5,6\]
rotate 2 steps to the right: \[6,7,1,2,3,4,5\]
rotate 3 steps to the right: \[5,6,7,1,2,3,4\]
**Example 2:**
**Input:** nums = \[-1,-100,3,99\], k = 2
**Output:** \[3,99,-1,-100\]
**Explanation:**
rotate 1 steps to the right: \[99,-1,-100,3\]
rotate 2 steps to the right: \[3,99,-1,-100\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `0 <= k <= 105`
**Follow up:**
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
* Could you do it in-place with `O(1)` extra space?
|
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
|
Array,Math,Two Pointers
|
Medium
|
61,186
|
1,963 |
So Hi Everyone, my name is Shashwat Tiwari and in today's video we are going to do another bracket balance question. It is a very interesting problem but at a medium level, you will have to think a little intuitively, so let's start today's video. If you are on this channel. If you are new then go and watch the old video, very important video is playing now because all these questions can be asked to you anytime in online assessment air interviews, so without wasting any time let's start the lecture. Okay so the name of the question is Minimum Number of You make D string balance by D way, there is another variant of this which you will find on the song, so we will be solving that in the next video and both of them are different patterns, if you are watching later then check it out in this playlist. Maybe the video is already ok so the question is you are life is zero index string s of and length n ok so till now we were checking brother order so return it blindly said it is other length tha string consist Off exactly n/2 opening bracket and by tu exactly n/2 opening bracket and by tu exactly n/2 opening bracket and by tu closing date hai ok thing balance you swap this sari definition we watch the last video what is the balance string bracket come other tu index other number of times ok you swipe any number of things You can use any bracket, it's okay, return D minimum number of saps, you make the swing balance, but what you have to do is to make the balance of the end of D screen, okay, so here they have taken an example, so in this you must be seeing if If you swap the first and the last one then your bracket will look something like this which is the balance is fine, here also we have taken a similar situation i.e. there is a lot of love question, it is i.e. there is a lot of love question, it is i.e. there is a lot of love question, it is fine as we strike, understand that we have to minimize so that Key and out video, my string gets balanced, what does it mean, what will be those who will not continue again, in the last few videos, we are talking about the same thing, brother, remove the valid page, so here too, first of all, let's remove the valid page. Because after completing these, they are valid among themselves, this is valid among themselves, okay, the rest of these are valid, for me, it will be done by removing these, it is okay, both A will go, okay, two more closing lines are gone and give three opening lines, okay you. I finally have this one swing girl no what is it de minimum way you swap letters understand let's swap these two okay so it's Bill Wickham something like this okay you can get the answer in less than three think okay think if I Tell me by commenting. Okay, so if you have solved then you must have seen a pattern here. If I had first swapped these two, okay, what happened to these two, one partner became valid, okay, that means you swapped. Did the saree get changed, why did this happen because friend, we swiped these two instead of these two, then obviously the opposite happens, this one also got balanced, right, what child do I have only one option, I swiped these two. Let me give you so this bill, something like this, actually, now I will swipe the balance, then these two will get stuck together, okay, something like this and this, what is the correct pattern, what is the pattern, something like this, one, three, four, okay. 1234 Now look, I will reduce it very simple here, I swipe this, I left the daily gap, now I swipe this, okay, balance this, swipe this, no, okay, so why am I doing this here? Why am I taking a gap of one each because what is one here, this is an opening and this is a closing. Okay, so when these are swiped together, there will be a closing here, there will be an opening here, this opening is this closing. Because these are which are closed, okay, these are all closed, these are all open, so these two together will make a leg, similarly, these and these together will make a leg, these and these will make a gate leg, so I have swapped three times. Did but how many are completed Three here are done I balanced a total of six brackets Right this is this D pattern which they are looking forward but when I have the order then how in the odd what happens in the odd here in this here There are three, one, two, three, here, there are one, two, three. Okay, so here too, we do something similar, we swipe these two and get rid of all four, but because I don't have any kids on the next one. The next leg is not just a child, it means I have the last option to balance it too. Okay, so what can I say because I have to return the count in the answer, not show it by making a string, so what can I say if the length is three. The length three whose three is what number of close this number of open bracket is ok deez are not the number of total non balance bracket deez are the number of close or open bracket if it is odd length what do I have to do three divide by tu Plus one is fine so this bill is something like 1.5 which is fine so this bill is something like 1.5 which is fine so this bill is something like 1.5 which is bill be one and one plus one is length hota to mujhe khali tu chahiye tha can I generalized tu cases I have explained to you in the video cocoa eating banana swelling how to divide three plus one by Ok or four plus one divide by tu then what will be the answer of this 3 + 1h4 4/2 this tu four what will be the answer of this 3 + 1h4 4/2 this tu four what will be the answer of this 3 + 1h4 4/2 this tu four plus one this 5 / 2 this is 2.5 ignore this plus one this 5 / 2 this is 2.5 ignore this plus one this 5 / 2 this is 2.5 ignore this then understand why this is plus one read to balance automatically. Because they do not have the gapping of you. Okay, the unbalanced bracket will always come in this order. Okay, there can be another order and there can be another order. If you put the closing here, it will be balanced. We have already removed the balance, you will put it here. This balance will be balanced, we are already here, we have started closing here, still the same pattern is being formed, okay, you have the number and we have already discussed it in the last video, so I hope you understand which point is okay, that we How are we going to solve this question, so what we have to do is simple one drive and let's take this one you three four five six what I have you do this I bill that tag okay I store all the invalids in the stock As I have been doing till now, all are valid since late, now here we will run things like this in stock, OK will be closed, debt bill will be Need tu sweep late if I am of open then open +1 then open +1 then open +1 divided by tu this gives your answer. Now when there is no saving in last i.e. there is odd par then we put this i.e. there is odd par then we put this i.e. there is odd par then we put this plus to handle this condition. One These Five Led You Told You In Coco Eating Bananas So If You Are Suddenly Jumping Into This Video So Thoughts Are Always Say's Full Series Watch Ok Let's Knowledge Ok Blind Zone Is If Your If it goes before close open or first or if tag is given then total size is ok number ok none was on valid i.e. I inserted as many none was on valid i.e. I inserted as many none was on valid i.e. I inserted as many elements as there were in the stock so I have wasted around up and time plus off and space Can I optimize yes of wesle you know they have tu us tu variables open and close ok so tu bill make tu variables ok your open zero pe and give close what is this also and you know whenever one will be on valid What they need you do is open mine is ok witch men basically pop operation please watch the old video this is actually already discussed method so I mean I will teach it again so those who are watching the already video have lost so much right please don't Mind and complete other video go and watch anyway so you miss open mines open plus ok open equal tu zero ok and you know the calculation this is a big open solution and space how many exercises have we done in seconds Off one space in the solution is fine, don't start it, friend, this was in today's video, if you liked the video, please like the video, subscribe the channel and share it with your friends too, see you.
|
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 |
290 |
hey everybody welcome back and today we'll be doing another Lead Core 290 word pattern this is an easy one given a pattern and a string for a find if s follows the same pattern so uh here follows me in a full match so what is a match uh by seeing the example one you can see that there is a pattern A B A and let me write it down a b a and the other one is dog cat and dog so now what we will be doing is we have to see like these are just making I'm making maps and you will see that AV is mapping to dog and then B is mapping to cat and he again is mapping to cat and dog again is mapping to uh a again is mapping to top so these will be the values uh and for this like you can see uh from the perspective of s to pattern dog is mapping to a and cat is mapping to B and again B and dog is again mapping to a in this condition we are there uh where the value at map one value of a is equal to the value uh the to the B you can say the first word at B and what is the word it is just being separated by the space so it is the same and if it is not then it will return just false you can see like a will be mapping through dog and a again will be mapping to dog and vice versa so in this case we will turn true but in this case where one value is changed like fish here fish and it will mapping to a part here there is an error film mapping to fish and a cannot map to a as a key cannot map to two different values so that's it we have to check if the values that is incoming is already present and yes if it is in incoming then we will allow it otherwise we will just return false immediately and that's it now let's code it down so first of all we'll be making a list and split this whole string on the basis of uh you can say a gap and if the length of words is equal to length of pattern only then if we are going to proceed the letter Y we will just return false because there is no way they are going to be the map of each other or will return true so we will just return false and in the else case there will be CW map and the WC map we will that will just character the corrective word and a word to character so that's it and now for i n range there is a function by the way in Python where you can just do like this a b in zip and you will say like putting words first but we'll be putting pattern first so a will be for pattern and we will be for words and that's it so you can check if a in CW is present in CW and CW at a is not equal to B in that case we will just return false and if be same with the B same process like if B is not equal to a incoming a then we will just return false and if it is done we didn't return it on false then we know that we should do the map like this value at CWA will be equal to the coming B and value at WC B will be equal to the A and if you pass all of this we know that we are going to return true so that's it and let's see if this works yeah this works and let's submit it and that's it
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
456 |
hello and welcome to another video in this video we're going to be working on a 132 pattern so in this problem you're given an array of nums and a 132 pattern is a subsequence of three integers nums I nums J and K such that I is less than J is less than K and it's index-wise and is less than K and it's index-wise and is less than K and it's index-wise and the num's I is less than nums K is less than nums J if turn true if there is a 132 and false otherwise so in this first example there isn't but let's take a look at some of the other so we have three one four two and in this one there is a one through two pattern because if this is I this is J this is K that works right J is greater than i k is less than J but it's still greater than I and then in the second example there is also a 132 pattern and there's a bunch of them but this is like one of them so if this is I this is J this is K that also works right I is less than j i is less than K and K is less than J so the Brute Force obviously is to just go through every combination of i j k and that would be n cubed but what we're going to actually try to do is we're going to try to find a good way of storing I and J and then we are going to be using those to be getting K or we're gonna try K from those stored I and J so let's actually look at some problems like let's say we do have this like maybe three one four eight nine two let's say we have something like this so how do we find an efficient way to store I and J pretty much and let's just think about one thing first so let's just say we have some J value like let's say this is our J what would be the best I for that J right the best possible I well the best eye for any J is always just going to be the smallest number in the array before it right so for like this J the best I is this for this J the best eyes one as well right for so for every number past one the best I is going to be one so to store I is gonna be pretty straightforward we're just gonna store the smallest number we've seen so far and that's obviously going to be like the best eye now to store J it's going to be kind of tricky and we need to store multiple values and I'll kind of show you why but essentially what we're going to be doing is we're going to be storing a combination of J and I and then we're going to figure out like what J values are redundant so for example let's say we have this J value that we store right and this would be the I and so this would be you know like eight one but what if we get to this J value instead if we have this J value like it's farther down so also notice that as you go farther down your I value is only going to get better and better right so if you think about it like for the I values like let's look for let's just say for all of these J values what would be the I value let's try to figure that out right so for this value there's obviously nothing because this can't be a j valuable let's say for this J value this can't be a j value either because the smallest value we've seen so far is three but here the smallest I we've seen so far is three so three would be here actually no sorry it wouldn't be three would be one right so if you one but it can't get worse because it's the smallest well it's the smallest value you've seen so far so as we Traverse right our I value can only be the same or better so knowing that as we Traverse right our smallest value can only be the same or better let's compare these two J values like if we have this J value stored with this I so we have one eight stored if we get to 1 9 do we even care about this one a like is there a k value that this would fail for and this would work for well not really right we're maximizing our J value which is good right we want to have the biggest possible J value possible so if the ri value Remains the Same ideally we would want to have something like one or you know whatever I value we have and ideally for our J we have like Infinity because that maximizes the range K can be in right K can be anywhere from Infinity to I now so if you have eight or nine the biggest one is always going to be better so when you have two J values and one J values further down any J value that's smaller is going to be useless pretty much right because remember our I value is gets better and better as you go down but our J value we want to store the biggest one possible so we're never going to want to store J value that's smaller than one we're on so if we have a bunch of J values and we get to bigger J values we can just pop like we're going to be using a stack we're going to pop J values that are redundant introductive J values are J values smaller than our current one because like I said our I is going to be optimized so as you go down this array I is optimized I is going to be better and then for J to be optimized you want to have the biggest one possible but you got to keep in mind if J is decreasing then you can possibly have something better like you have to store both of those so let's say we have a j value of like I don't know let's say it's like 100 here we can't just be like this 100 is better than something down the road we have to store actually both because for example let's say we have something like this we have 30 100 and now we have a smaller J values actually we literally have like let's say uh right something like this so we can't just store only 100 or else we're never going to have a solution here the solution is actually 198 here so as you go down the road the smaller value can get a lot better right the smaller value is going to be here the I value so we you have we might have to store smaller J values but we're never going to store uh where like yeah so our J values can be decreasing so we can have like a hundred and the nine and then eight and so on but we're never going to store if we have a nine here and we hit like a 15 later we then we don't need this nine this is redundant because the eye value is only going to be better here or equal to here so we're never going to want to use this value so now that we know that our I values are going to be better or equal going right and if we hit a j value that's bigger than previous J values we can get rid of those but not necessarily smaller right so our J values are going to be strictly decreasing and then our I values are going to be equal or increase uh equal or decreasing as well so let's kind of walk through now what would happen here essentially and kind of how we do this so we're going to start by keeping just some I value whatever like we're just going to make it Infinity and this I value is just going to represent like the smallest number we've seen so far so we're going to come over here and we're going to have a stack and our stack is going to have an i and a j value so let's maybe just draw our stack like this just to have some variables uh something like this doesn't look great but something like this so our stack is going to have an I value and a j value and we're only going to put things into the stack where the J value is greater than the I value so for this number obviously we're gonna we're not we can't put an i in a j because there's only one value but we are going to update our I to be the smallest value we've seen so far so the smallest value we've seen so far now is three I don't know what that is okay now we're going to come over here and we're going to say okay so the smallest value we've seen first of all our stack is MP so far right as you can see so we can't like pop anything and the smallest value we've seen is three so if this was a j value we can't have three one right J has to be greater than I so we can't really put anything into the stack for this one but we are going to update our I to be the smallest value we've seen so far so now we come to this four we don't have a stack again so we're going to check is four greater than one yes it is so this is a valid IJ pair and we don't have a stack so this can't be like a k value or anything right so we're going to store this now we're going to come over here and we're going to check okay so we do have a stack but like I said if a j value is smaller than this current value this is redundant right so if a j value is smaller than this value the end of our stack this can't be a k because K has to be smaller than J right K has to be smaller than J so this can't be a k but this is redundant because our smallest value can only be better here and we're going to want to maximize J so there's no reason to keep this so essentially what's going to happen here is we're going to pop this and there's nothing left on our stack now so now we're going to say obviously we're gonna add this on now right so we're gonna have one eight now then for this value here we're going to say okay is this bigger than the end of our stack yes it is so this so This value now is redundant so we're going to have a 9 here and a 1 here and now we get to this value and so is 2 uh is 2 bigger than this J no right so we might have to put it on we don't really know yet but now we can check if this is a valid K value right so let's check if it's a valid K value so if for it to be a valid K value it we already know that it's smaller than J because if it was greater than or equal to J we would have popped this off right so in order to check if it's a valid K value it simply has to be greater than I and it is greater than I right so if it's greater than I we already know it's less than or smaller than J then we have a valid answer here so our answer would be uh 192 here and we do have a valid answer so that's essentially what it's going to look like is your J values will be strictly decreasing and then your I values will be decreasing or equal and let's look at another example let's look at maybe a couple more so we're going to keep the same stack but let's look at a couple more just to kind of like understand a little better so let's say we have that other example of the 30 60 and then we have like 10 20 15 let's say something like that okay so let's kind of walk through the same thing so for the 30 we're going to be at the 31st we're going to check is there a stack no and we can't we obviously can't put this on now remember our eyes are going to start at Infinity you could start your I to be the first value in your array and then just start the second value for your actual Loop for the stack so I is going to be 30 here now we are going to go to 60 and we're going to check is there a stack no so is this a valid J yes it's greater than 30. so we're going to put in 60 30. okay now for this 10 is this there is a stack is this greater than J no it's not okay so we're going to check is it a valid K so we already know that it's smaller than J so now it just has to be greater than I and it's not a greater than I this is not about K value and is there a valid i j pair here no there's not because the smallest value is 30. so there is no valid IJ pair using this value but we are going to update I to be this because this is our new smallest value seen so far now we're going to go to this 20 and we're going to check once again is it greater than J no it's not or equal if it's equal we can pop 2 because we don't need duplicate values so it's not greater than J but is it about i j pair yes it is so we're going to add it to the stack so you could see how like this i j can be decreasing because in this example our I just got better right so the I is always going to be better or equal and this J is always going to be strictly decreasing and basically the reason why we don't have to check all the way down is because there's going to be two cases right for our new value that we're putting in so one case is it's greater or equal to the end of the stack right so if it's greater than or equal to the end of the stack like if we're on this 15 or whatever this value is let's say its value is 100 if it's greater than or equal to the end of the stack it can't be a k value because it has to be less than J so then we're going to be popping right but if it's smaller than K what does that kind of represent or if it's more than J it's smaller than the end of the stack so that represents we found the smallest J value that's greater than the value we're currently on which means we're optimizing our smallest value to be because ideally we'd want to use the smallest value as far down as possible because those are going to be the best values right the more numbers you've seen the more likely it is you find the smallest number so essentially the way this algorithm works is we are literally trying to find the J value that's as small as possible while being bigger than the K because then we make sure that uh the I is like that eye has to be if that I is not less than that K value then the rest of it can't be either so we're going to be able to find in O of one time once we get rid of the Redundant JS is this a valid ijk pair so finally for this 15 we're going to say okay is it less than 20 no it's or is it greater than 20 no it's not right so now we're going to check for the K so in order for it to be a valid K has to be greater than 10 and it is and so this is indeed a valid pair or a valid ijk where it's 10 20 15. and now let's try to find one more example of one that doesn't work and then we're gonna code it up because this definitely I think it's very good to see a bunch of examples of this because like this part takes kind of a while to understand and it's definitely not super intuitive so definitely like running through a bunch of examples here this is like one of those stack problems that's not very intuitive at all but once you realize that you are literally by making your JS decreasing we're literally trying to find the first possible J value that's greater than our K because that will make sure that the eye is as small as possible for that J value so the eyes will only be increasing here so if this I value doesn't work if this I value is not a match none of these will work even though these J values will still be greater than your K so then that's why you have the O of one lookup if this one fails this whole stack would fail so let's actually go through one last example and we're going to go through one zero 1 negative four three negative three so let's go through this one and this one will also kind of show why you can't just store like a local maximum and a local minimum because if you did you'd find some stuff right if you store the local minimum or something you'd find you'd be like oh look this was our minimum this is our maximum and now we have something that's you know greater or less than this value but it's not greater than this value so it doesn't work so that's why you need to store all these things so let's go through this one so we don't have an eye like I said we can just initialize I to be the first element in the list so we'll make it one now we'll come over here and we're going to say is this a valid IJ pair there's nothing in the stack to pop so we don't need to worry about that and obviously not right because if this was J this is greater this is smaller than I so we're going to update our I to be this now we're going to come over here and we're going to check is this a valid IJ pair and it is right we can't have a k yet because there's nothing in our stack so I would be zero and this value would be J so that's fine okay now we'd come over here and we'd say okay is this greater than our J no it's not is this a valid IJ payer no it's not because it's less than zero so we're going to update 0 to be negative four and then we're going to come over here and we're going to say okay uh is this greater than our J no it's not so is this also um is there a valid IJ pair and while this is the last one so actually before checking if it's a valid ijpair you want to check is it a valid K right so to check if it's about K it has to be greater than this value and it's not it's smaller than the J but it's not greater than I so it's not and so is this about IJ pair um and that actually is right so I can be negative 4 and this is this but then we're done with the array and we haven't found an answer so if we didn't if we never found a valid answer then we're done so essentially we Loop through our numbers we check is it a valid is it greater than the J values currently if it is we pop those and then we check it's either a valid IJ pair or it's the new smallest number right one or the other and also we also have to check before doing that if there is a stack still we have to check is it a valid K and then if we go through all our numbers and we didn't find anything then we're fine and this is going to be of n time in open space because essentially worst case you're only pushing the numbers once on the stack and popping once and you're gonna have o1 lookups for is it a valid k so now we can code it up so I'm just going to make small the smallest number um it's actually we'll make that negative infinity or actually we want to make it Infinity right so we're going to make that infinity and now we're going to Loop through every number and we also need a stack so we're going to Loop through every number for Num and nums so first we're gonna pop J values that are smaller than the current J value we're on because that's redundant information so we can say while stack and I'm actually going to store them in terms of the J is going to come before the I so it's going to be stack negative one um zero it's going to be J and then I in the stack so if stack if this is smaller than or equal to the number and the reason why we're going to get rid of the equal to as well because we're gonna add this onto the stack so we don't need like duplicate numbers there's no point also if they are equal actually you still want the new number because the smallest index might have gotten updated so you see you want to get rid of it anyway okay so if this is the case then we're gonna pop so now that we do that we have to check is it a valid K so we already know that it's less than the end of the stack we already know it's less than the end of The J value but now we have to check is it greater than the I value and the stack actually has to exist as well so if stack and number is greater than stack minus one which remember we're storing them in terms of uh J and then I so if this is the case then we have a valid solution so we could return true now we have to check is it either a uh it either has to be a valid IJ pair or it's going to be our new small number or equals a small number essentially which is fine right so we can say if number is greater than small then that's going to be a valid uh that's going to be a valid IJ pair right so if number is greater than small then we can just add that to the stack so stack dot append put number and the small number and then finally we are going to update our small number to be the minimum of the old small number and the number so and obviously if the number is greater here then we don't have to do that right because that'll never be the case so else we can actually even make it uh we can even just make we don't even need to do a minimum I think we can just have small be the number because they're either going to be equal or the new number is going to be smaller so we can just say this we don't have to like check for a maximum or minimum I think and this should theoretically work now we just return false if we uh never find anything let's see what happens okay so you can see it's quite efficient and so once again to go through the time and space complexity here so and this is like I said this is one of the stack ones that's kind of really hard to figure out like why is it actually working and once you realize that like you want for any uh of the minimums that Fails Like if your minimum doesn't satisfy the condition then every minimum to the left of it will also not satisfy the condition because the minimums only get better like I showed in the picture once you understand that then you kind of understand the problem so for the time it's going to be o of n because essentially We're looping through our gnomes and we are either putting the number on the stack once or not and we're removing it from the stack once or not right so worst case scenario you put every number on the stack and then you remove from the stack so that's the low event and uh yeah and then for the space we do have the stack so you might have like every number from you might actually put every number on the stack that's possible because like let's say it's literally just like this an increasing array then you would put every single number on because every new index uh well actually I guess what would happen here is you would never have them all in the same time so actually I think you want this to be like decreasing probably to have every number on I'm not exactly sure how you'd have every number on but either way it's going to be open because you can't have multiple numbers on here I think maybe decreasing it would I would have to double check but yeah this is going to be a event because we do have a stack so yeah I think it's going to be all for this video so hopefully you enjoy it definitely quite a difficult medium problem I would say and like you even want to see the solution it might not be super clear still so I definitely encourage you like walk through the examples and see why this works and uh yeah if you did like this video please like it and subscribe to the channel and I'll see you in the next one thanks for watching
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
74 |
Hello Hi Everyone Welcome To My Channel Today We Will Solve The Problems Of Today Matrix So Right Edition Elva Edison That Search For Value In And Processes For Subscribe And Subscribe The Channel 30000000 Withdrawal Element Person Subscribed On Thursday Time Complexity Of Dissolution His Wife In This Classification Optimize Time Video Channel Suli Columns And Deflection Remind Karo Subscribe One More Start From Her Last Element Of B Id M Id 30 Current Track Subscribe Return For True Video plz 0306 Running Beta Version Row And Column Total Number Of Karo Quiz And Process From Detail Se 0504 And Seized From VPN - Subscribe Index And Seized From VPN - Subscribe Index And Seized From VPN - Subscribe Index For This Channel Subscribe Is Trick To Machine Is Loop System Disturbance It Means This Is Not For The Like This Element Left Side Of The Robot Were The Robot Just Hair Care Number In The President Rule Will Increase The Plus Subscribe Asal First Saw Her Is The President Of The Same Approach Should Behave Like Amir They All Know One Will Be Started From 200 To Learn From Last On Thursday Reduce The Negative And Last Element Veer Video Subscribe Like This Thank You All Elements And Give them agro directions first whole am go to 10 elements for watching this element interwar matric-inter subscribe number roll number of matric-inter subscribe number roll number of matric-inter subscribe number roll number of columns of boys subscribe and subscribe this Video data is not deny difficult say flat in this year will give the like this element 123 likes 1060 til subscribe and Hit The Video then subscribe to the three again so will go to the first time Edison Simple Normal Boys Singh Welcome aware of this element is equal to the element as per its elements greater than searching element will go to the fire element is Subscribe Channel Now To Receive New Updates Will Take It's After This Element Subscribe Like Subscribe And From Last Element Like Subscribe And Minus One Next9 Will See Idli Are Some Will Find It Share The Know How Will Get A Row And Column In Mid That Element 114 Roy Next Isi Shaadi Matrix Iss Aamir And For That So Let's See Members Country Include V0 Plus 1182 Which Will Find Some Vs Noida One Number Between 305 Divide 3515 That Moon Subscribe Our Target Element This Great Content Will Reduce - 10 - Use This Idli Content Will Reduce - 10 - Use This Idli Content Will Reduce - 10 - Use This Idli Hai Hain saunf aur record meetu first check sirf modi sonth 20 min is let me made this small amount only som ismart length is 0 and that might have no problem mode on is maximum in this the number of days is 90 followers will start from Start from 0 toe and from chief minister and minus one randhe secure start luno request hai this both rohit sofia handa and finally true validig very good video online research i will provide a good night so enter medical to start plus and minus stop this is request To avoid overflow if the start and very difficult to know who will check that fifth math tricks of middle number forms and middle models in this half searching and will return through advice will compare the specified condition that f-35 lungi targets and goals blog that f-35 lungi targets and goals blog that f-35 lungi targets and goals blog improved right side So we will update our start with j plus one health key and increase e-mail minus one and will try and country e-mail minus one and will try and country e-mail minus one and will try and country Indian hiffin find the value of evil return gifts e that Swadeshi's sample binary search for its compile record and work in let submit record That and accepted for the time complexity of dissolution of this effect in this and excise officer in the middle of lord of the human that and space is of handsfree solution private and you want to YouTube channel subscribe my video and fertilizers solution hindi like button culture
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
350 |
hello everyone today we are going to solve another lead code problem this is called as intersection of two arrays two so we are given two arrays nums one and nums nums2 and we have to find intersection between them and numbers can be repeated so in this case for example there are two tools and here also there are two tools so one is one two is mapped to other two and other two map is mapped to uh this particular two okay so let us try to understand what we can do so there are two parts of this question the first part is when this given numbers are not sorted and they are given like in any order okay and if the given number given arrays are sorted so we will try to find two different solutions um okay so let us look into this first part so this is first part in this particular case the solution is quite simple so we know that we are given this two areas and we just have to find the intersection now what we can do is suppose we create a result okay and we have to find the intersections in this two arrays so what we can do is we can simply create a hash map of either of this array and then iterate through another error so let us assume that we created a hashmap for this okay with frequency so it will be something like 1 is 2 and 2 is also 2 okay so this is their frequency and this is the number now when we iterate through nums 2 we simply have to check the hash map of value 2. so in this case see this we obtained 2 here now what we do is we simply add it here 2 and reduce this frequency by 1 okay then we go to another 2 and then we again find two and we reduce the frequency to zero and here add it and we only check for those hash map whose value is greater than zero so for example if we had another two here somewhere um we won't be able to add another two here because sim simply the frequency of two in this case is already 0 so this is our answer which is quite simple now let us try to understand if the given arrays are shorted so these are sorted we simply took the same input and we just sorted this arrays okay now what we can do in this case is we can use simple two pointer solution okay and in this case we had used hashmap and in this particular case we can simply use two pointer so what we can do is let us say we call um the position of this num's one as pointer one and this position as pointer two okay now what we have to simply do is we have to loop through okay we can do a simple while loop where this p1 is less than uh let us say the length of nums one is n and this length is m so when p1 is n and p2 is less than m okay so when this condition is true what we can do is we check if the nums one of p1 is equal to nums 2 of p2 so in this case if both the elements at the given pointers is same that means we simply add it in the result okay so add to revert now if they are not same so for in this case um this p1 and p2 these are not same so we simply check because we know that the arrays are sorted then we check which element is larger so in this case if let us say nums 2 of p2 is greater than nums 1 of p1 then we understand that this element is larger so that means we simply have to increment this pointer so now this p1 will point somewhere here now again same condition is correct then we go somewhere here with p1 now this p1 and this p2 both the elements are same okay so we add it to the result so our result is something like this so we add it to the result two then again um whenever we add to the result we increment both p1 and p2 okay so now p1 is here somewhere and p2 is here now again same condition we add it here and that is our answer so this is quite easy now we'll also look into the code and see how we can easily implement this both the solutions so let us go to the code okay so we'll try with the first solution that is the hash map solution so what we can do is we can simply start with the hash map and then add a frequency in this case so for n in nums one h map of n is equals to h map dot get n zero plus one uh now next thing is we just have to check if those elements uh the elements in nums two are present in the hash map and we simply have to reduce the number so for and in nums 2 what we can do is if and in h map and um h map of n is greater than zero then what we can simply do is uh first we have to reduce it the values and also we have to add it in the result so answer dot append and we can append end here and i guess this should do so let us try to run this code and see if it is running so this is accepted so this is working fine we can also submit this code and uh check if this is correct or not so this is correct now we look into the other solution when the given nums arrays are sorted so let us write the two pointer solution let us sort the errors let us take the pointers p1 p2 as zeros initially and let us also take n and m as length of number one and length of nums 2 now while p 1 is less than n and p 2 is less than m we can simply do or check if both the elements are same if nums one is of p1 equals num2 of p2 then we can simply increase the pointers both the pointers also add to the answer so p1 or p2 we can do anything here and let us take answer to store our result also now next condition okay we can simply do continue um if num s1 of p1 is greater than nums 2 of p2 then that means we have to increment the pointer p2 yes is there something else to add okay assume no let us just check it once okay i guess we are missing something in this case okay so if both are same then we increment both okay else condition we forgot to write p1 plus equals to 1 because if now nums 2 is greater than nums 1 then we have to increment the pointer p1 also to get a greater value in num s1 of p1 so that it can match to num stop p2 let us now check this code yeah this is working fine and we can even submit this and this should also work fine okay i guess you understood the solutions both the solutions so first we looked into this intersection uh without having the arrest sorted and the other solution was sorted rf so the when the errors are not sorted in this case we used hashmap so that means our time complexity for this solution was um big o of let us say if the size of this is m and this is n so we are using hash map for numbers of one then let us say m we can do this and okay m plus n time complexity and space is big o of m or we can even do like something like optimizations minimum of m comma okay and for this particular case was if the if we assume that is given or already sorted and we are not calculating uh time required to sort this okay then this becomes um time complexity as uh minimum big o of minimum of m comma n and uh space is big o of 1 i guess because we are not using any external space yeah but in case if we also consider this sort then this will easily be off and login and login plus m log m something like this okay thank you for your time
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
672 |
hi guys good morning welcome back to the next video which is a bulb switcher although the problem a rating is not marked as that good but I say it's a good problem if you just want to have that math understanding and all that stuff so yeah I'll just say okay it's actually a good problem not actually a medium problem in terms of maybe it would have been marked a score of two or maybe while in a contest that's the reason the people have marked them marked it as more dislikes but maybe is this a good problem you should try it so yeah let's start with what the problem is saying it's pretty easy that we have N Bulbs okay in total in the first try which is first round which is first iteration you turn on all the bulbs cool which means everyone one two three four five six up till n then at the second round you toggle off every second bulb which means two four six eight and so on right on the third round you toggle every third bulb which means toggle is just if it is on make it off if it is off make it on so basically in initial we make it on all the bulbs then in this round we make it off so here also we did a toggle of every second bulb here every third ball in the third round swim goes for the ith round every ith bulb needs to be toggled and at the round nth bulb will be made if it is on it will be made off if it is off it will made on now we have to say in the last of those n rounds number of bulbs that are after like which are on number of first example which means in the first round one two three all will be made on because all are multiples of three what are multiples of one then two will be toggled back which means on then it turned to off in round three will be toggled which means on then off thus in final state only one bulb is there on thus the answer is one let's look it with a bigger example let's say we have six bulbs so as we knew that for every bulb which means if we have six balls so we have six iterations which means six rounds we will have cool in the first round every bug first second third or fourth or fifth and sixth everyone will be turned on because everyone is a multiple of one cool then in the second round two four and six will be toggled back which means on to off now the new state is this then in the third round every of the third bulb which means third and sixth one will be again traveled back which means on to off to on now it is the new state in the fourth every is the fourth one which means only the fourth one will be talking about in the fifth round only the fifth one will be toggled back in the sixth round only the sixth one will be toggle back now if you clearly look now see what I did was I mapped iterations to okay what is one how one iteration looks like for every of those bulbs now I will map the reverse thing which means for every of the bulb how may it in how many iterations it comes in which means as you can see one it only comes in the first iteration which means if it is on it remained on the entire time right bulb two it just Switched Off just one time and then it remains same right bulb three it just switched one time and then again it remained same while before it switched here to here which means one time it remains same it again switched next time also then it remains same so I will just map the same thing which means for one it is affected only at first iteration the bulb two is affected at first and the second iteration which means in the first iteration it is made on and then it is made of and then it just remains off only which means first iteration it is made on then at the Third Edition it is made of now it is main seam so you solve at and the fourth well it is affected at first second and fourth iteration which is football if you just go on first second and fourth iteration right it is being changed okay cool and same also the fifth bulb and the sixth ball if you just clearly look then what's happening is first when it say Okay first second and fourth iteration which means on off and back on right so in total if the iterations if this okay is it's it goes off first second third fourth is the number of iterations are odd then it will at last be in on state then the number of iterations are even it will at last be a off Street okay now we have to know for every bulb if the number of iterations are actually odd I'm gonna say okay it will be in at last call but you saw what these numbers actually are showing one what is one for two what is one two for three what is one three four what is one two four for five what is one five for six what is one two three six there are factors of that number for six the factors of six are one two three and six for four the factors of four are one two and four for three the factors of three are one and three okay so now I get to know one thing these are the factors of a number and if the factor of the number is the number of factors are actually even I'm gonna land on a off State but if it is or I'm gonna land on an even state so one standing division which comes in my mind is that I'll just go and say what all numbers out of the N A numbers because I have N Buds of the N Bulbs how many bulb half odd number of factors which means for every number I'll just find the number of actors depending upon which algo you use uh you can find the number of factors let's see the complexity which you use is O of f then for every of those n numbers which means for every number from 1 to n you will find the factors and whatsoever number has odd number of factors you will just return that count of numbers but can we just improve that if we just clearly visualize okay what ultimately I want is what are the numbers which have odd number of factors now let's visualize the factors of every number so that I can find them okay what all numbers can have odd number of factors so if I just write down numbers from 1 to 10 I return the factors of every number now what happens if you just clearly see I'll just pick and choose okay as you can clearly see that only the numbers 1 4 and 9 are the one having all factors arrest all have even factors but still we will just go reverse with let's just remove all the numbers firstly we are pretty sure for all the numbers right here that things are numbers which are prime so for every of those numbers you for sure know that if it is a 2 then it's a prime number then the only factor is 1 and 2 itself that's okay one and two the one and the number itself only two factors it's always going to be your even number of factors if you look at the other numbers also we can also Club them in the same thing as above that for every number if you just clearly go and look that then every number looks like this the factors are nothing but if you just go for six we have one six one into six and two into three for eight we have one into eight and four into two for ten we have one to ten five into two you can see it's just pairs of which means every number can be represented as a pair of those factors which means if I just represent nine also it is one into nine and three into three the only difference here is the three is being repeated again so in total the uni factors are although it should have been four but one of them which means three is repeating again that's the reason the factors have now become hard that's the reason if yes clearly you can see then the factors always are in pairs but for the numbers which are prime perfect square for the numbers which are perfect square one of the factor will actually repeat and we have to find the uni number of factors that's the reason although it would have been even which means 2 into X or something but as one of the factors is repeating because root of 9 is actually 3 which means 3 into 3 is actually 9 so 3 into 3 that 3 again is coming but I have to count the unique number of factors which means 1 3 and 9 I will count that's the reason it will have 4 minus 1 minus one for repeating three that's the reason even minus 1 you are always out that's the reason I will just land onto all factors for every of those perfect square numbers because for those perfect square numbers I will get up one into one two into two three into three which is actually repeating Factor which I have to remove from the factor itself that's the reason I will just count what are the numbers of perfect square up till the number n and that can be easily found by just doing a square root of N and that's it's your answer which means square root of n are the number of perfect squares which are less than that number which means if let's say if I ask you what are the number of square perfect square up till the number 20 you just do a square root of 20 you just return okay it's 4 so this 4 is actually the number of perfect squares how it is 1 4 9 and 16. these four numbers are the perfect squares less than the number 20. um how would I know that it's solar defense I mean why listen if we just clearly go and look at the number 20 and all the perfect square less than 20 then we can easily look it's 1 4 9 and 16. if we just write them back on okay what's a multiple like it is one into one two into two three into three four you saw what's happening it's the first perfect square it is the second perfect square it is the third perfect square to the fourth perfect square which means first second third fourth that's the reason if I just do a square root of 20 it will land me back to something like as 4.472 but it just it like intelligent 4.472 but it just it like intelligent 4.472 but it just it like intelligent means okay it's not a perfect square the last perfect square it just ended at four that's the reason 4 means okay that's the reason I have one four nine and sixteen as the perfect square as these four perfect squares less than this number 20. that's the reason I just can return a square root of n which can be internally every language has internal implementation of square root of n which is actually your overflow login implementation although you can actually by yourself also Implement a o of one approach of that square root of n but that's just a high effort for this small question because understanding this question itself and getting to answer itself is actually a big deal so I guess it will be okay for you should like you if you want you can go to off one also but it's internally how the square root of n is implemented by o of login and it would be good to go space is no use so it's O of one only but yeah you just have to return the square root of N and it will be the number of perfect squares less than that number n and that will say okay what all number of bulbs will remain on in the end that was all from me I hope that you guys liked it code for every language although code is pretty simple it's just square root of n square root of N I hope that you guys liked it if yes foreign
|
Bulb Switcher II
|
bulb-switcher-ii
|
There is a room with `n` bulbs labeled from `1` to `n` that all are turned on initially, and **four buttons** on the wall. Each of the four buttons has a different functionality where:
* **Button 1:** Flips the status of all the bulbs.
* **Button 2:** Flips the status of all the bulbs with even labels (i.e., `2, 4, ...`).
* **Button 3:** Flips the status of all the bulbs with odd labels (i.e., `1, 3, ...`).
* **Button 4:** Flips the status of all the bulbs with a label `j = 3k + 1` where `k = 0, 1, 2, ...` (i.e., `1, 4, 7, 10, ...`).
You must make **exactly** `presses` button presses in total. For each press, you may pick **any** of the four buttons to press.
Given the two integers `n` and `presses`, return _the number of **different possible statuses** after performing all_ `presses` _button presses_.
**Example 1:**
**Input:** n = 1, presses = 1
**Output:** 2
**Explanation:** Status can be:
- \[off\] by pressing button 1
- \[on\] by pressing button 2
**Example 2:**
**Input:** n = 2, presses = 1
**Output:** 3
**Explanation:** Status can be:
- \[off, off\] by pressing button 1
- \[on, off\] by pressing button 2
- \[off, on\] by pressing button 3
**Example 3:**
**Input:** n = 3, presses = 1
**Output:** 4
**Explanation:** Status can be:
- \[off, off, off\] by pressing button 1
- \[off, on, off\] by pressing button 2
- \[on, off, on\] by pressing button 3
- \[off, on, on\] by pressing button 4
**Constraints:**
* `1 <= n <= 1000`
* `0 <= presses <= 1000`
| null |
Math,Bit Manipulation,Depth-First Search,Breadth-First Search
|
Medium
|
319,1491
|
6 |
Jhaal hey brother and welcome to get specific today if just any thing problem the continent of victory in the Christian eminent people and subscribe problems can they give me the number of district rule in it's true lies in it's a our field here being different is directly Day The See For Example Of Benefits Through To Start Doing Agni Back's Newly Discharged Valid Contract For Members Form Her Induction Why Do We Call The Number Of The Day Are Next Ingredients E-mail Next Ingredients E-mail Next Ingredients E-mail Person Filling Up The Road Making Roles Subscribe Button To Do The Thing Ro Question Is Deposit Where Going From One Binttu Second August 2002 302 201 21 123 2 F 2 10 Gram Subscribe Video Subscribe 512 Hai To Wicked Vikram 2068 Begum One Difficult To-Do List Vikram One Difficult To-Do List Vikram One Difficult To-Do List Vikram One Difficult zero-valued 102 100 to 120 Devices - 121 Subscribe Like This Also Let's See Close lit Kami Lage Aur Suji Yeh FD Ke Adi Due To It's Not Doing All In To-Do List Seervi First 000 - 120 With U The Ring To Next Day Vishuddha Gyan Decrement 102 Let's Do Me 108 You Tell Me If It's Plus One And - 108 You Tell Me If It's Plus One And - 108 You Tell Me If It's Plus One And - How To Tell The Value Vikram 0 votes In Preventing Thee Victims Nuvvu Start Decree Withdraw All pre-2005 Notes - 1929 Quote Superhit Decree According Doing All Chapters Page Straight Thread The Noose Towards Yourself Straight Statement See The Question Quote Just Want Without Doing In Thee This Event United Unplugged Song Talking About Time Complexity Talk Time Complexity Subscription Declaring and Subscribe Former BCD and CVD Plus One Two Three Bigg Boss Joe Hair Ki Testing and In Love with Met After Time Complexity on which Initiative Will Not Coming subscribe this Video plz subscribe and subscribe the Subscribe Roof End Space Akshaydeep Twitter Switch Off Wave Very Clear In Dishas By Students Bigg Boss Subscribe Comment And Subscribe This Video Give This Is The Subscribe Thank You To The Tu Pattern When Doctor System Akhilesh Das Can Access The Editor Of News Atal Given In Next Job Portal In Notes Can Take Care Personal Subscribe To Juice Like And Subscribe To
|
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 |
278 |
foreign the latest version of your product fails the quality check so since each motion is developed based on the previous version all the versions after a bad version are also bad suppose you have n versions from 1 to n and you want to find out the first bad one which costs all the following ones to be bad there are bad versions okay so let's say there are versions from 1 to 8. 5 and a and let's say the fifth one is the first bad version so all the version 6 7 8 all the version six seven eight after the first bad version are all bad versions and that is what they have told here and you have to find the first pattern so if all these are all of this as the bad versions then you have to find the first bad person that is file has to be written as the answer so you are given an API rule is bad version of version which returns whether version is back so how do we get to know whether a version is bad or not directly given an API which is where to call this so which returns whether the given version is bad or not so implement the function to find the first pad version you should minimize the number of calls to the API so our main intention here is minimizing the number of calls to the API and that is the function how do we Implement that function to find the bad function with minimum number of calls to the API so uh usually the linear search could be applied so we could have placed from 1 to n we can iterate over it and whichever function gives us first as a pad I mean answer as 0 or like negative then you just written that particular answer as bad motion but uh they have told they have to minimize the number of hours so best method which comes to our mind since the numbers are in the ascending order sorted order we could use the binary search yes you could use binary search method so first we will have the numbers one two three four five six seven okay research as you know one point will pointer Point into right and we have to calculate so mid will be nothing but left plus light by two so let me just write the indexing 6 Plus 0 by 2 will be 3 so it will Point here and here uh we cannot just do with equal to left just right by 2 so make equal to usually what we do is left plus right by two so we'll not use this we will use the other method because this is cause an integer Overflow what if left and right something that is maximum and it will cause an overflow after the addition of the two numbers so what we do is we use on the left Plus right minus left whole so what does it mean so first we do right minus left see right is 6 minus left zero that will give you six means right place left will give you the size of the current patch so size of the current batch from left to right it will give the size so first we need to find a size 6 minus 0 is 6 when you divide it by 2 it will exactly point to the middle that will point to this particular number so 6 minus 0 will give you the size if you divide it by 2 to the point to the middle index so from left you have to move till the middle index so left plus the middle index that is three so zero left is pointing to 0 plus 3 so that will give you three if in case left was pointing 1 okay 6 minus 1 will be 5 by 2 will be two so five by two will be 2 right so from left we have to move two pointers so it will point to three again so that is how we solve the problem so once you get the middle now we have to check we have to call the function is bad version of meter so is bad version of mid so this is a function so if this returns false what does it indicate if this rate is false if this written false what does it mean all the numbers all the versions next to this value are false that is for sure so this we can cancel and this also we can cancel but what about the number previous tools this can be an either bad version or a good version right can either the bad version or not a bad version so there are cases so what to do we initialize the right to the middle not mid minus one because mid minus one we are not sure whether it is the first bad question or not there is a balancing previously so since we are not sure about that we'll do write equal to Mid so that it will point of it so what the reason why are we just assigning write a particle because we are not sure whether the three is bad motion or not it can be a bad position it cannot be a bad machine this is three is not a bad question then four is the first bad version itself so in such case you should not move further back no so that's what that's the reason so once you get right again left plus right by two here now in case if is bad version of mid that is pointing to this element if this gives false if this is not a bad version then what do we need to do equal to your given number is not a bad version that means this number is not a bad version so the bad version will exist after mid that is for sure so what we do is left equal to Mid plus one so this will be left so left equal to with plus because in this case we will show this particular two number to second version is not a bad version because we are pointing it is pointing to the mid and that particular version is false state has given so it is not a bad version the number next to it only can be a bad version next after the middle so we as an electrical replacement but then it comes to the right we assign it to hit because there are chances where we do also can you have bad version and a number previous also can be a vibration the number pointing at midoli can be the first bad version so that is the reason so we will implement the program so first binary search right so it's left equal to zero then in right equal to and N minus one and yeah at last which will be the answer will be pointing to so it's like a cross music since right if this is pointing to bad version and left this is not pointing to that option so once the index crosses left to be important to vibration right will not be according to minus it will be either pointing to or not pointing bad version that is how the logic is right left lesser than right so first we calculate equal to left Plus right minus left why are we doing this because to handle the integer overflow so if is bad version of made so if it is 2 then the right will be equal to Mid else left will be equal to 8 plus 1. so at last return left okay so this should be equals yeah I was thinking so thank you one second see since lesser than light is fine and since the number is Raging from 1 to n I had to give one to N1 right that is where it is shown false because 0 is not at all in the reach that's why yeah and for Java also same logic and same broken nothing change in any syntax so we'll submit this let's go okay here there should be one bracket yeah successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come up with another video in the notification until then keep learning thank you
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
963 |
hey everybody this is larry this is me trying to do uh something new which is that i'm going to try to do one problem that i haven't solved before so um because the daily problems have been repeats for me so yeah let's see let's check that out uh let's just say to do and yeah let's just click on it is there an easy way to like pick a random one pick one is that does that work have i solved this before let's see well okay maybe we should pick one that isn't premium still way too click on that no okay let's try again okay and i haven't done this before so let's go so two so today's random volume is 963 minimum area rectangle two let's see the given array of x y point points where points of i is equal to x sub i y sub i return the minimum area of any rectangle form from those points given that the sides are not necessarily parallel okay um i think so this part is let's see well let's figure what n is okay n is 50 so it's um so the tricky part isn't going to be the complexity right because now you can choose n choose 4 which is 50 to the fourth or something like that um or if you want to be a little bit what's 50 to the 4 maybe 50 to the four is a little bit too much yeah that's six million and in a lot of languages that'll be okay probably five maybe a little bit too slow but we'll see but that said if you're given three sides you know where the fourth one should be so you could optimize that way for sure um so we'll talk about that in a bit but the second part is just figuring out um oh it's a rectangle not a square huh i mean that i think squared there are like cute tricks that you can do but rectangle is fine as well um it has to use all four points then okay i mean i think it's just about so we can try to do this in n cube and that's what we're gonna do or n choose three maybe more specifically which uh i guess that's maybe faster let's see because i'm just googling 50 choose four because 50 choose four is not quite the same as 50 to the fourth right 52 sports only is apparently 230 300 so actually that'll be fast enough so we do i think that's the difference um between and choose four versus and to the fourth right because n choose four is technically roughly o of n to the fourth but it is at the way at least n over four over 24 ish right um so yeah i mean it's actually less than that even but as a result 50 choose 4 is way less so we can force it so let's try um so first we do this you know the loops and then the question is well what is a rectangle right a rectangle means that given um a rectangle also i have to double check that we don't duplicate but i think this should be okay but because we do it this way we have to be careful that we have to try all orientation um this is a annoying problem but mostly because i'm not very good at geometry but yeah um i think here we so what is a triangle right oh sorry what is a rectangle is you know two sides a rectangle is two sides or two sides equal to each other and two sets of sides if you will and they're opposed each other so you don't have a diamond type thing right but uh i think the tricky thing with the way that we're doing here is that we're not trying all possible orientation so we have to be a little bit careful and i think the way that we'll have to um i think given any so one way to think about it is that for every two points so i don't know if this is quite generalization but for so you have two points on the um let's say i and j and then you have k and l those sides have to be equal right oh but um so i guess obviously having four sides being you know that uh is not enough because you have to do the angles um so basically okay so let's maybe list it out but first um so first sorry i my alexa was pinging me so i had to tell it to stop but so first a sub i plus a sub j should equal to a sub k plus a sub l right and also the other case as well because you can just think about it as visually the points and then the possibilities have to be even the oh maybe that's the way to do it because if let me draw it out actually because i think i've been doing hand motions a lot um okay so i think this is right now okay let me put on the screen and sometimes uh learning these problems is kind of expo doing these explorations so i'm very excited about that maybe i'll use it in the future because i didn't or may i probably knew it in the past but i don't know so there are a few ways to do it right and i think the first uh observation about you know opposing you know let's say you have uh oops that's a j right i j k l and it has it can be in any direction really right um then here if we take any two points that are not or you know when we take two lines that are not next to each other they have to be the same right so that means this has to be the same with this and this has to be the same of this but of course this isn't a rectangle by the virtue of the obvious thing which is that it does not access parallel right uh oh that's right well it's also not accessible now but it's just a diamond right because i have to be 90 degrees so then the cube thing is that you can also actually check uh one additional thing which is the two diagonals so given these two diagonals if you have a rectangle then it should be the same as well and in that case now that means that for a number a sub i or a point a sub i it will have to be equal to you know so that means that all the line pairs have to be the same right so i think that would be that's good enough for me to get started on programming hopefully that made sense for you at all okay so yeah so this length has to be the same and then what i'm saying is that this length also has to be the same because that's just the other side but also now the diagonal has to be the same assuming i mean depends how you know because these points go every way but now we this is way easier in the sense that we don't have to worry about you know orientations and stuff like this right so yeah let me let's okay let's see um how did i say this um let's see right so a x i know maybe just x i y i is equal to points of i guess just this because maybe i could just put it here as well and then x j y j is equal to point sub j uh x k y k and then x l y l is equal to point sub l and then here like we said so then the length of all of these so yeah i usually actually would write a helper function for this but i feel like lead code is very slow okay so yeah um let's just do it anyway we'll see what happens if it's too slow we'll optimize it out so we have just say length two and while i would say length two is just so that i um yeah maybe just a b and i don't need all this stuff then uh maybe that was just fun but length two is because i want it to be length squared and the reason why i say that is because now we can do something like it's minus b sub zero so we have this square or just times itself maybe that's a little bit easier to write and the idea here is just that so we don't have to worry about square root or something like that and everything will fit in um everything will fit in a integer or and by integer i mean uh like you know um like whole number right so yeah um and also the sign to be positive and stuff like this so there's a lot of benefits here um so then here we go if um length two of points of i so now from points of i to points of j is you go well let's actually store this so we don't have to do uh you know l i j is equal to this l i k is equal to length 2 of sub k something like this l i um okay that's a little bit awkward but yeah and then now ljk has got length two of points up j points up k name j l is equal to basically this is all eight or six possibilities maybe i could win this a little bit more quite a little bit nonetheless um and then l k l is equal to length two well points kl and of course the thing to optimize minor thanks to optimize here is just putting this here so we don't do a duplicate work and i sub k we can put here for example and j sub k as well and then the last one is just these things um and then here we go okay if l sub i j is equal to uh l sub k l hopefully this is right otherwise we did a lot of stuff where it is wrong so uh ik is equal to j l and uh what's that's one i l is equal to j k right then count increment by one um yeah that means diagonal right all possibilities and i think this maybe is a good start uh let's hopefully this is right if not then it's a little awkward now did i misread the problem at all a minimum area of any triangle okay i mean that's fine wow i totally miss about the problem as count but that's fine because we're still trying to find a rectangle and this is a rectangle right and now that we have these sides we can now think what is the um what is the area of the triangle right oh sorry what was the area of the rectangle and then we do a min of it or something like that so we have the hard part done anyway so best is to go to minimum right so we maybe we can do uh 1g 30 or something because we want to angle um how you do the so this part we would have to do the square root but now we have to figure out the side that is uh the most accurate um so i guess coming up if you just look at and this is me just thinking off my head but if you have l i l j okay and you could draw it out for every point the longest one is going to be the one that is the diagonal so then you can just figure out the other one the two is not right so that means that um we can do something like uh maybe this is too awkward okay uh um times i k times l i l over uh the max of l i j l i k l i l right so best is equal to min or best of this if best is greater than 1 e 30 then we return 0 maybe 29 just for rounding out and this is because that we want to get rid of the max because it's the other two right um and as i messed this up this has an area of two well why do i think it's area four oh i am dumb because i actually was thinking about this but then i totally forgot about it as i was doing it but because this is um this is squared right so then now we need to square root this these numbers but that's okay we can do that um yeah okay so then now we just have a b okay fine i'm trying to think where i could do it in a clever way but um i mean i think you could just you could probably also just square with these but then the max part doesn't really make sense so now i think it still makes sense actually because then now because the square which is inside then you take it out anyway and the max of the square would be the same with max okay i mean it's very awkward looking though for sure and this is also one of those things where you know you see someone's solution and you're like what is this guy thinking like how do you even get this formula um well if it's right first we'll see maybe it's too slow is it gonna be too slow i hope not maybe if it's too slow about to use another language because i think this is super good in uh how cos am i this is going to be super good in like c plus because this is only i think the square root maybe is an issue to be honest but and you can put maybe delay the square with until later but uh i think this is trying to think better uh because we don't do that many things but i guess they're just a lot of cases because like we said 50 choose four um it's like 200 000 or something whoops what did my finger go i minimized the accent okay so 50 choose 4 is only 20 and 30 000 but maybe we do a lot of cases but this is what i was worried about with having these functions uh but this is just like tedious right so okay but let's find fine i hate this i'll try to do this first before i convert it to uh um before i convert it to uh which my card c plus or something this is way you know i'm not learning anything by this though so that's why this is sad um now maybe we could use this as a benchmark actually before i oops see if i can use this as a branch mark a little bit that seems like a big i mean it has almost 50 numbers right how much of a benchmark can it be how slow can it be 385 let's see if this actually speeds it up and we also worry about typos with stuff like this obviously where you usually don't have typos i should have also done the inner ones first just because i think the inner ones technically are executed the most right then i have just see to see if this is much faster just for purposes we got rid of half of these but they're not proportionate right so this is actually slower but i don't know maybe now i do new friends and this is still correct so i haven't made a knock on wood typo yet though this was a contest i would be pretty sad about it not gonna lie okay all right let's see if this is better i guess the worst part is that this could potentially have that many square roots this is actually slower hmm is that true or am i just like unlucky okay well in that case yeah let's change to c plus maybe it's just um let me think whether i guess we could do end cube and try to find a dirt point um yeah okay fine i think maybe but two hundred thousand is not that much i'm well to be uh like i feel like if i did java or something like it'll be faster but uh yeah i guess i knew that this could be a friend okay fine um that's so yeah this is going to be just annoyed that i thought andrew's fourth would be fast enough but this is also a thing where you know like the number of test cases matter right you have one test case this is obviously fast enough but as you can see but given a hundred test cases maybe it's a little bit too slow right hard to say okay so let's think about it again let's try to do it for n cube the idea behind the n cube algorithm is just the same idea right so given i j and k let me actually take the one that i took because if that didn't save enough then i rather have this code because it's easier to see um okay then now we can figure out the third point right so but then now we can also do it in a harder way so then we can make sure that we get the two corners to two corners right and the idea here is let me think about this for a second is the idea that i'm trying to think um okay so what do we want it to be given i j and k let's um well first of all yeah now i just took out the first one now we have to do all three but then if i is equal to j we contain you of course and yeah if i is equal to k or i or j is equal to k we continue right um you go i guess you could have also checked for this being zero but that's more expensive okay and then now the idea is that okay what do we how was the user's way given these points do i have to think still on screen because that would be actually kind of sad uh let's see okay so i am now putting this back on screen so let's see right let's say i have why is this right let's have something like this uh well actually no i don't need to diamond anymore that was just a different case whoops uh let's say i have a rectangle right and pretend that's a rectangle i can't draw and now we're given uh i j and k so that so what can we assume about this right um so here what is the assumption how do we get this l uh i guess it's just like vector math but i am very bad about it okay so i guess it doesn't so i think we're trying to find a diagonal again wow i kind of use the one brush for that one um and if we figure out which line is the diagonal so we basically okay so then to figure out the diagonal we just have to make sure that um yeah okay i think i have an idea which is that given the diet we figure out the diagonal as we said that's the longest length right okay so then now we have i j and i k um oh wait no we don't have outside oh man i am not thinking about this right so we're just given we're just coming this and this but i guess the worry is that um you know we maybe we were you know maybe this is k instead by accident right what if this is k instead then how do we rule that out and do we have to roll it out i guess not i guess we could just look for it right because what i wanted to do is basically the ij translation you can think about as a line but it's also a translation and then you we operate it on the k right so let's say we kind of copy and paste it here and then we just try to see whether this l exists and then after that we can figure out whether this is a thing by the thing that we said right um the two diagonals okay yeah let's give that a try um i think that's a possible thing so yeah okay so we don't have to we can just find the fourth point and then see if it's a rectangle so we already have all the components for this um right okay let's just keep these actually let me go back to what i had before just what i had before i deleted stuff because then i can reuse some of this per se probably possibly okay and then now what we want to do is figure out what l is right oh i meant to do the lookup i forgot to do the lookup um because i've been a little bit switching from before but um yeah why not so okay so for point in points uh tuple of point right that's fine um lookup dot add or maybe scene is better we just want to set that's what i'm trying to say oops okay so now we have uh a scene and then now we can just say okay uh given i j line add k to find l right so okay so the dx is equal to points of i um or points up j i guess technically speaking minus points of i uh yeah i was just like a hair y swing but okay and then now we can take the k and then do the translation right so l um let's just say pl for points of l maybe is equal to a point sub k of zero plus dx points of k of one plus d y right and then now we can do the things that we did before except for now instead of this we have pl and we also have to double check that pl isn't one of the i don't think that is possible but maybe we have to check whether it's you've got i j and k but i mean as long as it's not zero delta should be okay so and there are unique points right yeah all the points are unique so it should be okay and then now we have to i guess we just do this thing really so yeah so i guess we had most of it we just have to do uh an optimization on finding out i didn't even have to change that much really okay here's the wrong answer is that um what is that my answer is smaller than the expected which is not uh well also i guess i always have an answer for this one but oh i am dumb i forgot to check so of course my answers are better um so here we have to check if pl in uh not in scene we continue oh wow what a silly mistake um i mean that was the whole point of this optimization but i just forgot about it because i was focused on the other parts um so that looks okay this looks only slightly faster let me oh yeah let me run it once more but okay let's just give it a go maybe it's fast enough if it's still too slow then i'm just gonna be sad and cry maybe we have to do some optimization on the other parts but come on okay wow this is way slow uh maybe i could move this bit underneath maybe but let's see yeah so that we you know i don't know if that's the most expensive part but i'm sure it helps but that's still like so slow though huh maybe it's the square oh i guess that is so expensive look at this is what i was talking about and i think if i had the not function calls it would be much faster but i'm not going to spend time optimizing that part um cool yeah yikes this is uh you know pretty tough for an initial one so let me know what you think uh i don't know how long i'm gonna do this or how often i'm gonna do this but i'm gonna try to do it a couple of times and then see the reception so if you do like this and you want to see there's more of it more of this let me know stay good stay healthy take your mental health leave it a comment below give me some love and support i'll see you later and take care bye
|
Minimum Area Rectangle II
|
three-equal-parts
|
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**.
| null |
Array,Math
|
Hard
| null |
1,477 |
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 daughter's 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 that's pretty much it cute we find two non-overlapping cute we find two non-overlapping cute we find two non-overlapping sub-arrays each with targets um yeah so sub-arrays each with targets um yeah so sub-arrays each with targets um yeah so this one I think I spend a good amount of time just reading it as well as you kind of see here so the thing that I was trying to figure out is just well there non-overlapping point I think there non-overlapping point I think there non-overlapping point I think that's the quickest point the thing that I looked at was okay what is n can we do anything good for us well n is 10 to the fifth so you have to do something in linear or and again and then the second thing I look at is target is positive right and what that means we're talking is a positive number means that well then you could do greedy with a sliding window and that's what I did here that's what I start by doing or start doing at first I was just gonna keep track of all the lengths and then just like pick the last two but I didn't knew that I didn't need to do that but I know I mean it's just template like mental putting it there just in case I need it later but here I am Here I am doing the styling window for you to ride and you could have done this where prefect sum is the same thing but when basically your design windows as you is trying to find it in variant for targeting and basically when you process an element to the right you're gonna add that number to the current segment and then if that current segment the sum of that current segment is bigger than the target you can subtract upon the left until you it is either equal to or less than the target and you could do this because target is positive so that condition it will always hold otherwise you might have to do some dynamic programming version of it and yeah and just moving to index ears obviously because I always forget it yeah now this is the fun part and then what happens when it and there you go to target right well I was like okay let's just put this segment in there because I was by the time I typed it I was like okay get all these segments and you one two of these segments that are not overlapping and then you want the smallest version of those right so that's what I'm trying to do here by the way you're still watching this note that there's a full description at the link below so that you can or explanation the link below so definitely check that out you're impatient for whatever reason which is fine but for now I'm gonna talk about my dog process and not necessarily the solution because that for me I think it's interesting or possibly interesting maybe not maybe a fast warning kind of my dog process and here I just wanted to print out the segments just to make sure that I was okay with off by ones and stuff like that and it should it looks like I was okay so I was like okay let's jump to the next step I was trying to keep men's I was trying to be live with not clever but I don't know if it made sense now I'm trying to think you know let's say we process two segments one at a time what does that mean now it's like actually we process with one apply system from left to right so that means that I want to process the events anyway so then now this is what I cause this is what I do as a sweep line algorithm the left and then ditto courses on the right and then you do some processing sourcing on the left and the right but I actually messed this up a little bit as you will see I mean so right now I'm thinking for what are the cases have to solve it first but I really should have spent an extra minute thinking about it to be honest because I end up with two wrong answers because I wasn't really clear about how I wanted to implement it or at least two edge cases or a balloon at this point about ten minutes into the contest I was very much watching it I thought that I had to be a little bit faster though in retrospect I didn't need to but I was feeling that pressure and I and this is wrong this is just if there's no more segments we do the Delta thing I don't know why I thought this was correct but basically what we want to do is we want to handle the left end points and the wide end points in a different way but what I was thinking was like okay when the Delta zero meaning when we're no longer in any elements then maybe we can process the minimum in some interesting way and I think that the rest of the idea makes sense it's just that I don't know why I and sometimes when you want you don't know wine in retrospect but you especially these albums which are a little bit once a greedy but greedy in nature in the processing especially of sweep line it's generally gonna be really in that way but yeah but this is well somehow though unfortunately it matches to answer from the results were there a couple of things I have to do I did check that is if it's not possible then we turn negative 1 which is an infinite number but I was having off-by-one somewhere that's all mostly off-by-one somewhere that's all mostly off-by-one somewhere that's all mostly that I was checking down to and not the current which was one altogether less that never gets caught as a result when the code it looks still wrong and I was like huh and it turns out that I just sent off by one because my right I mean you've seen me effects are very quickly this is not a training it's just an off by one because I was like ah yeah my cuz I do bite - left plus one but why he's bite - left plus one but why he's bite - left plus one but why he's already exclusive so I didn't need that case because I add one afterwards for sometimes tricky to catch but I mean I knew that was the case kind of I knew that's a possibility I wasn't sure that was the only bug and that's why I'm hesitating right now and that's why we just weren't printed out just in case you know i was like a zero to one that's exclusive so we definitely need to fix that I was also thinking whether I should just put the right later but that's fine yeah so now that looks good which is unfortunate because that's why I submitted it but I still had a I don't know I think I was just not care I mean to be honest I was just really just like some of it is jet lag that's my excuse I'm sticking to it but also some of his job was just careless cuz I was washing it I really wanted to get a high school if you will and when you watch things sometimes you like I definitely could have tested this case and there was another case that I could have tested that was very much obvious which you see in a little bit spoiler alert but I want ya appreciate because I know if by one well that off by one it's just that so the first one is just this is actually just wrong it wasn't nope I won it was that based around about overlapping things but well then every bad a that overlaps a B and then B there overlaps of C see that's not processed a number in a so that was the palm that I was running into but I and yeah I don't know why I thought that would work to be honest it was one of those things but yeah you know proof by a C and now I'm like okay if the Delta is negative one meaning at the end of a segment then we can do it right and that's just kind of I test this but I should have tested more cases but like I said I was washing it I was hoping to get a good high score for my friends out there but that I click on submit before I really test some basic cases especially after one wrong answer anyone once they enter sometimes I'm okay but getting to wrong answer is me not being responsible like not being a responsible person I am responsible for it but because I was like okay this is such an obvious case when you see it - it's just obvious case when you see it - it's just obvious case when you see it - it's just and that's pretty much what I do for the next five minutes I actually resolve it did there was actually an easy way to fix this which is by it and I go over it in explanation later but which is that I had to treat the beginning segment and the end sickman differently grouches washing it I was just trying to get an answer because I knew that I was closed and I was closed but when you are I think it's just a mindset thing when you're like 95% of the way there like 95% of the way there like 95% of the way there the last 5% of the way you're like okay the last 5% of the way you're like okay the last 5% of the way you're like okay let's just do whatever works to get the last 5% but sometimes you need to make last 5% but sometimes you need to make last 5% but sometimes you need to make sure you get that last 5% and I didn't sure you get that last 5% and I didn't sure you get that last 5% and I didn't do that and that's why I got two wrong answers and it was really sad as you can kind of see me being a little bit frustrated in that regards but are ya and now I'm just thinking like can i hack this and it short answer is yes but I think I had in my mind that those two things have to be together and then I was just like okay let's reboot how I think about this problem the sliding window is correct I didn't want I didn't need to fix that port but I just need to handle the left and the right in a better way and that's what I ended up doing I'm still thinking it for like I said I was still trying to think but I wasn't really clear about it to be honest oh yeah but now I instead of trying to figure out the love segments I was like okay let's just pull each left segment we just keep track of where it begins and then we only process the left part when we get rid of it where my no longer overlaps or possibly overlaps at the current going from left to right then we can track it or we can use it so that's basically what I do here the idea is that okay once we increment left pass that then we know that we can be like okay whatever is in there it could be the min segment so let's you know put it in there and that's what I have 2 min for yeah and the way- stuff is just too sick yeah and the way- stuff is just too sick yeah and the way- stuff is just too sick minutes inside so yeah ran it no yeah forgot to I guess I could eat it yeah it looks okay I mean it looks wrong so I was like a weight that is still wrong what is going on the could open statement like I usually say when if you have to debug during a contest it's always a sad thing because you'd never want to debug it always takes way too long with this coding but sometimes when you need to yeah the short answer is that teaches enough time well yeah I said to I was putting a left into writing the same thing so it wouldn't make sense but yeah and also by this exclusive time fixed off by one so that basically you're right but put in like okay this is the segment and then when the left gets processed then we're like okay just segments actually good that's basically what this is trying to do and I was like still okay at this point I was not confident obviously after two long answers it's hard to be confident but I was like okay let's just try this and really good think it's quiet and I get any one cute boy fine to non-overlapping supper race boy fine to non-overlapping supper race boy fine to non-overlapping supper race with targets um so this one was a very tricky one for me mostly just by off-by-one errors or not by one but I off-by-one errors or not by one but I off-by-one errors or not by one but I had an idea on how to solve this and I did it two different ways by accident yeah and I spent 10 minutes debugging which is kind of unfortunate but the idea is that well the first part is just sliding windows right but and then from the sliding windows you just get you just look forward to target he goes to target the first thing to note is that targets between 1 and 10 to the 8th but the key thing from that is positive and it's not 0 so therefore by sliding when once line window processing it's good enough because you could do it good in a greedy way so that's how I did the sliding window part and then the overlapping points a little bit tricky the way that I did it and I end up just tracking the minimum I could've done this a little bit differently with like a heap or something like that and this would make this a lot space-efficient would make this a lot space-efficient would make this a lot space-efficient though time a little bit slower but the idea is that for each element if this is the left part of us so basically how I would think about this problem is you have some overlapping segments and you might have seen how I try to attack this we sell but basically you know you come in an array and then now you convert it into convert into segments that or several ways that have target you go to subject I say these are both ways you have one two three then your 1 2 and then 2 1 right so get all these overlapping arrays the thing that I was trying to do and this problem is change it to event based system where okay so every time a full segment is finished we put it into we count down as a possible candidate for the mint right and then we just keep on doing that so for example here the minutes one here the minute stupid I wait for it away because it's not mean enough here it's one again or to actually sorry and this is three because yeah it's inclusive but this is two so then here it looks it's a two elements plus the previous min which is one so that's three and here again but this one here we do not I think I had an off by one hour now that thing about it but we do not pop that yet until the Ray n until this element is processed and then now once that elements process then we can yeah we can use it so for example let's say I'm just making up examples here now but let's say you know you have something like this you know these are all overlapping segments so now you process this is the min here well here you process this but then here you don't you do not update the min yet because we do not process the right endpoint yet so we're going from left to right sweeping line so here it goes okay that's okay we started at the beginning of a segment here we begin another segment and here we end this segment though I think this you have to do this one first so it doesn't end it so here it begin a segment in here and a segment and then this week updates min here which is four or five or something like that right so it updates the min and then when we go to here it also updates the min because this segment is more than this segment but then here but that's create another segment so we could illustrate but I say we're up to here well now we can check the size of this segment times the plus the min because here we know that everything that's already updated in min already contains the minimum segment and here we just check this segment like this segment plus a previous min segment is good enough so that's what this is saying and then here that's okay we update the segment let's move this a little bit back so then here again when we get to this point we update them in again and then here we take them in from this segment and the smallest previous min segment so that's basically my algorithm here basically have a sliding window and a different frame to process for the left endpoint and right endpoints I think I should yeah I don't know why I didn't really think about it that much I think the way that I did the first time is right it's just that I was trying to merge two things at once so how I would have we done it the way that I did it was actually with the to you friends say don't this is okay to her obviously but if I had you know given a chance to do it again with the event stuff and even see that you bent away but we append the left one for increasing a segment right - left this increasing a segment right - left this increasing a segment right - left this is a and then the right so grab something like that and then now we have event start sword and then a for was it X don't we never use it Delta and segment our size in events we can do well if Delta is equal to plus one which is at the beginning of a segment well what do we do when we enter a new segment we go okay let's take two ends as equal to men and the current previous men plus the size and then if Delta is equal to negative one well then we get to update the men and that should be good enough but I and this is n log n versus off and it would have been with the other one but it's still so much Queen and so much less Emma for once you really get to understand what is trying to do I'm not going to submit it don't actually I guess I won this exam with Tess I'm not gonna submit it because the contest is still going on and I don't know what happens but I'm relatively sure this is right now that I understand a little bit better I think in the contest what happens sometimes is that for me is that you know you really want to get a high score and then you rush through things and then when you watch for things you miss it a little bit I was trying to combine these two things into one place but I didn't really like I had died dear in my head of what I like I had I knew that I had to solve this problem but I didn't really visualize this well enough to be like okay on the left hand point do this on the right endpoint do this what I did was that I just was hope was trying things out until we hoping that it was okay and that's how you get two wrong answers and I was a 10 minutes of penalty on this one where I just to bag them and really think about it I grabbed got this really and instead I did that other thing yeah but that's all I have for this forum the way that if you do it with the defense basis and lie again because you have to sort though you could maybe do a little bit clever with the way you insert things because you're going let them wait after all but of one space so that's owners I am I like the sorbent space because for each end there's yeah for you and also well it's up to our event space but yeah for you to target I guess it could be or men for you to target overall one so they'll be all n possible targets because for example you have just all the numbers are the same yeah and you can reduce this to all n as we did before for the one in time the space will be the same cool this is a really tricky problem at least for me there's really a lot of places for potential off by once especially when you try to rush it definitely when you solve this problem make sure you get it right getting it right is faster yeah faster than getting it fast but one way obvious but still you know I still make that mistake at one time two time way so yeah that is cute definitely good practice I like to farm actually to be honest even though I got two wrong answers and it's not too hard it's not too easy you just have to really think about the edge cases and how to break down a problem because there in a way you're solving two different problems in one problem and that's where the difficulty might come in
|
Find Two Non-overlapping Sub-arrays Each With Target Sum
|
product-of-the-last-k-numbers
|
You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the lengths_ of the two required sub-arrays, or return `-1` if you cannot find such two sub-arrays.
**Example 1:**
**Input:** arr = \[3,2,2,4,3\], target = 3
**Output:** 2
**Explanation:** Only two sub-arrays have sum = 3 (\[3\] and \[3\]). The sum of their lengths is 2.
**Example 2:**
**Input:** arr = \[7,3,4,7\], target = 7
**Output:** 2
**Explanation:** Although we have three non-overlapping sub-arrays of sum = 7 (\[7\], \[3,4\] and \[7\]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
**Example 3:**
**Input:** arr = \[4,3,2,6,2,3,4\], target = 6
**Output:** -1
**Explanation:** We have only one sub-array of sum = 6.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 1000`
* `1 <= target <= 108`
|
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
|
Array,Math,Design,Queue,Data Stream
|
Medium
| null |
278 |
any guys are doing this is Jay sir who started good at algorithms I'm recording these videos to prepare my interviewing smile in this video I want to take a look at two 7a which is marked as easy first bad version I'm a product manager when currently leading a team to develop a new product unfortunately the latest version of my product fails the quality check since each version is developed based on a previous version all the versions after bad version also bad suppose we have n inversions and I want to find out the first bad version which caused all the funny ones to be bad you are given an API a bad version which way return whether version is bad or not and play the function to find the first bad version actually minimize the number of calls to the API Wow actually I just a it's a fun story that I actually ran run into ran into this problem before we found a special bug on I was 5 and I know iPhone 5 I was 10 and we don't know why but before it was okay so we did one thing and choose to find the bad come in which we did a binary search we calculated time that the time where the application will run well and until now the committee where it doesn't work well so we checked the commit in the middle to see if it's good or not if it is good we could just stop checking the full previous event just to check just to continue checking in the new half right in the more recent half and do it over and over again and yeah so that's actually the solution for this one wow this is a really great experience well it's panel research yes we choose the middle if it is bad then we will check the first half if it's not we'll go check this lat second half mm-hmm so well ready when second half mm-hmm so well ready when second half mm-hmm so well ready when will it be when will it end well let's see when we end and is a integer it's a number okay so like 4 1 2 3 4 5 let's say 5 4 is bad right it's 4 is bad now first we choose 3 because this is okay right so we remove this half and this is bad so we choose a 4 this is bad so we will we move this 5 and go check these 3 4 right so actually we what we want to do is narrow like shrink is interval right I firstly start with I 5 who will just remove the possibilities remove the valid versions and at last it will just have one version left why that is the target well are sure that there will be a bad committed right cool I try to do it so this is a closure who returned the function and yeah let's create I know they just let I start the star equals 0 let's N equals n while start is smaller than and what if there are two commits it's just a left one if there are two commits because of our choose to use math.floor the left one choose to use math.floor the left one choose to use math.floor the left one will be used yeah actually like say we've three I've added then we could remove this half right and move there forward right so even if these are two numbers actually we will that the left the start will be moved to the next so for each traversal or for each round at least start will be moved one step for right okay so it's kind of not gonna be a problem let's do that while start is smaller than in well while there is well there is a enough where with it there is a number there are numbers which is the middle which is math.floor start plus n divided by two math.floor start plus n divided by two math.floor start plus n divided by two now if middle if the middle is a bad version M it'll say this is bad version then itself might be the first bad version right so we move the rest means n set to middle the middle will not you see which is four so it will not be the end when there's no problem here so else if it's valid then itself could not be the bad version right so set start plus if we set start to middle then it start might be to middle so it will be infinite loop so we actually we could use plus one here and so actually end will always be the bad commit and start well my surpass and right at the end or when there they are when they ran into this when they ran into when they are equal to each other or started speaker than in either way we could just return the end I think should work right yeah let's try to submit cool so we are accepted it's actually very simple binary search for each round we just reduce half of them numbers possible numbers so here time of course if not log in space we don't use any extra space it's constant okay so that's all for this problem hope it helps see you next time bye
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
714 |
hi guys welcome to algorithms made easy my name is khushboo and in this video we are going to see the question best time to buy and sell stock with transaction fee you are given an array prices where prices of i is the price of the given stock on the ith day and an integer fee representing the transaction fee find the maximum profit you can achieve you may complete as many transactions as you like but you need to pay the transaction fee for each transaction note that you may not engage in multiple transactions simultaneously that is you must sell the stock before you buy again so here are the examples given to us and let's see the first example wherein we are given the prices array and the fee is two so the maximum profit that can be achieved is eight by buying at one and selling it eight with a transaction fee of two that gives a profit of 5 and buying at 4 and selling at 9 that gives a profit of 5 minus 2 which gives you 3. so 5 plus 3 is 8 making the total profit as 8. so let's quickly go ahead and see how we can solve this question till now we have seen a lot of buy and sell stock questions on this channel and in those video we have already covered the concept of effective buy price that lets us calculate the profit easily by calculating the effective buy price at each and every step let's recap what we have seen in the earlier videos you can decompose the transactions into different steps for example if you are taking two transactions you will have a buy and sell of transaction one and buy and sell of transaction two and then you can also calculate the profit for each of these transactions now suppose that you are giving two coins to buy a stock and this cost price becomes c1 and now suppose you sell it at five so what you are getting back is the two from the original amount that you have invested and three as additional profit now when you want to make another transaction say buy a stock on some other day on say value 4 so what you are effectively doing is you can give all the profit that you have earned from this transaction and you can now give one unit from your own pocket so that makes this one unit as effective by price which is nothing but the actual buy price of this particular transaction minus the profit that you have earned from all the previous transactions and now if you sell this particular stock at say 6 then your profit will be the profit by subtracting the effective buy price from this sell price which gives you this y minus x minus p1 which was the effective buy price for buying this particular stock making this profit the profit from all the transactions that have occurred earlier from this particular point so that's the concept of effective buy price and how you can accumulate the profit by iterating through all the transactions and reaching to the end point where you have the profit from each and every transaction that you have made so now let's go ahead and see one of the examples and dry run this approach this is the first example that is mentioned in the question where over here we have taken a table this is the index this is the price for that particular day and we have taken two other variables which will be profit and the effective buy price initially the profit will be zero and the effective buy price will be the price of buying this stock because everything that you are giving is from your own pocket so for this example the buy price becomes one initially moving ahead the profit over here now becomes the maximum of either the profit that you have seen earlier or the profit by selling the stock at current price so for finding this current profit you will say that this is the price at which i am going to sell the stock and my effective buy price was the price that i have seen earlier minus this 2 because this is the transaction fee for making a transaction so that gives a maximum of 0 and now my effective buy price over here becomes the minimum of either the previous effective pi price or this price of i minus profit that i have seen because over here i am trying to buy at this price so the minimum of both of them is one moving on to another day we will continue the same the profit will be maximum of either the previous profit or the current profit which is selling at two my effective pi price was 1 and this transaction fee which gives a maximum of 0 and my effective buy price becomes minimum of either the previous buy price or the current buy price which is price of i minus the profit so that gives me a minimum of 1 and so we save that moving ahead we do the same for index 3 and over here the profit becomes 5 and the minimum effective buy price is still one now when you move ahead your maximum profit becomes maximum of either the previous profit or the profit by selling the stock at current price and my effective buy price now becomes minimum of either the previous buy price or buying at this particular value by paying with the profit that has occurred till now which is this five so my minimum becomes -1 at this particular minimum becomes -1 at this particular minimum becomes -1 at this particular index moving ahead we do the same and the maximum profit now becomes 8 because effective by price was -1 and i try to sell this at price was -1 and i try to sell this at price was -1 and i try to sell this at price nine which gives one more transaction making the profit as eight and my effective buy price over here still remains minus one so at the end this profit is the entire profit that we can achieve from making multiple transactions while taking into account the transaction fee that is applicable for those transactions so that was about the theory behind the question let's go ahead and code this particular approach out before going ahead with me i would suggest that you try to code it by yourself and if you get stuck you can come back and see the code that i am showing so let's take the few variables that we wanted instead of taking array over here i am just taking the two variables because what we need is just the previous value and the current value so that can be handled with the use of single variables instead of having an array and now we will go and loop over the prices array and in this we are going to update the profit and effective buy price using the formula that we saw in the video earlier so the profit becomes the maximum of either the previous profit or the profit from current transaction which is selling at price of i minus the effective buy price and minus the transaction fee and my effective buy price becomes the minimum of either the previous effective buy price or the current effective buy price wherein the current effective buy price is buying at the current price by including all the profit that i have got from the previous transactions so this is prices of i minus profit finally we just return the profit and that's it let's try to run this and it's giving a perfect result let's submit this and it got submitted the time complexity for this particular solution is o of n for the loop that we are running over here and the space complexity is o of 1 because we are only having these variables with us so this becomes our space complexity and this is the time complexity so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding you
|
Best Time to Buy and Sell Stock with Transaction Fee
|
best-time-to-buy-and-sell-stock-with-transaction-fee
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,3,2,8,4,9\], fee = 2
**Output:** 8
**Explanation:** The maximum profit can be achieved by:
- Buying at prices\[0\] = 1
- Selling at prices\[3\] = 8
- Buying at prices\[4\] = 4
- Selling at prices\[5\] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
**Example 2:**
**Input:** prices = \[1,3,7,5,10,3\], fee = 3
**Output:** 6
**Constraints:**
* `1 <= prices.length <= 5 * 104`
* `1 <= prices[i] < 5 * 104`
* `0 <= fee < 5 * 104`
|
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
|
Array,Dynamic Programming,Greedy
|
Medium
|
122
|
1 |
hello everyone and welcome to Python programming practice this video we're going to be coding up a couple different solutions to leet code number one so we're just gonna start by reading through the problem and then we will code up a couple different solutions for it so the problem is called to sum it has a difficulty level of easy so it shouldn't be too difficult or too long let's read the problem description given an array of integers return indices of the two numbers such that they add up to a specific target you may assume that each input would have exactly one solution okay you don't have to worry about doubling up or getting the wrong indices I guess and you may not use the same element twice all right that seems important as we if we're looping through something multiple times we can't use the same element at the same index twice it's giving an example here given these numbers and a target of nine because the zero index which is two and the first index seven those add up to nine which is the target we would return those two indices so you turn in X zero and one which are the two numbers that add it up to the target of nine okay so that is the problem so it's not super complicated but let's go over to the code and we could start out by making some notes here on how we're going to approach the problem now we're gonna solve this two different ways start off with we're just going to do a double for loop solution which will essentially will be looping through the list of numbers and then looping through the list of numbers a second time so we can find every single combination of additions between the numbers and that should find us the solution it is a brute force solution though which means looping through an array twice with a double for loop means it's going to be the runtime is going to be N squared Oh of N squared which means say if we have an input list of length 100 we will end up doing 10,000 operations with the end up doing 10,000 operations with the end up doing 10,000 operations with the double for loop that's something that's generally better avoided if you can manage it but and for our second solution we're going to use a dictionary to make some to store numbers that we see and that should allow us to only have to loop through the numbers once so that will allow us to have a runtime of only O of n instead of N squared so this is the general plan here let's take our notes away and think about how we would start coding up the first solution here so basically we need to loop through the data or the number let's see here so are given the starting code here where we have an input list of numbers and a target and we need to output a list of integers which are the two indices that add up to the target or store the numbers to add up to the target so with for the double for loop solution we want to start by looping through the numbers we probably want to loop through by indices because that's what we're returning so we could say for I which is index in range of the numbers the length of the list and we don't we're gonna loop through twice but we don't want to duplicate anything if we remember from the problem description we couldn't use the same element twice which means we want to avoid having the same index in our hands at the same time so we'll set up the loop so that the first loop will go through everything other than the last element and then the second loop will start from I or where the first loop is or I plus one I guess and then only look at things from that index till the end so it will allow us to avoid looking at the same index at the same time and it will cut down somewhat on the total amount of run time it's still on the order of N squared but it will be a little bit better so we want to loop through all of the numbers except the last one and then we're gonna do another loop for the other index in a range from where our current index is I you know we don't need to look at ones that we've already seen so we'll start at I plus 1 which is the next index over the array and then we'll go to the end of the numbers so go all the way to the end of length numbers and then here's the code that has to check whether the sum of these two numbers is equal to the target so if the number at index I plus the number at index J which are different because we set up the loops that way is equal to our target input we should return a list that is the two indices right so I and J so this should be a working double for loop solution it's not going to be the most efficient but I'm going to click Submit here it's saying pending my cutoff for the video but it is judging right now and then I can pull over okay so the solution says it's it passed successfully the runtime unsurprisingly was pretty slow so about 6,000 was pretty slow so about 6,000 was pretty slow so about 6,000 milliseconds and it was only faster than 6% of other Python 3 solutions so it was 6% of other Python 3 solutions so it was 6% of other Python 3 solutions so it was pretty slow but we knew that going in alright so now let's go back and try coding up a more efficient solution so this time we are going to use a dictionary and we're going to store the indices and values that we've already seen and we can use those stored values to look up and see whether our current value plus anything that's stored will equal the target and if it does we can just immediately return what those indices are and that should allow us to go through the number array only once to find the solution but we will have to have a little bit more memory usage because we're gonna have to store some numbers but see how we do this well first we need to define just an empty dictionary to store things in so we'll say scene which is the numbers that we've seen so far and now we're gonna have to loop through the numbers again so well maybe use enumerate this time because we want the index but also the number and we don't need to stop like at any specific point like we did with the first example we just want to do all the numbers all at once so we'll just go through everything for index and numb in enumerate nums so enumerate gets you both the index and the value at the same time so I is the index num is the value and then first we need to check whether the dictionary seen contains the number we'd need to add to our current number that makes it equal the target so the number we'd have to add to the current number you get the target would be the target minus the current number so if the target minus the current number is in the seen dictionary then we can exit and return the two indices so let's see here but the second index is just going to be I because that's what we're looking at but the first index would be the one we already stored in seen but means we're going to return the value of the seen dictionary where the key is equal to this number that we looked up and that will give us the index we're gonna have to store that in our else clause so we're gonna want to list that we have to return the first element is going to be the value in the seen dictionary associated with this number and the second index is just I and then if the target - our current number is if the target - our current number is if the target - our current number is not in the scene dictionary we need to store the current number and index in scene at least if it's a number that we haven't seen before so else if our current number is not in scene so we've never seen our current number before we will store it so seen our current number and this is equals this index so this should loop through every number if that number plus something that's we've seen before equals the target then we just return it the two indices that made that true and if not then we have to store what we're currently looking at in scene but we're only storing it if it doesn't already exist in scene I don't know if the problem definition specified whether you can have repeated terms in it like in theory that would be possible but we don't need to store the same values more than once like if they're giving us an array that has several Breeze in it or something we wouldn't need to store that more than once so let's submit this one as well and see how we do sure how fats is gonna be compared to other solutions because this website from run to run sometimes you get pretty different values for your solution speed but it should certainly be better than the row of N squared solution that we submitted earlier so let's check on that all right it looks like it ran in 48 milliseconds this time which was a lot faster I think the first one was around 6000 and it's saying it was about in the 95th percentile of speed for the Python 3 submission so that seems pretty good and the memory usage isn't really too much different than before and it's actually still less than over half of the submission so that doesn't seem too bad now of course there are many different ways you could probably solve this problem this might not be the most efficient method but it got the job done and seemed to be faster than most of the submissions that have been sent in so seems like a reasonably good solution for that first easy problem on leaked code so keep coding and I'll see you again next time
|
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
|
191 |
hello guys hope all you are doing good so today i am going to discuss this question it got 191 number of one bits i'm going to solve this in two languages which is one of uh i mean one is c plus and another is java so let me first do it in java i'm not going to implement this by uh my own there are some built-in functions in the language some built-in functions in the language some built-in functions in the language so that length that function is i'm going to implement in order to solve the question so in java we know that there is a function called two binary string so let's if i just say that ah i don't need it though i need to convert binary form let's be just let's say return integer dot bit count break give me the result so it is giving me the result so let's submit this and as you can see that this is extremely faster so same code i am going to implement in c plus let's see i'm not going to write it though because it is already written so let me show the execution of this code you can use this function double underscore built in underscore pop count of n so this is the code for c plus and this is the code for java so you can take screenshot of this it will submit the c plus code and as you can see that this is also extremely faster so guys you can use these functions uh when you are implementing and you are solving a very large problem and there you can't actually write a proper function your own user defined function because of uh time constraint so there you can implement and then you can write these functions in order to find the popcorn thank you
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
152 |
hello friends this is shravan kumar mantri technical trainer welcome to my channel csc gurus in the series of video lectures i want to explain some of lead code problems which are mostly asked in top level companies and here i want to explain them clearly hope it works well for you so the first one i have taken the maximum product sub array so mostly disaster the concept in facebook amazon and google so this is a problem this is lit code the number 152. and of course it is given it as a medium right now so we'll see what is this problem and how to solve this one what is a like name approach how it will be and what is the best one approach so all those things we'll see now so the problem is given here like this given an integer array of nums find the continuous sub array within an array that is containing of course at least one number which has a largest product so what is this question we'll see first so let us take the input so here it is an array of elements you have to find the largest product where you will get it is it might be with only one element it might be with the two elements it might be with three element might be so it can be anything but it should be a continuous sub array okay so let us see for this example how it works so first i'll take two what is this product okay if i take only two next two into three can i take yeah the value is six next let us suppose if i take two into three into minus two so what is the value it is minus 12 now you can see so when a negative value comes so the value where first it has increased but now it is decreased going down okay so might be if i take 4 okay so if i take 4 what will be 12 into 448 again it is in decreasing so it is asking like not only this you can take another sub array like 3 and 3 into 2 3 into minus 2 which is minus 6 and 3 into minus 2 into 4 so that is also one more right yeah like this 3 into minus 2 that is minus 6 that is over 3 into minus 2 into 4 which is minus 24 okay might be you can take minus 2 and x minus 2 into 4 which is minus 8 right now you can take the last element 4 right so like this you may have all the values in this what is a maximum product that you can get it okay so the answer will be definitely that six is a maximum value so can you take like two into minus two no which is not a continuous sub array right it's a subsequence it's not a sub array so there is a clear difference between sub array and subsequence anyway i'll let you know that in the next video so where i'll go for some common subsequence okay yeah so there is a clear difference you cannot take here 2 into mine 4 which is also not a sub array so you cannot take 3 into 4 you cannot take what you called as 3 into 4 also is that right so the continuous sub area ok so that is what here it is asking where you will get it so what is the approach and here you may have positive values negative values of course you can have 0 also okay so here the answer is 6 and which is what is the sub array 2 comma 3 of course in the lead code it is asked only for largest product here we will see not only the largest product we will see the range also we have to find that range how to do this one that also will see here okay how to do that one how simply we can do we will see and of course this example you can see minus 2 0 minus 1 what is the minimum you can get it minus 2 into 0 which is 0 minus 2 into 0 into minus 1 0 of course minus 2 also to be taken right so 0 separately 0 into minus 1 0 next i'll take minus 1 separately so what is the maximum value 0 only right yeah like this we can have so how we need to solve this one what are the approaches we have and what is the best approach that can be taken so that is what we will see here okay anyway i highlight here uh highlighted here dynamic programming of course the best approach we'll see that one on that one here now of course here uh in this example also you can see what is the maximum product you can get it you can solve it i think you will get the answer as 240 you can solve it anyway we will clearly solve this part okay yeah 2 into 3 okay we'll get time 2 into 3 into minus 4. so anyway how it can be done anyway i'll show you i'll explain everything but uh remember how what is the value you can get it from this okay and of course so why i have given like this means whenever if you if i say product in between somewhere you find 0 means what happens you cannot get the continuous sub array if there is in between a 0 that means let us suppose 2 into 3 you can take but 2 into 3 into 0 so that means if you find something 0 that means your sub array should again the largest value in order to get again you have to start with the here element after zero right so zero is something like a disconnection okay zero is something like this connection so what i mean to say is you cannot get from three zero five as a sub array right so never you will include 0 in between or anywhere in the sub array in order to get the maximum value unless until 0 is the maximum value right so that is what here and anyway we will see what happens how we can solve everything we'll say so the general approach name approach what is that anyway i have done it here simply are taking all the sub arrays all the servers let us suppose four elements are there so first you will get fours four here next three here index two next one so what is the maximum value you have to get it right so what is the time complexity for this one anyway there are four elements means uh in n into n minus 1 by 2 right so that is which is a complexity that means n square sub arrays you will get and in that n square sub arrays for each one you have to find but each one you have to get the product uh again n so totally big o of n cube initially you will get anyway further modification you will reduce it into big o of n square somewhere like instead of every time going to the maximum value you can reduce instead of writing three for loops you can get it by two for loops also that is not a big deal okay right yeah so there is a one we have done it so traversing the array uh two times or more than two times so that you will get n cube or n square complexity so is there any way of going with n complexity so can you get the answer with big o of n complexity so definitely the answer is yes by using the dynamic programming method so we'll see how we can get the answer with this dynamic programming that means we go off and indirectly i can say that i can traverse each element only once not more than that yes so how to get it and what are the steps everything we'll see now so this maximum product sub array in the sub array using dynamic programming anyway i have taken this example you know to make you understand better so where i have taken positive values negative values of course zero also okay yeah so there we can find there are three possibilities basically so you can see there are three possibilities of getting the maximum product the first thing is either element only one element itself sometimes you may get here something value like 5000 so even if you product if you get the product of these five you cannot get the 5000 right so only one element sometimes only one element gives the maximum that is also you can take in the question itself it is given right at least one element you can see here it's containing at least one l one number that is also an answer right so now that is a one thing we can take might be the chances maximum positive so far so that means when you are traversing if all the elements are positive you are getting that means always the sequence is increasing right see 2 is a positive 3 is also positive 2 into 3 6 increasing let us suppose here is let us suppose here it is plus 4 6 into 4 24 increasing right so maximum positive so far into present element so that is a one way of getting the value which is largest but what if i get negative okay let us suppose 2 into 3 is 6 into minus 4 which is minus 24 so you are not getting up the solution you are getting down that means the value going down but this is also very important to store why because after minus 24 let us suppose if i get minus 2 what is this value is it minus 48 plus 48 again you are going up right so there is a need of storing if there is a negative value also so that's my maximum negative so far so this is also very most important part which we can consider right hope you are able to understand this one so that is one why we need to get the negative values in your array if you get odd number of negative values you may go in going down the value but if you get even number of negative values again you can go up to the values right so this is what anyway so whatever the example i have taken i will explain step by step here and i will take this indices from 0 up till here 6 okay yeah i've written an algorithm here you can see i'm showing here yeah steps i'm showing okay so by default step that is if n is 0 no elements return 0 directly ok now here i am taking 5 variables you can see the one which is maximum positive maximum negative result choice one and choice two okay i'll show you everything why these things are very most important maximum positive maximum negative and the result which you want to store choice one and choice two and not only this i'll take one more element uh let us suppose it is something like uh end okay something like n is a variable okay which i also i'll take here okay i'll tell you why we have to take this end variable here i have not written we'll take this one okay we will let you i will let you know why this is required now we'll start from initial initialize max positive max negative result all or with a of 0 what is a of 0 let us suppose it is an array a 2 so max negative is 2 result is also 2. so always this result after taking always this result returns the maximum value maximum product you will get so far so that result you will get from in the variable result okay you can't get every time maximum positive that is a maximum product value here okay yeah now we can see i starts from 1 it's not from 0 so taking the second element 3 which is a positive element you can see ch1 which is a choice 1 which is equals to maximum positive 2 into 3 which is 6 of course ch2 maximum negative is also same so 6 here also 6 right yeah now what is maximum positive so this is a value which you can get the maximum of three variables what are those three choice one choice two and current element what is the current element three so what is the maximum of these three six what is the maximum value six so update this one as the maximum value that means my what is the maximum positive you will get so far now what is the maximum negative that is a minimum that is minimum of these three choices choice one choice two and current element what is the minimum value three right so i'll write here 3 now result is now you will get it as what is the maximum product till now what is the maximum product engine in our view 2 into 3 which is 6 we need to get you can see max result comma max positive so what is the result 2 maximum positive is 6 2 comma 6 what is the maximum 6 right yeah and one more thing here i have written and write so whenever you update result you just store that what is that index value whenever you update only when you update then store what is the index now you are updating results so index is one okay so i am storing this end equals to 1 here now the next one so next element is minus 4 you can see choice 1 equals to maximum positive is 6 into minus 4 which is minus 24 right so choice one is minus 24 and choice two maximum negative three into minus four which is minus two l now the thing is max positive i need to get from the three choices what are those choice one choice two and current element is minus four minus twenty four minus twelve what is the maximum value i am talking about it is minus 4 okay and maximum negative which is minimum value minus 4 minus 24 minus 12 which is minimum is minus 24 right so now you can observe that maximum positive you got it as -4 so i told you like you cannot -4 so i told you like you cannot -4 so i told you like you cannot get what is the maximum value in the entire in the max positive you only are getting in result okay you can see result equals to maximum of result comma max pass 2 what is the result 6 what is the max positive 4 minus 4 so what is a maximum 6 only it's not updating right so i don't want to update end okay yeah and this is what i'm saying max positive means when you get a negative value your max positive is not able to store the exact positive value till no but anyway you are storing this one maybe afterwards you will get it i told you know might be you may get some negative value like this now the things next taking the next element 5 okay so choice 1 equals to max positive is minus 4 into the current element 5 which is minus 20 and max 92 minus 24 into 5 which is minus 120 now what is max positive maximum of these three current element choice one choice to what is the maximum value these two are negative and this is a positive that's why positive value only i'll have to take right maximum and now maximum negative minimum value 5 comma minus 1 20 comma minus 120 definitely it is minus 120 see this minus 120 is very most important why because if suppose there is a negative element then it will become positive which might be a maximum value right so that is what that's why i have taken this one now the thing is result equals to what is the maximum 5 and now it is 6. which is a maximum six only it is not updating so don't update end so now the next one next element is minus two now you can see minus two means max ch1 equals to max positive is 5 into minus 2 which is minus 10 right minus 10 and choice 2 minus that is max negative is minus 120 into minus 2 which is what is the value 240 plus 240 right minus 120 into minus 2 which is plus 240 so that is choice 2. now what is maximum positive will be maximum of these three a of 5 that is choice 1 choice 2 which is so current element is minus 2 here minus 10 here 240 what is the maximum 240 see now you can see max positive got we have 240 so this is what happens so 240 and what is the maximum negative minimum of these three minus 2 minus 10 to 40 so definitely it is minus 10 right like this now the next element 0 so here very most important you can see what happens when you get it as 0 and one more thing we got we forgot to take result equals to max of result comma max positive what is the result 6 what is the max positive 240 so what is the maximum value 240 so now you update so end also you have to update why because result is updated what is in what is the index of this one right now four so update it as 4 end value is 4 now the next value is 0 you can see what happens for 0 choice 1 equals to max 1 max positive 240 into a 0 so it will become 0 choice 2 ch 2 max negative that is -10 into 0 which is 0 that is -10 into 0 which is 0 that is -10 into 0 which is 0 right now max positive what is max plus 2 so maximum of current element 0 so entirely 0 and max negative also minimum of 0 entirely 0. now you can see all the values are zeros here okay except result of course the result is maximum of result comma max positive what is result 240 max positive is zero so 240 as it is and don't update 4. see when you get 0 i told you like so complete disconnection you will get in the range so that means you may find a new sub array so there is no connection with the previous you may find or till now whatever the maximum product if you get so that if that is a large compared to the next then you may get the previous one only so like this so zero means complete disconnection you can see choice one is zero choice is zero max positive is zero max negative is zero okay now the last element 50 so you can see what happens choice one of course zero that is zero into fifty zero and choice to zero i mean into 0 and now what is max positive a of my current element is 50 0 comma 0 so max positive will be changed as 50 and max negative is what minimum value 50 0 minimum value 0 as it is right and result will be max positive 50 and 240 so which is a maximum 240 unchanged so don't change this one also right so now the answer is 4 and let us suppose if i have here instead of 50 if i have 250 what happens you can see here it will be 250 and result equals to 240 comma 250. now you will get here as answer is 250 which is with the only one element that is a maximum product that means instead of these entire this one only one element gives the maximum value so here we have 50 so maximum of 240 comma 50 which is 240 only so i'm taking this one so that's it over so this is what we can consider let us suppose if you get one more element here okay let us suppose here one more element which is 200 you can update like 200 here so first what happens here you can see choice one which is you can take here as the value so like this it happens okay maybe you can get some more element you can check it out if that element comes again you can go for it and might be your result value will be changed so like this we need to proceed this is the problem and you can observe here and each and every element i am traversing only once so that's why the complexity is only big o of n so that's what so that's why this is a problem where you can answer by easily with the less complexity that is big of n and one more thing of course till now this is fine finding the maximum product okay i just enhanced this problem to get the next value that is what is that range of course i know what is the result 240 we know that the result is 240 how we are getting the 240 that is 2 into 3 into minus 4 into 5 into minus 2 which is 240 right so now we have to know from which index to which index anyway it is a continuous sub array right so our answer should be 0 to the index 4 right so this we need to get as an answer how to get the answer now so now we will use this end variable so i asked to store it right so this end variable so how to do this one means so you check it out what is the last end value you are getting 4 so that means so let us suppose i'll write here start and end so anyway whatever the end value are getting that is the index of the ending that is a sub array range ending value index is 4 here right now how to get the starting so very simple what you need to do is just go to what is a of that ending okay you have some value what is the value minus 2 okay so now you have a formula that what is the result you got result by a of i so what is i which is starting with end and every time it will decrease you can see what is the result 240 you got it by minus 2 so you will get the answer as minus 120 you have to divide like this until you will get the answer as 1 so minus 120 divided by what is the next value 5 so 5 means minus 24 okay so next again you divide so minus 24 by 4 so which is your minus 6 now minus 6 divided by sorry yeah it is minus 4 right so you will get here as plus 6 so 6 divided by 3 which is 2 divided by 2 which is 1 so what is the last value that you have taken this one that index is 0 so that means the starting with 0 up till end so the maximum product is equals to 240 that you can get it by index 0 up till 4 so this is what i think this code you can write it easily okay in any language right whenever you are getting maximum value there you have to include a variable that is end variable where you can get and from that after getting the final maximum product you can go in reverse until you will get the answer as 1 you have to divide it so that you will get the answer as that is range also so in this problem i explained about what is the maximum product sub array you have to find and also the range also so like this we need to get it and we will see the next problem in the next video lecture and moreover uh if you want to be perfect in cmcqs you can follow this video and 100 mcqs you can find it and very most important and not only this is also very most important you can find in my channel in the description also in this video thank you you
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
908 |
oh welcome guys so nine hundred eight okay nine zero eight yeah so given array of integer uh for each individual ai you can choose x uh this s belongs to minus k and s to a after this process we have some array b i reason smallest possible difference between maximum value and the minimum value of b uh so it is one k zero so you see okay is zero right so there's no choice the only choice x is zero so when you edit the maximum medium and still be zero right so you just output zero and then for two you can add a plus two right you get approximately two twelve as a minimum uh and if you add minus two you get the minus two eight uh so the problem for this one is that you need to find the maximum value so maximum value is uh the smallest possible right so the maximum should be us uh as small as possible so maximum should choose eight to choose eight and the minimum should choose two so minimum should be largest so a minus 6 can be a minus 2 can be 6 so 6 is the smallest okay so from this and you can see from this point of view you know that what you know that maximum should be choose to be as small as possible so uh this is very easy we just choose maximum minus k right maximum to maximum you choose the smallest as possible uh whereas the minimum should choose the largest as possible right so many measures at k so uh this is just the answer right maximum minus k maximum should be because we want the difference to be smallest right so the maximum should be uh small and the max minimum should be largest as possible okay that's it yeah so just uh simple mathematics and once you understand this problem you can solve it immediately yeah so okay uh yeah so i previous i just write just combine this to be this yeah so this is very similar yeah that's it okay and i will see you guys in the next videos and uh be sure to uh subscribe to my channel thanks
|
Smallest Range I
|
middle-of-the-linked-list
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 0
**Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104`
| null |
Linked List,Two Pointers
|
Easy
|
2216,2236
|
1,903 |
welcome back for another video we are going to do analytical question the question is largest odd number in string you are given a string noun representing a large integer return the largest valued odd integer as a string that is a noun empty substring of noun or a empty string if no odd integer exists a substring is a contiguous sequence of characters within a string example one 9 is 5 2 the output is 5 explanation the only now empty substrings are 5 2 and 5 2 5 is the only odd number example 2 9 is 4 2 0 6 the output is an empty string explanation there are no odd numbers in 4 2 0 6. example 3 9 is 3 5 4 2 7 the output is 3 5 4 2 7 explanation 3 5 4 2 7 is already a odd number let's work for the code we iterate the characters of string y to left if the current digit at index i is odd the substring of the largest odd number must start from index i to i plus 1 if there is no odd digit in string none return a empty string time complexity is on space complexity is o1 the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
|
Largest Odd Number in String
|
design-most-recently-used-queue
|
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros.
|
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
|
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
|
Medium
|
146
|
116 |
hey everybody this is larry this is day 29 three days left of the december league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm populating nick's right pointers in each node okay so you're given a perfect binary tree where all leaves are on the same level okay probably each next pointer to point to his next right note okay hmm that's interesting i am curious how i want to do it you may only use constant extra space um i know that's a follow-up but that's interesting uh do follow-up but that's interesting uh do follow-up but that's interesting uh do because okay that's kind of dubious uh they kind of contradict i mean i know that they don't count it but like yeah why don't you just say salvador recursively or something you know like because it does used to uh stack space right so is extra space anyways there's a little bit awkward um okay um let's see how would i mean there are a couple of ways you can do it with like you know uh what's it called level first search or whatever it's called huh but i just call it breakfast search right and then you can do it that way um but i think that's the way that i would do it but of course it would take off and extra space um and of course that is not recursive even though i don't you know this is a crappy condition because it's kind of weird um uh how would i do it recursively let me think about that for a second huh that's curious but i mean the left and the right i guess that part is pretty straightforward but then hang the right oh okay that's not so bad i guess depending how you want to do it um because basically for each i would imagine that for each note you just return the right most of that level and then the other side you return like the left most or something like that and then propagate them up and then uh merge them that way um yeah because you just want the right most of the left and the left most of the right but i don't know that's really awkward though uh i mean i guess that's fine but i'm not gonna do it that way because i don't think like this i mean it's just a weird restriction of uh if you ask me in the sense that i always count extra implicit stack space s6 as uh extra space because you don't get it for free for sure right so it's a little bit or maybe a lot awkward uh for that reason okay so i'm gonna do it my first search uh feel free to do it with whichever way this is supposed to be medium problem but to be honest uh maybe when it was written it was a medium problem but now definitely a little bit on the easier side maybe not like a yeezy easy but something that requires a little bit of practice and after a little bit of practice i think like everyone should be able to get this in a sense that like if you want to be interview ready um it is definitely on like below the bar right like you have to be uh not only knowing by first search but knowing how to apply breakfast certain other scenarios uh more complicated scenarios even right so yeah um in a couple of ways you could write this you can write this in like a level first search way as well um i don't actually um uh i don't actually do it that way but um but yeah uh yeah i'm just thinking i'm thinking whether i can um is there not any other way i guess that's really it um yeah okay i think that's what i'm going to do for now so yeah let's go so then here uh we'll start with a queue i was just thinking whether ring and then here yeah and then we enqueue the root and then now while length of q is greater than zero um current is you go to q dot pop left uh we want to say um let's actually also add in a parameter to make it slightly easier which is to like just like the level here so then now we can have current node let's go node and level um and then the front of the node the front of the queue is going to be the next node so we can just throw if no of level is to go to queued dot front that's not a thing uh something like this uh then know that next is you go to q dot zero and then that's pretty much it and then we um and then we append the next two right so yeah um so that's node.left so that's node.left so that's node.left level plus one and then no that way level plus one and i think that should be good uh do we return anything or is it just uh it doesn't actually tell you even though in the definition it seems like you should return something so i'm just going to return the root maybe that's right i don't know it doesn't really say right unless i'm missing something here uh what none not oh okay yeah because here it goes into none so i forgot to check if no dot left is not none so technically this is a complete tree so um so yeah i don't know what the thing is uh i don't get it isn't the root just to root they don't tell you what to return so it's a little bit awkward like do we turn the root do you return nothing nope so you do return the root i guess but why is it uh given an issue i don't even touch the root right hmm this isn't the typo is it i didn't change anything this is very awkward to be honest this is not a an error that is on my note but honestly don't know what to do about this one to be honest oh is this none is that why okay um i guess i should have just done something like eh not gonna lie i don't know what this ever uh is referring to because none of this is in my code is in the thing and they don't really tell you exactly what to return unless i miss understanding it and i don't really change root right like this is literally what they give us um like i don't change it so i might change stuff in it but i don't change to wherever right so this should be the same type huh so that works that is very awkward isn't it huh and i know nothing like drawing snow or something okay so this is still that's also weird though right because hmm now i guess this is okay but when i do this it's no good because is it because of stuff like this oh i see i did my it is a malaria mistake though it's the way awkward um i guess this is one of those uh problems with um yeah that's my mistake uh this is actually one of those problems with python is the type uh the lack of type safety because now node.next could point at anything um now node.next could point at anything um now node.next could point at anything um and even though i had a different type which is a tuple um it still kind of was good uh for that reason whoopsy daisies uh but yeah let's uh let's try a couple more keeping in mind that it has to be okay this is it because it has to be a complete power of two minus one or something right so uh okay let's give it a submit man what a typo but uh okay that looks good 638 days down done consistent is key apparently um yeah so this is gonna be linear time linear space uh every node gets put in the queue once every node gets popped up to q1 so that's all one time and well one space for each node um so yeah i mean i don't think you can do any better uh except for maybe with recursion where you use magically do not count the stack space uh but yeah though is much more confusing i think if you ask me but i wonder if you could play around with this idea of looking at one note i don't know anyway that's all i have i think let me know what you think hit the like button hit the subscribe button join my discord i'll see you later uh hope this week has been going well for you uh almost the end of the year so let's make it count let's get those final days in get those final reps in i'll see you later stay good stay healthy take our mental health see you later bye
|
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
|
812 |
uh so somebody gave you a set of points and you try to output the what are you trying to try to return and we have largest triangle okay so basically you need to choose three points and uh give you the triangle give you a try uh the area of triangle okay so the key point is that you need to know the formula of this so basically you have three points i call it pqr so this is p naught p1 this is basically the point okay so this is your sub uh lymphedema not g of one of naught of one of zero okay so you need to compute every of these okay so you can let this use vector a this is vector b so area just the vector a cross vector b and add an absolute value okay uh actually okay so i guess everyone knows how to compute this all right but let me still write down zero minus p of zero and of one minus p of one this is zero and it will be just q of zero must be zero q of y minus p one this is zero and then you just compute this one okay so the number is half uh r zero minus p of zero q of one minus p of one okay and uh minus r one minus p of one times q of zero minus p of zero okay so uh okay this is the answer okay now you can just expand it out okay also when we write the code uh what we like to do we just it's just we take a 0.5 and add these points we take a 0.5 and add these points we take a 0.5 and add these points that's basically when you expand you will see there are four times three men so someone gave you three points you define a function which calculate this area and then you return all the combination to three and uh take the mix take it into a triangle and compute the area okay so this is very straightforward basically this is the peripheral search somebody gives you three points then you can go area somebody gives you three points and you can go area and then you choose the largest one okay so this is the answer and uh okay think it's not very difficult question but uh unfortunately there's nothing uh nothing trick about what we can do so i guess this is why there may be yeah i mean i should add it not like okay so i will see you guys in the next interesting because something session and then be sure to subscribe to my channel
|
Largest Triangle Area
|
rotate-string
|
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\]
**Output:** 2.00000
**Explanation:** The five points are shown in the above figure. The red triangle is the largest.
**Example 2:**
**Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\]
**Output:** 0.50000
**Constraints:**
* `3 <= points.length <= 50`
* `-50 <= xi, yi <= 50`
* All the given points are **unique**.
| null |
String,String Matching
|
Easy
| null |
629 |
hey everybody this is Larry this is day 27 of the leco d challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm ah we got a hard one yay 629k inverse pairs away um so I was going to say that uh I was saving this for a hard one but I am a little bit lazy and tired today so uh but what I was going to say is I got another package from lead code and I'll do it unwrapping or un unboxing I'll do it tomorrow or something uh today I a couple of y'all ask me um uh what is my squad routine and right now I don't really have I mean I have one but it's just linear progress up uh as you some of you might know I've been Trav or I was traveling in Taiwan in Japan in for like three months and as a result uh my games were gone so now I'm just kind of slowly working up my workload um like you know 5 pounds um uh five pounds of workout and then kind of try to get to figure out where I pateau and then I will probably just do like a 531 or something like that uh both and on my uh on my bench as well but yeah so just a quick update for those of you who are asking me about my workout and today I just worked out a lot so I'm kind of spend like four hours in the gym a lot of it is like warm up and cool down cuz I'm getting old and just kind of need the flexibility not just the strength uh and I also even did like an hour uh cardio um so yeah so I'm very tired what I'm going to say um man I am not um I think one thing to say is that when you get up there uh my intensity is still pretty good but the recovery is definitely not as good so uh so yeah uh tomorrow is a rest day though so we'll see anyway all right sorry for the long intro hopefully either you skipped it or you know fast forward a little bit or you know you're just hanging out uh but let's take a look at today's problem 629 K inverse pairs away it's a hard problem all right let's dig into it for an integer array nums and inverse pair is a pair of integers i j with uh okay I is less than J less than n and nums of I is greater than J given two integers n and K return the number of different arrays consisting of 1 to n such that they are exactly K inverse pairs since answer can be huge we turn something mod so let's do the mod song mod um I think the thing to uh kind of first thing to notice about these things is just look at the constraints and here we see that N is a th K is a thousand so we I mean you know off my mind um I don't you know I don't have an idea yet but I the idea is that n * K is okay uh but I the idea is that n * K is okay uh but I the idea is that n * K is okay uh end times K is okay kind of sounds like a lime somewhere those are some bars there not a good bar but you know anyway um yeah and then the other thing is try to figure out how to you know uh like for dynamic programming problems for um uh memorization problems the first thing that I'm going to try to do and my hair is like really funky today I have like a crazy hat here but uh yeah it's trying to figure out how to do Bo force in a slightly smaller way right so they're K numbers or sorry n numbers right so that means that um know there's going to be n factorial things uh you know permutation things so we will see um H right and I think the idea here is that okay so the way that I like to think about some of these PS as well um even if I kind of have the idea I like to play around with small numbers to kind of play around with just like the combination right obviously n factorial is going to be too slow I don't know if I kind of went over it but basically okay you start with inserting one and then you start inserting two and the two you have two choices you have be before one or after one and if it's before one then you have um you know K goes down by one or something right um and of course if two is behind then K does not go down and then the next one is going to be um uh three right and three you have three choices you have either here or here right and I'm right and what does that mean practically right well if three is here that means that the two inverse Pairs and here means that there's one inverse pair or one added inverse pair and here there's no inverse pair right so I think from here that's basically where I start getting a pattern also for disclosure is that I kind of did this all in my head already but I just want to demonstrate this right so uh sometimes with enough practice and I don't know when I was younger probably I'm able to keep more things in my head but nowadays I'm just old and tired and you know but yeah before that means that basically the idea here and I know that choose one 2 three but you want choose 3 2 1 right but here you have for every number that you insert you can choose either here so this is K minus 3 this is K minus 2 Kus one or k minus Z right so that means that for every number that we insert no matter where we have that kind of freedom right so here is K minus 4 dot right so I mean so this complex is not going to work but we can at least um what I want to do is at least write it out so we have an idea on how to um uh how it would look like right and I you know we'll go over it in a sec but like for example maybe just count we have n we have K or um yeah or maybe like current n or something some and then K left just to be a little bit clear and then here um so as we said so if current is equal to n that means that we already finished so we have one possibility well actually that's not true so if K left is equal to zero then we have one possibility otherwise we return zero right and then here so um let's say that well I mean we can also count from 0 to um n minus one because I don't know I like zero index things even though technically you know but yeah so it's zero then you have zero degree of um k um you can't choose any K right but if the number is one meaning the second number then you could choose one or two so then here we can subtract up to current to K left right and of course we can prove Force this or like just iterate for it by saying for I in range up to the current plus one to be inclusive yeah um you maybe we have a total count right and then here we total we add count um well current + one but K left minus I um well current + one but K left minus I um well current + one but K left minus I right and of course you may want to mod this just you know keep everything within the same domain and in theory this is well this is uh a thing right Big K I don't like small K oops right so in theory this is you know this is a this will give you a solution right but let's look a look at the complexity so current oops is going to be zero to n right K can also be I mean it or k left is technically zero to K but keeping in mind that K can go up to a thousand so it's kind of sketch but then now each one so what is the time complexity right time complexity is equal to um number of inputs times time per input right you could do um unit analysis if you like and here number of input is going to be all of n * K and time per input however it's going to be all up to K right cuz this goes up to K left or sorry current which I guess goes up to n okay so maybe I'm wrong uh I let's just say it says n or K I don't even know I guess actually I think one thing that we probably could have done is if uh if K left minus I is greater than zero then we do this so I guess you know whatever right but uh but I know way either way the total time is going to be all of times time and o of n * K * K which is for n is equal to th000 * K * K which is for n is equal to th000 * K * K which is for n is equal to th000 K is equal th000 is going to be too slow even if you memorize it obviously we haven't even done the memorization yet right so then the idea is how do we um yeah how do we figure out how to you know now we have a dynamic programming a memorization problem that is too slow to for Bo Force oh no I'm doing the Home Alone face but uh yeah okay so then and it is in a way back to drawing but this gives us a visualization and at the way least if nothing else to be honest it give us it gives us a checker right meaning that let's say we write another solution that we make some optimization here I'm relatively I mean you know this part may take practice but for me I'm relatively sure that this is um correct I mean maybe there's an RI one somewhere but then like or you know whatever but for the most part for Mo uh most things this will be correct uh just that is too slow so we can use this to um check our other answer when we get it for smaller end and smaller ends and smaller KS so that we can verify our optimizations are correct so how do we um you know optimize this well how do we get this to work really I think that's the biggest problem right so then now let's go back a little bit to our uh fun iteration thing right sorry excuse me like we said we the first one we have no choice right so actually I just put zero cuz we kind of do it from zero to n and then the question is can we reduce either this iteration so I mean to make it n * K iteration so I mean to make it n * K iteration so I mean to make it n * K or n square or k square or some of these things but basically a th Square really the if the approach that we're doing is correct there really only two things we can do one is um optimize out one of the inputs um and then the other um the other is to optimize the loop right so yeah so here we can maybe um take a look and give a think right yeah um and here we will say okay maybe put zero as we said like before we have a one right uh and maybe we just add a few more numbers because you know it generalizes anyway the peration doesn't matter and you just have some K value that you're playing around with and then now let's say you put in a four um as we said we have uh five choices yeah five choices to put to four you have one two three four five and then the question is can we uh get rid of the for Loop right cuz I don't think we can get rid of K left and we can really get rid of well the current the N um unless there something like bri divide and conr thing so then the question is okay if I put the if I okay so there two things we can do on the first space right which means that we can put it here or not put it here what does it mean when we put it here right um we when we put it here put the four here that means well now we have what is the state is just a new K which we can do the math on um a new k and a new n right which is basically what we have here but then what do so what happens when we don't put it in here right well when we don't put it in here that means that we're not putting it here but then now you uh another way of thinking about it is that now we have this sequence and we're trying to put in a for we're trying to decide whether we're put in the four in the beginning and of course as I said the actual numbers don't matter because the number that we putting it in is the biggest now right so that means that um yeah there only three numbers left which if you want to reindex everything then you have 0 1 2 and the next number you put in is actually three right um and this actually works even if you have like you know some other funky um perations because even in this case like I said the actual numbers don't matter because the number that we're putting in is the max so therefore even if you kind of just like put in 302 uh it doesn't really matter right because then now you can reindex this to one and two but again as I said it doesn't matter because the number that we're putting in is the bigger number than all of these right so that means that we have two states that we go down to which is that we go we put in uh the four here or we don't and when we don't then we are um one less number and um yeah and then now we just have three numbers and uh four choices and then we got we can make this recursively so yeah I mean I think I get it uh maybe far A little bit if you are having struggle but one thing that I would change now is update some definitions or maybe even update some variables so current um before um you know I think K left is actually pretty straightforward K left uh number of uh inverse pairs left and then current it was used to be uh current number to be added right previously or you know that was that's now and then now to accomodate this what do we want to do we actually want to say k is going to be Cur is the number of um fixed things if that makes sense fixed items right and fixed items like I said um these things don't I mean I'm putting numbers for visualization but again I know that I overemphasize this but it doesn't matter because we're putting a number that is bigger than every number so they might as well be XX XXX right um so then here now basically uh and that's number of fixed item right so then now you can see that um given that okay so now we say we that given that okay so now we say we have current number of it items so we have two choices one is um to uh well one is if K left is greater than equal to current um cuz current is the number of things inside so then if you put one in the front it's going to subtract current number of things right from K left so then you can add something like count um and now once you put in the front it is it's going to be current plus one for the next number right and then K left the way that I'm doing this is a little bit awkward to be honest because we're adding numbers in a weird way CU okay yeah H I think the way that I Define this as a little bit awkward uh from the other way that I did it but because the reason why I'm saying that and let me just go through with the dot and I think I made a mistake I mean it's actually not that difficult mistake to fix but uh but I just want to be you know full disclosure and I'm just kind of like huh I didn't really think far enough on the explanation part like I kind of knew how to do it um just from like recognizing it but I messed up here but I just want to go through why I'm like slowing down having second dots but what I was going to write is that it's going to you go to this right because now um the next thing is that now you have this amount right and then you just kind of count the number of things and then the other thing is not ticking it which is going to be count or current minus one k left right oh this is K left minus curent sorry and then maybe like you do a mod or something like that but it turns out that this is not right um because I like I said I made a mistake and the reason why is that um let's say we don't put uh let's say we don't put one here then what happens right if we don't put one here then we here if we don't put one here then we get to this state but then after if we let's say we put one here then what right it actually doesn't go like in a asyn kind of way because now then you have these items and you can kind of expand this to another thing but then now you have to kind of keep track of how many things you want to that you already skipped right and so this is kind of not um you know dynamic programming only works on uh DXs um so this is going to have a nasty psycle and it's just going to give you the wrong answer right maybe you even wanted I know just give tell you that you're wrong or maybe just infinite Loop really I think it just yeah right so then now how do we fix it so I mean the fix is easy only because this is just like way wrong right so the way that I would think about fixing it and I kind of I think I just did the other solution in a tricky way but the way that I would fix it is that okay now that I um you know we have a sort of a recursion this is isn't quite right or recurrence this isn't quite right for you know things that we see and kind of a really short explanation as to why it didn't work um but then now we can think about it maybe just going in reverse right let um yeah and going in reverse then now uh it's still fine but then now we're saying okay let's say there are current number are let's say there are current number of items and there's K left and then now you have to say Okay use it given the biggest number um and the biggest number where is the biggest number right and the biggest number is either the first object so let's say now you have four things so then now you have to Define where the biggest number is and the biggest number is either the first object if it's the first object then you have minus three if and then otherwise then it is um if it and yeah and then now if it's the second object then you have something like um I guess it's just X's now right if it's the and then now you it goes down to whether uh it is the second object right with the thing eliminated um yeah is this right man I am maybe I'm just like leading y'all to a wrong paths but I would say even if we're really wrong here U these are kind of ideas and things that kind of come up in other similar problems so it is definitely worth kind of exploring it kind of in this way but um hm how do I do it backwards so uh yeah if this is equal to zero then have zero items left then yeah all right so we change spase case and then now if it's the first item then we do the we try to find it on a smaller case and this thing is fine otherwise we want to count but this isn't enough because this assumes that the next number cannot be hm it assume that the next number cannot be let's say we pick this one but there's actually three numbers left not two huh yeah I think I'm wrong on this one wow sorry friends for kind of leading yall through the wrong path H how do I fix it what is K LOVE at least it terminates okay just want to make sure that I didn't make mistake on that one but uh H let me think about this then I thought I had that idea but apparently I'm just like well very well I mean the way that you would fix this is by adding another dimension but obviously we don't want that because that would just be too slow anyway so that's why like I'm kind of trying to think through it a little bit huh I guess it is a hard one I haven't done it in a while H can I express this the same C no but I do this that's just silly oh okay I guess we could do it that way huh Can we I think the way that I'm fingering about it is a little bit awkward but okay maybe that works I could maybe do this but I don't think that works because we have to figure out a way to terminate it oh I see that is a ridiculous problem if that's true um I think I got it but that is so hard like to one to explain or not even to explain but just to like come up with wow I mean okay I mean I'll try I mean I think I get it but it's just wow not a definitely not my first cuz to be honest it's just harder than I expected that's all okay so what are we doing here right this is not the right answer yet um this is kind of similar to what we were doing but this is um but also in a way not really right um but basically this is the idea of okay let's say we have current number of fixed items left and then now it is I so now before we've been counting from the front to the back so the idea is just to count from the back to the front right so let's just say here we go um uh okay so let's just say is you know if it's this one then we can um if it's bigger than this one well the smallest number is here then we're done but then the question is that um on the K whether you want to do a little bit more so then here now we can actually we could actually cut it oh my this is not a easy problem to explain I mean I get the math and that's why but like I'm trying to explain it more visually so my apologies this is kind of very hard um especially if you haven't done it before um because in my head uh just to kind of give you a little bit of an insight to my thought process is that I was just thinking about like the different perations because and some of it is like kind of BR forcing all the algorithms my head not the algorithm Bo Force but Bo forcing on the algorithms in trying like well to be honest if like we said if we want it to um we want the complexity to remain n * K there really only a limited number * K there really only a limited number * K there really only a limited number of ways to do it and then here this is idea is that okay um we're done with the current number right and then here is let's move one space to the left right so this is basically boot forcing um the summation and this part is actually um I mean I don't know if I have a good visualization for it but if you kind of recall what we had or maybe we can kind of rewrite this a little bit similar to what we had before with the for loop I maybe should have kept it but whatever um but basically the idea and you might know and this idea is I think easier to understand is Right which is that Y is in range k um+ one and also current or something um+ one and also current or something um+ one and also current or something like this right so Min of this and maybe current plus one I don't know if it's current plus one or current uh doesn't matter right for a point of visualization but K left is greater than current then we have oh sorry if KF is greater than I right so this is basically what we had before right and the idea here is that um this is not a easy thing so definitely if you didn't get it I don't know I mean it's taking me a while to be honest right so like I wouldn't feel wow 28 minutes um but yeah but basically the idea is what I would call uh loop caching but basically that this idea is you kind of expand this out this is just going to be you know total is equal to or this Loop which you can write rewrite as count is equal to this um should can it be zero I guess it could be zero actually right well I mean okay actually in this case it's current minus one that's why I got a little confused because now you're done with the current uh number right and it'll be this plus you know something like that right though it's a little bit yucky right so yeah so it looks something like this is what this Loop does and then the idea here is um almost like a prefix sum if you're familiar with that uh is that now instead of you know we have this uh recursion or this function that we're trying to get we can actually um we could we should actually um get some do and that's the thing where um if we had current um well actually technically with minus Z it doesn't actually goes to current - one doesn't actually goes to current - one doesn't actually goes to current - one and then the next one would be current k minus1 um and because of this actually so it's this thing right uh is what we're proposing and basically this thing expands out to this plus count of current K left minus 2 right um dot right and so you could kind of see um and this like I said it takes a bit of experience to kind of figure it out or even just like you know oh how do I have it right yeah right all the way up to count oh well actually I guess this actually terminates what I mean is this now kind of expands it out right I expand it one more time just for clarity um but yeah but this expands out to netive one this thing plus count of current K left minus 3 right and you can kind of expand this all the way out and it'll be basically this thing right kind of why did I say kind of because um and this thing is actually a little bit wrong because this should be maybe K left minus curent or whatever right like this is the actual Min but it could be zero but let's actually change it to this uh for now right and here but in this case if we kind of expand it out and maybe you do a like I said like if K left is equal to zero um just make sure that K left is greater than zero otherwise yeah so let's say you have something like this and you should anyway otherwise you have negative K left which is meaningless or it's a easy optimization in other case but yeah if you kind of expand this arum to this will actually go to um this would actually go to zero right until it is done because we don't keep track of the current so that is kind of ridiculous right um so then now we basically went from uh this function which is our for Loop that we had and we kind of understand why did I remove it uh it's fine I trust you can go back and look at the follow Lo again but yeah um I don't have it in a good visual way like I had with the X's apologies but yeah but that's basically the idea and then now but now you have this versus this right so this isn't it uh this isn't the answer yet because now we have this thing or like our current thing is this but we want this so then what happens well the idea I kind of hint at is and this is actually zero or well this uh the idea that I was saying is going to be prefix sum right uh so yeah so let's actually expand this out a little bit you have K left minus current plus dot right that's dot this part and dot this part right um yeah so then you have like these two things so then now what uh let's actually expand this one more out but well yeah the short answer is that now I hope I'm right I mean I think I'm right but I should have tested this before uh before but yeah but basically here now like I said you have this so and you have this so then now you just have to subtract out this thing so then yeah and I think you can write something like um but I don't know that this is quite precise right or is it and well here we actually don't want this because this is actually wrong because this is just this part and we have to add the dot part but this part actually go to count of current K left minus current I think or maybe minus one right yeah uh and this part is equal to this part so yeah so this would be this and you obviously if you don't do it that way then you have to write out this for Loop and this for Loop is also going to be like you know add a lot of time complexity so that's what this part is I'm trying to think whether that makes sense or that's precise enough because then here this Al cuz this also that's recursive right um as in that this also subtracts on KF minus one I think this is right but this stuff is kind of tricky but that's basically the idea behind the prefix sum is that the way that we did it we have this and then now we have this and it's definitely not a easy thing to come up with um let me just leave it here let me one real quick all right well that didn't go well I have the right base case uh I think this part may be a little bit awkward let's just actually do something like I guess I like it here a little bit is this right yeah okay I think I like the e sign but H I think the part that I'm struggling is trying to figure out if we need the entire St or iside the DAT this maybe that's a little bit better but well we're getting zeros so maybe there is some like a base case issue instead um oh yeah well we're getting zero because we're counting down instead of up so our this thing as well uh that's actually a little bit of sillyness um okay so we have 27 two H am I off by one somewhere 3 Z is one okay H maybe I'm am I off by one I mean I'm literally off by one but I mean like on the indexing so 31 I mean I guess we can just print uh k left and then total right just debug it um K left being zero is a little bit sad or less than zero uh how are we doing that I thought we double check how are we getting negative K left huh definitely should fix that oh this is uh man double negative stuff hurts all right I mean yeah it's still wrong but at least we uh fixed that part okay so 31 goes to 2 one 31 doesn't go to 3 Z as well okay yeah three so it's this plus this 3 Z is one is correct two one two numbers one inv verion this two ways of doing it seems wrong that's the thing is that I don't know if I'm D over subtracting it but that would only gift the other side but man this is a hard one I think the idea is right but I think maybe I'm just off by one somewhere which we should still res solve but uh okay so two numbers yeah okay one number oh am I off by I think I yeah okay um I changed it to zero index and I think that's why okay fine yeah okay that's just a silly thing cuz I changed the zero index and I so it was doing one extra number uh yeah okay let's play something slightly bigger oh no okay I mean that's good in that you know well let's CH find a smaller case to be wrong um so then we could debug it easier huh oh did I change something no cuz I think this one I'm not sure cuz there two ways you can write that formula that's why I'm a little bit uh sketched okay so it is this way that is hard um okay yeah I mean so the reason why I wasn't sure about this um to be honest um is that even though this is equal to like I said this is actually this thing that I'm highlighting is actually equal to count of current uh K left minus current minus one um there's no easy way to only do this deletion once for the world right CU this expand this thing expands out to all this stuff but we also keeping in mind that in the future so like so um if we call this oh sorry if we call yeah I mean but basically the idea is that we call this then we also call this then we basically double deleting a lot of these counts and they kind of cancel out in some weird funky way but if we do curent minus one then now another way of thinking about it is that this number sub will subtract this number and then this matches up with well this minus one so this matches up with this and then all the way to K minus current um and by definition it this will subtract um and current minus one so it would only have so this would subtract K left so you should have the right number um but well this only goes all the way down to zero is what I mean right I don't know this feels very sketch to be honest I mean I think this is roughly right but it still feels sketch uh all right well I just say for now uh that's basically the idea um we have to add memorization um I'm not going to uh okay fine let's just actually do it I'm just do my usual um memorization thing uh I'm not going to explain it too much today kind of went over it all week and I'm a little bit um you know and to be honest it's not just because I'm lazy though is a little bit out it's j I'm not I'm just like eager to test to make sure that this is right before I kind of want to go further um because I'm kind of not feeling that super confident about this um cuz it's just a lot of I mean the idea the core idea is right just to be clear um I believe in the idea but it's just so easy for like I can't I'm having trouble doing all these prefix sum form and recursion and stuff like this in my head um that um yeah it's just tricky right yeah it's much faster and then now we can try something bigger like a th a th000 or oops 500,000 th000 or oops 500,000 th000 or oops 500,000 right I mean the complexity I'm not really worried about anymore because this is just going to be I'm just looking at the right answer I guess if it is the right for these it's going to be right but this is a ridiculous problem to be honest how did I do it last time did I explain it man I mean this is the same code as I have today pretty much but um I wonder if I did it quicker though uh I mean this is the same idea prefix sum and then just like pre-calculating sum and then just like pre-calculating sum and then just like pre-calculating it but this is bottoms up but yeah hopefully this idea kind of makes sense let bring it back here let me delete this so you can see all the code at the same time the code isn't super interesting I think the idea is actually pretty cool um the idea of prefix some and having to remove it but um but it's really hard like I said I don't think I don't know it's not a easy one to do for sure I think for me it would I would consider it too hard for an interview apparently it has but um I don't know is still a user solution let take a look boo Force okay that's just silly you're wasting my time DP I mean this is also too slow uh DP cumulative some which is I guess kind of what we're doing what is going on I guess this is what we're doing but there's a 1D oh yeah I guess if you convert this to Bottoms Up of course it's going to be 1D the way that it phrase is a little bit weird but uh yeah I mean I don't know what to tell you I mean you saw it live I know that I do spend some time trying my best to explain this problem but you know so maybe I get it in like if I have to estimate um and I kind of went the wrong path a little bit um though I kind I knew how to do it but like if I have to estimate like um I would it would probably take me about 20 minutes to solve this problem which is to be frank like and you know maybe you could call arrogant or bragging or whatever like I think that's relatively pretty good so I think that's just too hard for interviews just because like you know like if you haven't seen it or done it specifically um and you're kind of doing it from scratch and today I don't know like I did it today a little bit from scratch like I don't remember the previous time I solved it I do remember the ideas from either this problem or other problems similar problems I have those things but it's still not an easy problem this is a really tricky technique to kind of recognize so um I don't know uh let me know in the comments what you think this is a very long video uh yeah hopefully you enjoyed it uh so no extra uh premium PR today but yeah let me know what you think stay good stay healthy to go mental health I'll see yall later and take care bye-bye have a great weekend take care bye-bye have a great weekend take care bye-bye have a great weekend everybody byebye
|
K Inverse Pairs Array
|
k-inverse-pairs-array
|
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`.
Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, k = 0
**Output:** 1
**Explanation:** Only the array \[1,2,3\] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 2
**Explanation:** The array \[1,3,2\] and \[2,1,3\] have exactly 1 inverse pair.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= k <= 1000`
| null |
Dynamic Programming
|
Hard
| null |
728 |
what's up guys my name is Michael and welcome to my youtube channel today we're going to do another league code challenge self dividing numbers a self dividing number is a number that is divisible by every digit it contains for example 1 2 8 is a self dividing number because 1 - 8 mod 1 is equal to 0 1 - 8 because 1 - 8 mod 1 is equal to 0 1 - 8 because 1 - 8 mod 1 is equal to 0 1 - 8 mod 2 is equal to 0 1 - 8 mod 8 is equal mod 2 is equal to 0 1 - 8 mod 8 is equal mod 2 is equal to 0 1 - 8 mod 8 is equal to 0 so it is divisible by every number it contains every digit contained also a sub dividing number is not allowed to contain the digit 0 given a upper and lower bound I'll put every single possible so dividing number including the bounds as possible this is pretty basic you guys try to do this on yourself on your own and come back to me when I when you're done okay try to do this on your own if you can't figure out in one or two hours then come back to this video but essentially the algorithm is that you're gonna go through every number between left and right inclusive okay and you're gonna check if it's a self dividing number that is it's divisible by every of its digits okay and if it is then we add it to the array we're returning and then when we go through from left to right once we're done with the right one we just return the array that's essentially the algorithm yeah that's how you would do it come back when you implemented that and then we'll see you if your solution is like my solution so yeah okay so first we'll hold up guys hold up my bad hold up okay so first how do we do this well first you need to create an array that you got a return that has all the self dividing numbers so this is gonna do it so I'll call it to return for now but yeah then what do we got to do we got well we got to go through every single value from left if it's less than we're including right so it's that's why it's left to being equal to go through every value between left and right and then if is self dividing passing if whatever value we're checking itself dividing we're gonna add it to return pushback I then after that we're gonna return to return okay so then that's essentially the algorithm now we need to create a method called is self dividing we're gonna pass in a value of I so how do we check if it's self dividing well a self dividing number is a number that is divisible by every single every digit in contains so first we need to essentially let me think how do I say this do we have to go through we have to get every single digit and then mod it get every single digit mod it and if it equal if it doesn't equal to zero then we return false okay and we're gonna do that for every single digit so how do we do that I'm going to do while I is greater than zero okay we're gonna do I is okay how about instead of using isle use an actual number so let's change I did like numb so that I don't like the variable I so Y is greater than zero we're going to take number and we're going to divide number by ten so if you divide by ten so let's say one to eight you divide by ten then you get one two 28 - yeah so that gets you two 28 - yeah so that gets you two 28 - yeah so that gets you if you were to divide a number by ten you get this one - that's the remaining you get this one - that's the remaining you get this one - that's the remaining okay and now what we want is we want the remainder want to mod by ten to get the last digit so that we could get eight and then two they want so I'm gonna take all a number called remainder is going to equal to num mod ten okay so this is going to get the remainder now what we need to do is we need to check if the original digit is able to mod by the remainder and if it's equal to zero then we continue if it's not equal to zero then we return false okay so in order to do this we need to create another variable we're gonna call this original and this is going to equal to whatever value we passed in the original number before we went through this while loop okay so let me call this original alright now we're gonna check if original mod remainder is not equal to zero okay then that means we return false we also have to check or the remainder is equal to zero because if the remainder is equal to zero is all out of containing the digit zero so we got to return false all right this is a good basically going to go through every single digit in this array if for every number and then it checks if it divides it mods it is equal to zero okay if it doesn't equal to zero returns false after this loop is finished that means it must have none of that means none of them have returned they had not returned false we're gonna return true okay none of them all of them had been able to divide by mod by zero mod by remain so they were all divisible by each digit yeah this is a shared work if it doesn't work then I don't know there's must have been a compiler or something happen this is basically how you would do it let's see what happens runtime here what is the difference divisible division by zero oh okay so you can't do this we got to do this first it's equal to zero the return is the effects of it's called shortcutting I think something called shortcutting where it checks the left side first then checks the right side okay so this is working now we submit and it got accepted so that's basically how you would do this yeah I don't think there's any other way let's see the solution oh yeah okay so there's only brute force they don't have anything else that's basically how you would do it Raycom subscribe I hope your solution looks something like mine I'll check you guys later peace
|
Self Dividing Numbers
|
self-dividing-numbers
|
A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104`
|
For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number.
|
Math
|
Easy
|
507
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.