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 |
---|---|---|---|---|---|---|---|---|
112 |
Hi gas welcome and welcome back to my channel so today our problem is Parth Sam so what have you given us in this problem statement here we have given the root note of a binary tree and the target is OK what do we have to do with the root In all the paths from the leaked note to the leaked note, if even one path's target is found, then it will return through, advise, retain, and make false. Okay, so let us understand this problem through an example. First, what is our problem exactly? After that we will see whom. How can you solve it? Okay, this is your tree, okay, and this is the target and end, what you have to do is from the root to the live note, this is a leaf mode, okay. There are so many parts in between, this path, you have found this one path, you will get this one part, this one path will be found, this one pass will be found, so if we make the target true in all these parts, then what will we do for this, which is Told you, if you get even one letter of yours here, what will be the path's sam, then what will it become true, what will we keep in the initial, we will keep it false, okay, if you get even one, what will you do with it, people, you will make it true and in the last there will be flag return. Tax people, if we do n't get even one then it will remain as fall. Okay, so we will start from here, what are we going to do, why are we going to do that, because what we have to do is take our route notes and go till late notes. Right, so what do we have to do with DFS. If we have to do that, what will we do here, what will we do, let's start, okay, then go towards its left, what to do with 11, add it, done, what to do with seven, add it, done, then where will it go to its left, also tap Its right is also null When your left child is not even there Do n't even take the right choice That's leaf note when you will know that its left is not even right This is leaf note from Redmi We have come here on our own path If you get the sum till here, see whether you are getting a total of 22, now you will see that 5 + 499 11 20 plus 7 27 is will see that 5 + 499 11 20 plus 7 27 is will see that 5 + 499 11 20 plus 7 27 is not equal to 22, so here we call it the falling seven, then you call it on the right side because you have left. Have you looked at the right side of this, add tu to the right side and then you will see that the left side of tu is also null, the right is also null, so what will we do here, we will see Sam here because we have reached till the leaf note, so this is the second part. If you have yours, then look here, Sam's is equal to 22. So this time you will get equal to 22. Right 5 + 499 1120 plus you get equal to 22, Right 5 + 499 1120 plus you get equal to 22, Right 5 + 499 1120 plus you get equal to 22, then what will we do, we will make it true because we have got one thing, okay. It is found in this case but it is possible that if you find it in this thing then you will have to see all of them. Right, so let us see all the parts here, it is not necessary that we will find it here in the second part only. If you get to the last point, you will have to see all the passes, that is, you will have to call once for all of them, because you are calling the function once, you are calling like this, it is not going to end until you do it completely. Right, here you will finish, then it will go back, so you have to go from here, right, you will be put from here, then when it sees 11, its right has also been done, left has also been done, light has also been done, it will come back 11 also. Four will go from here, four will go towards its right, if it is null, then it has gone back, then it has also turned to its left, light has also come on, it will go back, so four will also move from here, okay, then we saw that five has already looked towards its left. So what will it see? If it comes to its right then it will add 8. Okay, it will go to its left and first add 13 to the left. Okay, here, so the sum till now will see 5 plus 18 13 26. Is this equal to this? What is not? Okay, so what will we do? We will go back, we will add it back here, it has seen its left side, it here, back here, it has seen its left side, it will see its right side, its five till here comes 134 17+18 OK, 18 is equal to 22, none. 17+18 OK, 18 is equal to 22, none. 17+18 OK, 18 is equal to 22, none. So go back from here, go back, this will not end, this right will do something, is it true? If it is true then we must have got the date men once, if it would have remained false, if we had not found even a single path, then what is this fall? If C happens, then what do we do? We retain the flag. According to the flag, you come to know. If the flag is false then read and false. If it is true, OK, now let us look at the code part, what we did here. If you go to the previous function, you will return here. Okay, you are calling left. Milk will be left towards the target. Right here, target is sam. Okay, then you will get the flag because the flag is your global, so here you will return the flag. So according to the flag, you will get the answer. If you have not found even one, then if the flag remains false, then false will be returned. If you have found even one here, then the same targets of the path from the root to the leaf note and near the note. If it has been true here once, then there will be 10 rows here. Okay, I hope you have understood. If you liked the video, then please like, share and subscribe. Okay, I am telling you till my time comes, watch it. What are you doing here, you are also visiting its notes, right, so what will be your time complexity here, O N, what will be the number of notes, number of nodes, okay and what will be your space here, what will be the space complexity. Oh, because now you are calling the function, this is calling here, this is here. If someone is calling then you are going to the left then what is the maximum you can go as far as the trick is concerned, what will be the height, so this is what it is, this is the height of the tree, okay, the maximum can be the same, this height is your method.
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
40 |
hi everyone welcome to my channel let's solve the problem combination sum 2 so this is a second problem of the combination sum series i have already video on combination sum and combination sum 3 so if you haven't solve the combination sum problem before attempting this problem i will recommend to solve that problem first because if you solve that problem you will easily solve this problem there is a bit little bit changes as compared to that problem so let us understand the problem what is the problem given a collection of candidate number candidates and a target number target find all unique combinations in candidates where the candidate number sums to the target so each number in candidates may only be used once so this is a change here we can use only once in the combination sum we can use multiple times so all the numbers including target will be positive integer and the solution set must not contain duplicate combination so we do not have to return the duplicate combination as well so this is the example one so let's understand over here so for solving this first of all we will sort the candidates array so that we can easily take the decision so now after sorting this will become one two five six seven ten now if i start picking this index so for starting we will loop a helper method and start from the zeroth index we will start picking this so first if i pick this one then i will move to the next index so if i pick the one so the solution array will contain the one and the remaining target will become seven minus eight minus one which is seven and index will be one so here this is a second the third number is for tracking the index so then we can pick the another one this will become here ah 1 and the sum will be the target remain will be 6 7 minus 1 6 and this will come to or we can do from here itself we skip the second one and we will do the one and then we instead of one we will pick the two so this will become the upper array and then next element the target remain will be seven minus two which will become the five and next index from here we will pass the i plus one the current i we are processing is two so this will become like this similarly from here we can select two now 1 2 and the remaining target will become 6 minus 2 which is 4 and the index is 3 and we can also again go here select skip the 2 and select the five or so this will become one two is not selecting now we are selecting five if we select five this will be our temporary list and the target will left one and this index will be 4 and we can also select from here 6 instead of 5. so 1 we will try all the possible combinations if i select this will become 0 and the remaining will be 0 and the index will be the next number which will be five so if you see this is the case is one of the our solution case where the combination sum is becoming that equals to the target as we reach the this zero this will become the target so this is the first case then what we can do from here if i select the 6 in this so this will become the combination 5 6 but the sum will become the target remaining will be negative which is -5 is -5 is -5 hence from there we cant get any solution so we will backtrack from this solution so this is the case we will start like remove this element and try further and so on then we will go back and so on this is the way is the recursive tree will come up and whenever we reach to the negative this is our one of the base case we will backtrack from there return there will be no solution after that or when if the remaining the target remaining will become zero then that is the one of the solution but now here we have to deal with the case where we get the duplicate solution like one solution from this numbers we can get one comma seven pair by starting this another solution we can get from another one which will be one comma seven again and we have to remove this duplicate once so how we can remove the duplicate pairs so one of the solution we will use the hash set to store our list of combinations so that will be automatically removed and all the elements we are selecting as after sorting the array in the increasing order so all the element in the list will go in sorted way e so this is the way to remove the duplicate otherwise it is very similar so let us quickly implement the code so for the code part we need a one let us say we will take the first set then the list and then integer so this will be our let us say result to call and initialize from the headset now we will call our backtrack method that will do all the recursive call and try for this and before calling this method we will first sort the ah our candidate arrays dot sort this candidates array and then we will pass this into the method and also we will pass a start index from the zero and then one temporary list new array list that will be called as a path we are selecting the branch or something and we will also pass the result and we need to pass target the current target so that we will use for the hour base case so this is the case and in the end we will return new arraylist we will convert the set of list into the list of list using this new list of ah result so this will be the written answer now let us implement our helper method backtrack which will be written type void and back track so this will get the candidate array let short end with the candidate can and then the into start index and enter target and the list of integer as a let it call list itself and the set list of integer and this let it call it as result so this will be the method signature now we will check the base cases if target becomes less than 0 then we just return from here there will be no solution if target equals to 0 then we have that solution we will add that list into our result set result at new array list of list copy from that current list and then we will try all the possible combinations starting from the start to go till can dot length i plus and then here first we will add the current element into the list so list dot add cand of i once we added this then we will call for the all other and here we will pass can i plus 1 because we do not have to use the duplicate so i plus 1 and we will subtract target from the selected number which is scan tend of i and same list and result will be as it is once it done and once we get notes once we tried all the possible way from the one branch we will remove that from the list so we will backtrack from here so list dot remove ah list dot size minus one the last element because the last element on the index minus size minus one so this is the recursive implementation so let us compile the code and see if it is working so it is working and we are getting so the order does not matter so its fine we are getting all the combinations so hence we can try to submit this code and see and it is accepted now what is the time complexity so at every moment we can select the number or skip the number so hence there are two options and we have two number 2 to the power n is the time complexity which is exponential time complexity and in worst case this branch can have all the numbers so the space complexity inverse capes ah other than the recursive call stack it's o of n so this is the solution if you like my solution hit the like button and subscribe to my channel for the future upcoming video thanks for watching
|
Combination Sum II
|
combination-sum-ii
|
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30`
| null |
Array,Backtracking
|
Medium
|
39
|
657 |
hello everyone so in this video let us talk about a very easy and very small code for a problem that is robo return to origin so what the problem statement is that there is a robot starting at the position zero comma zero in a 2d plane okay and the zero comma zero is let's say an origin and there's a 2d plane now what did now there is a sequence of moves the robot has to perform and the sequences moves are like from a current cell you have to either go left right top or bottom or like up or down so from like you can assume that there's a very large grid and from the from any grid point you have a sequence of moves and from that sequencer move you have to like from any grid you have to either go up in the grid down left or right and then what you'll actually have to find out is that after performing all those operations after doing all of those moves whether the robot comes to the same point that is zero comma zero if it is true the answer is true as the answer is so or you can check that out now for this problem what you can actually see is let's just it's a very small easy problem but let's draw it out so that it will become locative let's say this is the grid i have the grid but let's see it again try it out let's say this is zero comma zero okay zero comma zero now the sequence is that move up so you move up okay then he said that go right then again right then down then left and then left so what you can directly see is that if i want to come back to the same point what it actually means is that the number of steps i moved up should be the number of steps i have to like bought down as a number of steps i have moved right should be equal number of steps move round like uh right is equal number of steps move left that's it so you have to just match them out and just check that out whether they are equal or like whether they cancel out or not what you can say is that you can just take two variables like how much horizontal movement you have done so let's say horizontal and how many vertical movement you have done so vertical means that this is this moment causing moves this moment so let's see that you have moved one step top so you have moved one step vertical for every vertical moment in the up direction just increment your vertical variable let's have some variable plus one so plus right so now it becomes one now you move one step on the right so for the right also let's say now you're moving in the horizontal direction so move your horizontal by plus one so plus one now again you move white so horizontal now become plus two so you have two spaces on the right from your region as well as one space on the top of the rear now you just moved one step back so now because you have moved one step down just decrement your horizontal like vertical position by one so it will become zero now you move two steps on the horizontal on the left side so whenever you move the left side just decrease it by one so one and then once it will become zero and whenever the sequence completes out both the values should become zero again which means that you have like whatever left or right up down or like horizontal or vertical distances you have traveled everything should be boiled down to zero that's the overall logic and quote like logic part for this problem that is one of the code part so this is horizontal hor and vertical like movements you have done it right over all the moves if it is you which means that you have moved up increment your vertical by plus if you have moved down decrement your verticals if you have moved in the right direction increment your horizontals if you have moved right left hand side then decrement your horizontal at the end if horizontal and verticals turns out to be zero the answer is that you have returned to the same point like changing out this problem if they just check out that whether they have reached to a certain point let's say starting from any coordinate and they have a certain coordinate whether the sequence is kind of not you can also do this thing and just check that from a particular point if they have to use this particular point how many moves they have required like it's that yeah they are on any particular point in the grid on this point and they have to reach this point so you have to move certain moves in the horizontal directions or take us like certain the vertical action and certain horizontal direction you cannot check it out in this problem so that is a different variation for this problem as well oral time city is o of n because you are iterating all the different moves and no space is required that's it that's over a logical part please regard for the variables actually so it's constant or fun that's over the logic and the good part for this problem thank you watching video till the end i will see you in the next one i'll keep coding and bye
|
Robot Return to Origin
|
robot-return-to-origin
|
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).
Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.
**Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
**Example 1:**
**Input:** moves = "UD "
**Output:** true
**Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
**Example 2:**
**Input:** moves = "LL "
**Output:** false
**Explanation**: The robot moves left twice. It ends up two "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves.
**Constraints:**
* `1 <= moves.length <= 2 * 104`
* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
| null |
String,Simulation
|
Easy
|
547,2239
|
309 |
what is up everybody welcome back to my channel this is tony aka one lead code one day if you're new here the channel does one lead code per day following the pattern of topics or series that is i'm going to be solving with you together on a lead code problem i have never attempted before you heard that right there's no prescripted answer we're on the same page here but don't you worry i got you covered and i promise that i will stimulate the average performance code at the end of each video here's a little bit about myself i come from a non-computer myself i come from a non-computer myself i come from a non-computer science background so i'm no better than most of if not all of you guys in terms of coding knowledge but that is okay if i can do it you can do it is all about learning on the go you can think of this video as a first person gameplay of cracking lead codes and who doesn't like first person gameplays right so without further ado let's start today's coding problem today we continue on series one everything about dynamic programming and the problem is a continuation of the last two videos best time to buy and sell stock now with cooldown so let's get into it all right so we know about what um on the previous uh you know buying selling stock array was like so you have an array called prices and the value at um and those uh in this array is uh the price of a given stock on the i stay so we're gonna find the maximum profit you can achieve uh you may complete as many transactions you like buy one and sell one share of the stock multiple times with the following restriction after you sell your stock you cannot buy stock on the next day there's a cool down day you may not engage in multiple transactions simultaneously you must sell the stock before you buy again okay so this is like a further restriction um in addition to um the last problem uh buy uh best time to buy and sell stock number two um right you can still buy and sell multiple stocks but you cannot buy again on the same day right so for example we're given uh one two three zero two so you can buy on day one let's say buy on day zero because we want to use uh zero indexing consistently by on day zero sell on day two you have a gain of two dollars uh but then um actually no you don't do that you want to uh you know exploit this the free stock so you buy on day one say on day two you know do your cool down on buy on day zero stay on day one and do your cooldown on day two and then buy again for free on day three and then sell on day four and you get a uh full um profit of three dollars so with that said let's start um let's just first move these descriptions into a new python uh jupiter notebook uh and we're going gonna copy the description and uh you know the first example in there because the first example is always the best example uh and here we go and we're gonna store that for you know future reference whenever we want to you know take a look back uh it's going to be good and uh representative and now we also want the constraints there right because constraints is something we might be able to exploit to make our solution uh even simpler all right so there is your description and your example and your constraints we're going to copy also the solution template and we also want a um you know we also want some kind of uh test case so we're going to copy from a previous test case uh let's just name this rename this uh python notebook called lead 309 right uh and then what is our test case is one two three oh two that's our first test case uh right let's just you know build a new line i want to keep the previous ones there one two three oh two and expect seven uh expect three sorry there you go and these ones we don't know yet we're just going to comment them out whoever test case and we have our solution template and let's start sketching it uh so we turn to our sketchboard uh this was uh from last video so now we start with a new one and we start with this example here uh to prototype uh upon and then uh we're gonna start you know thinking about some intuitions here so we can buy and sell it as many times as we want but there's a cool down time uh so continuing with our previous intuition that we came up with which is you know always buy any dip and sell at every peak um which is still somewhat valid but now we need to take also into a account that uh you need to have a cool down time so really this kind of like cool down you need to really uh be careful when do you spend that cool down day on because that is a day where you know you definitely cannot do anything you cannot buy you cannot sell basically you cannot buy like on that cooldown day after selling you cannot buy anymore so um so this pattern is gonna be like you're gonna have to define whether a day is a day worth doing the cool down or not right um and how do you right that's the key question um how to def how to decide if a day is a good day to do the cool down right because other than the cooldown everything else is pretty much the same so if we can just pre-select the days so if we can just pre-select the days so if we can just pre-select the days for the cool down uh then we're good right if we just pre-select the days for cool if we just pre-select the days for cool if we just pre-select the days for cool down and then we just um because we know if we pre-select go down because we know if we pre-select go down because we know if we pre-select go down then that means the day before the cool down is the day we sell right uh so we immediately know you know our selling days and that would be great so how do we decide what day is a is it is a good cool down date so let's ask a further question you know what is how to quantify the worthiness of a cooldown day right quantify it and then we can pick it um we can take a look you know in the optimal solution for whoops uh let me just move these things down a little bit so we can start working on this so in this problem here we selected number three date num day three which is you know index number two we selected this day as our cooldown day and why was that because you know if we cool down this day that means we basically uh sell on this date right sell on this day uh that was right basically that means we so we do perform a sell action on the previous day uh why is that good well um because you don't want to block any low prices right this is a low price you don't want to block any low prices right you don't want to block that this is a dip you don't want to block any dip basically yeah let's just you know say dip this is a dip right and this is also called like a dip maybe so you don't want you definitely don't want your cool down to block your dip um if possible but then you also don't want your cool down to um to block your peak as well you know this is actually one of the peaks right peak so if after the peak right after the peak and after the peak if the next day is not a uh a um a dip day then it's perfect we can just you know cool down uh sell at the cell at the peak and then do a cool down and then wait for the next step and then do it right that's just natural uh if we have that freedom to cool down you know between a peak and a dip that is perfect um but you know nothing's perfect sometimes you just have to make a choice because what if a peak and a dip is just next to each other then you have to make a choice right um yeah so let me just write that down okay if uh between if there are um if there are at least a one element between a dip and a following no between a peak and a following dip then those elements in the element and that element or maybe those elements um is a good place to cool down without any cost right so it's going to be like a free cooldown there but that's the world is not perfect right so this is just uh you know scenario one but the world's not perfect so um if there are otherwise right otherwise if there are no elements between a peak and a following dip right this is when we need to decide uh where to place the cooldown right there's two choices on the peak or on the dip right yeah so um let's just you know maybe start drawing something to make it a little bit more illustrative so for example in the best world right like in the scenario number one uh let me just use a darker color actually because i think this color is a little bit too bright yeah let's just use this so in our first case uh which is the which is this case here right this case here um so if we somehow pre now have a peak right and then there is uh you know between the peak and then the next dip right this is like a dip and then we have another going up if there's like some non-zero non-zero non-zero there's some elements in between right for example there's one element here if there's one element here then this element is a great you know this is a free cooldown right because this is a peak and this is a dip you can just do a free cool down between um take advantage of that free cool down between the peak and the dip uh second scenario is where you know the peak and the dip is like back to back right we have a peak and next to it we have a dip you know uh so of course maybe we have you know some value before that some value after that right um so now we just let's just write it as you know back to back peak and back to back peak dip right back to back picked it this is like the scenario and in this scenario we have two choices right what are our two choices well the first choice you know choice one is that we can place our let me just change the color okay just to make a little bit more dramatic uh yeah the first choice we can place our um our cool down on the dip right so that means cd on the dip what does that mean well that if this is our cooldown then we're definitely like selling here right uh and then on this dip day we're not buying so that we have to you know continue consider buying on the next day and who knows what happens next right it could be going up it could be going down if it goes down again i mean there's no buying chance but that's the risk that we're taking here um right this is like choice one we put cd on the dip on what is the another choice then the other choice is that we can um it'll be like this oops this is like a different color than before so we want to use this right so it'll be going up right going up going down going up again uh going up and then quickly going down right and then going up again so this is your peak again this is your dip uh the next choice let's use back the purple color uh is where we actually um take you know uh cd on the peak so what does that mean that means we're gonna uh target buying from the dip here because we know it is a dip that we can definitely sit on that game afterwards but then we would sell earlier right we would sell earlier basically that means we would have to sell earlier uh like here yeah we would have to sell earlier buy and then let's just yeah use the purple color again that means we're gonna have to sell here all the way by here and in the first case right in the first case this is choice two right choice two yeah choice one is where we maybe buy over there and then we sell at the peak right peak we sell so we're gonna protect um we're gonna protect the transaction uh belonging to the peak um in the second case we're gonna try to protect the transaction uh us uh you know uh starting on the dip uh so these are the two choices so which choice gives you know between these two ices which one is going to give you more uh benefit well um well it's kind of hard to decide right like you have to kind of like take into account um a peak value uh and what are you losing by you know uh setting that cell action backward one more step and what is the value of like giving up a dip and then going for the second best dip value so this is like kind of like counter-intuitive no or away um or a counter-intuitive no or away um or a counter-intuitive no or away um or a little bit uh complicated in terms of uh intuition so uh it's kind of a hard choice to make so i think we're on a wrong tangent or like a not optimal tangent of thinking um what else can i think well instead of using this like um you know trying to do a bi-dip and cell peak kind of intuition bi-dip and cell peak kind of intuition bi-dip and cell peak kind of intuition we could actually use a different perspective which is more microscopic and we just look at you know each individual step like what actually what action do we perform on a day-to-day basis on a day-to-day basis on a day-to-day basis right so on each day we can perform basically three types of actions we can either buy or we can either sell or we can just do the cool down um and depending on whether you are buying or not i mean uh you have limited options of like selling or uh or not selling right because if you're not buying then you cannot sell anything so uh what about that alternative um what about that alternative vision uh that you know microscopic step-by-step-by-step-by-step vision let's just draw something illustrative and then try to figure it out all right so for example let me just forget about what we just discovered uh what we just discussed and just you know take a look at uh a random you know maybe sketch of a stock price chart right and if we just focus on the step-by-step action uh can we maybe somehow include this cool down into our uh maybe into our uh consideration here for example these are our you know day to mark there and uh basically you know from this day zero to day one it's like of course we're gonna buy we want to buy and sell but no uh if we do that too frequently we're going to experience a lot of cooldowns right so we're probably going to just uh buy here b and then we're going to hold here just do nothing right let's just use a dash to mean do nothing uh probably want to we may want to sell here but since we have like you know we have this thing here we can definitely use this as a c d right so we're definitely just holding uh and at three we're definitely selling because we can just take this free code down here right this is a free cooldown and then we let's see about these i'm not sure whether we should um at number four whether we should buy i mean we definitely should buy right just based on this but um let's say we buy it okay uh see if it's like globally optimal we buy it and then do we sell here uh because we don't have free cooldowns anymore so you will be ha you'll have to be a little bit hesitant um that depends on actually the value between this and this right so if you just sell here and you take it back from here if this is slightly higher than this right if this value is slightly higher than this then definitely you don't want to take it back from here you kind of like want to hold on to it right so if this is actually the case we don't sell but we kind of hold here uh but then you know maybe if this price here is actually lower than uh than this price here right if that's the case then maybe instead of buying here we actually don't want to buy here maybe we buy here instead right maybe we buy here and we don't buy previous in the previous dip yeah maybe that's uh i mean this is still all getting over complicated um so the best thing to do i guess in this locality is to buy here right is to buy here and uh don't sell until here maybe we yeah maybe we don't do anything here we sell here and um maybe for this one we're just gonna do the cd here because there's not a lot of gain in this little local slope we might as well just uh hold and we do it by here because there's a pretty long uh price rise streak ahead of us so we hold i definitely want to sell here um and then this is going gonna be our cooldown and we're definitely not buying because it was on a rise so we're just gonna hold and this is like this looks like a dip so we start buying uh then we hold it and we sell it there and this is going to be our cooldown and that's it that's the end of it so intuitively i can kind of like feel what strategy to do but um programmatically do we have a good intuition in terms of you know what to do and what not to do uh in this like mic very microscopic it seems like you cannot be very microscopic because if you're too microscopic right uh then you're definitely gonna hit a local optimum because the cool down thing is like it takes at least you know two steps it's like a combo action so if you only focus on like step by step action you're not going to capture that cooldown if you're making decisions based on you know step to step information you're not going to uh allow enough insight or information for cooldowns to optimize so yeah i think we still have to kind of like go back to more a larger scope of the problem and then look at you know globally how we can simplify it so that we can decide what is a good time to do the cooldowns can we build this membing into sub problems uh well if we cannot decide which days to cool down then we cannot break down and break them down into sub problems but if we know which days to cool down then we can basically break the problem into you know compartments into you know sections into smaller arrays because cooldown is almost like you know on that day the stock market doesn't go to work and everybody just stay at home uh and watch tv and whatnot so but the hard thing is to know to decide what are like the days where you definitely can perform your cooldown i mean if it's case one right that's like a free money in the bank because um if we have like a peak value there and we have like some price drop and then we have another price drop so yeah basically if we have any like down slope of lasting you know at least three days then we can use the you know the value at the middle of this the downslope as the um as the cooldown day because you know we're gaining by holding stock during stock rising like if we don't do anything during stock dropping that's fine i mean we only get money by riding the upward wave right the downward slide well you can do all the cool down you want doing the downward slides the hard problem you know is when you do not have those knives downward slopes that are you know that contains at least three uh elements so that is when you know you no more you no longer have those three cool downs and you have to make a decision so these are hard decisions to make and uh we basically need a somewhat localized way to judge whether it is a good time or a good idea to uh perform a cooldown uh during such you know brief drops right those back to back peak dip so or uh you know aka let's do an aka brief drop roof pressure up yeah these you know brief price drops are gonna be killing us because that is where you know any cooldown action needs further justification right so at those back to back peak to dip uh brief dry straps you know it's a brief drop um that is where you know we need to really worry about so you know during this entire you know up and down of a stock market um the only thing we need to worry about the only places we need to the only kind of like shape or terrain or geometry that we really need to focus on are those um back to back peak tip price drops so let's first identify those points right those are like the only places where we need to make a decision you know anywhere else the decision is self-explanatory and the decision is self-explanatory and the decision is self-explanatory and it's just straightforward i would just follow you know the by peak uh by bite dip and sell peak kind of like heuristic or we just use you know the crawling uh step-by-step uh step-by-step uh step-by-step uh very short-sighted decision very short-sighted decision very short-sighted decision um heuristic we can get it done but it's only when we have you know these back to back uh peak tip uh peak to dip uh drops where we have to make a decision right so what are the possible decisions here um so we either right we either sell at this peak and then you know skip the dip or we don't sell at the peak so yeah so i think this is how you can uh how you can categorize or separate them into cases you know a cell at the uh at the peak right so this is like uh this is a scenario where you actually sell at the peak right um the second one is where oh the second one is where you uh basically hold at the peak right so these are the two options we're just going to try to decide which action to take better at any of these like back to back peak tip uh pre-price drops uh pre-price drops uh pre-price drops yeah so that's like our new kind of like new revelation here uh right so let's just write it down okay the only places that require extra attention are the back to back uh peak dip drop uh short drops short price drops yeah one day yeah like one day price drops right two options two possible actions one is to sell at the peak right two is to hold at the peak uh so what do you mean if we hold at the peak um but if we hold at the peak shall we hold at the peak i mean uh yeah like if you hold i mean hold is the holder empty i mean right hold or empty those are two different things uh well because you were on a um previous if this is a peak that means the previous value is less than this current peak right uh so you could have sold it beforehand meaning selling here that way you can at least start buying at the new dip right that's something you know you either you know take advantage of the peak or you take advantage of the dip right that's kind of like a heuristic so instead of we say hold at the peak we want to all empty at the peak right because we only want those two things we don't want hole at the peak right let's just say that like say we never want to hold at any peak uh because i think it's just simply uh it's simply not optimal to hold at any peak you either sell it before the peak or you sell it at the peak but i mean i don't know how i can rule it out so let's just say hold at a peak is that still an option uh hold at the peak empty at the peak oh wait didn't we just say cd on the peak yeah if we see the on the dip that means we sell at the peak and then we move on right and if we cd on the peak so that we can buy it at the next dip then that means we must sell at the previous value but uh what if you know i mean who said you have to put a cd here right i think what i if you want to you know break something into two cases you want to make sure that those two cases are mutually exclusive and you know when combined they form the whole set of probability one so maybe instead of say cd on the dip maybe we should say no cd on the dip right yeah this is like how you separate cases no cd on the tip uh but it doesn't mean that you're gonna buy the dip right so it doesn't necessarily mean that you're going to buy that dip so this is a considerably more difficult case it sounds to me uh now we're going to have to consider you know quite a lot of different cases so choice one is what uh cd on the dip right choice two is no cd on the dip so now if there's no cd on the dip what we can do is we can no cd on the dip uh so we can does that mean we're gonna buy at the dip if there's no cd on the dip we would definitely buy on the dip right this does directly you know lead to you know buy on the dip by dip because if there's no cd on the dip why not buy it i mean right if you know it's a dip it's for everything afterwards the only right choice here to do and the best choice here to do is to buy the dip right so this deck directly leads to buy the dip but cd on the dip what does that mean it directly means we sell uh we sell on the top on the peak right on the previous peak so these are like direct uh direct inferences here because the only time a cd can happen is when you know on the previous day you had a dip oh you had a cell action so right so these two choices are now mutually exclusive and combined they form the whole probability of one so but what does this mean no cd on the dip it means by dip right if it means by dip does it mean anything about the peak buying dip it doesn't indicate anything on the peak right like we can if there's no cd on the dip uh we are free to buy the dip which we will do um then what does it say for the peak before do we sell that peak well because if we sell on that peak we definitely cannot buy on the dip anymore because the buy is going to be a cd uh yeah so what this also indicates right what this us what this also let me just uh remove uh this line here because now it's uh kind of like getting into our way so no cd on the dip this also means what um no cd on the dip this also means um there's no cell right there's no yeah there's no cell previously that's the one thing we can indicate we can inference there's no cell at you know at the peak so there's no cell so we don't know if previously we sold it or not but this just means that there's no cell so we don't know if we sell before that we just don't know about it okay we just don't know it just means that we don't know we don't sell here so these two cases are kind of like mutually exclusive now and they combine to make up the full probability of one uh what else can we infer from here so in the first case we do cd on the dip that means does it mean we buy anything later it doesn't mean that right it doesn't mean that actually it doesn't mean it doesn't directly indicate that so we need to be careful about what comes next about what you know could be said about these things this is yeah this is a little bit annoying i just want to remove that and put this back all right so it doesn't mean what that we're gonna buy next um right so these are the two cases it does mean that we're gonna sell at the peak and we're definitely not buying at the dip because we're doing it doing the cd on the dip but it doesn't mean anything about the it doesn't indicate anything about the action next to the dip it'll have its own logic okay it just means that um it just means that you know at this dip here we're empty right so yeah so that's something we know we are empty here we are empty whoops what did i just do we are we're empty here let me just write empty here we're empty here uh and you can either buy and you or you can just either you know sit back and pass uh add the step at the day on the day next to the dip so we are not against that uh does it mean like now you can treat this thing as a complete new problem because you know here we're not buying anything we're just letting the day pass through you know this is like a new sub problem does it look like it you know everything afterward is like a new sub problem right uh what about it's almost like okay we forget about completely forget about their past whatever gain we did in our past we just you know sit on it and then we're going to start a complete new sub problem and here if we buy here no cd on the dip no cell at the peak uh that means we definitely buy it in the buying the dip all right and um and if we're not selling here if we're not selling at the peak so we're holding on to it right well it doesn't mean holding up it just means we're not selling but uh um we could sell here or maybe we could sell somewhere else so it means that we basically cut you know this into like a sub problem right we just basically cut everything before this as a sub problem that we can you know solve uh separately right because you know it's this peak that had no selling so we can just ignore it you know cut that day and its value off at all because we're not doing anything whatever the price is or peak or whatever it is right so we can cut those into sub problems and just solve the previous sub problem um and what about the buy here so this is like buy this is a different sub problem it's almost like we definitely decide to buy and i mean the initial uh classical you know uh by buying stealth stock problem two it doesn't have such things at the beginning like you don't really buy at the beginning you don't know so how can we force you know this to look like the original classical problem um because you know because we know uh that we will definitely buy at the first dip in any uh in the classical you know stock problem too so maybe we can you know split this right at here right we can split this into a sub problem because if we take this as the first element and then because this is a the immediate drop and then we know this is a dip then we're definitely going to take the by action right so we just add these two together so this is going to be like our sub problem two and this is a problem one we just you know add them up right great so see if we can do that uh so for choice number one we're actually uh here we're just so we know that this is empty right it's a dip but uh we're doing cd on the dip so we're just sitting through the day the dip day uh we're not doing anything so that's why we can separate whatever comes afterwards as a new sub problem but what about what happened before uh well we knew that we did sell at the peak and if it was a peak at all then by treating whatever happened before as a sub problem will cause the algorithm to uh to actually sell at the end so we can treat this as a sub problem as well sub problem one and sub from two okay guys you know what we just cracked it i think the only thing we need to do now right is to uh find these back to back peak dip uh places and then we're gonna just cut the problem there and we cut at any of these back to back uh peak dip uh pick dip uh drop and then we're just cutting those uh cutting the entire array into you know sub arrays that's great so the only last question we're gonna ask ourselves is like how do we find such sub problems right um so we can pretend that we're like solving the classical problem you know until we see a uh until we see a um you know short drop like this when we see a short drop like this um we're gonna basically uh um when we say short drop like this we're basically gonna um say okay this is a short drop and uh short drop meaning that we have a dip right after a peak right whenever when whenever we see such a short drop we're gonna say hey this is a short drop and we're gonna just cash on what we did what we gained so far and we stop it there right we stop it there and we're gonna start again like this is where we start a new problem this is where we do the separation and we split this is like um yeah doing it one way or we can do it in the other way which is you know we split the uh the sub problem here in these two ways and we sum them up but then of course we need to combine the maximum between these two cases so we need to uh we need to split okay this is getting a little bit more again uh uncertain because we need to basically perform the split in two different ways and then we're still going to calculate um stop wait did we exclude this point there like you see in this sub problem here uh um can we just you know assign or you know just assign the this dip to either circle one or sub problem two um yeah i think we can include it into sub problem one because if the last um point is like a drop or we don't really do anything about it right so we're okay to you know i guess we're okay to include the um include the last point there we should be okay right so let's just uh say the sub problem one is gonna include the dip all right this up from one is gonna include the dip or so we're basically taking the peak and dip either in the first shop or take the peak and dip in the second sub problem yeah split them like that and then find the best um find the best way to split them basically yeah find the best way to split them um so what do we do about it um we're checking if this has you know yeah if it's worthwhile to include them include the peak and the dip and the left sub problem one right if it's worthwhile to do that so when we sweep from you know when we crawl or like do a for loop from left to right whenever we encounter such a sub problem so i know such a um back to back peak dip on drop we have two choices right choice one is we're gonna uh we're gonna include both the peak and the dip and then cut there cut it cut the problem there or we can just cut the problem right before the um the peak and the dip are they gave or are they gonna give us the same value definitely not because those are two different choices so these are like two different cuts right two different cuts of the array so we either cut it one way or we cut it in the other way it's about cutting cakes right now you're about you know we have on a higher level we have at each of these cutting points uh two choices of cutting the cake so um if we have you know m numbers of such uh decision points we have in theory um 2 to the power of m numbers of ways of doing it and each of these ways could this each of these combinations could uh yeah they could uh lead to a solution they could lead to a solution yeah it's i'm gonna say this time i'm going to give up because i think this is a little bit harder than i that i imagine and this heuristic that i come up with it does not lead to a is a quick solution because the way i try to split these things they lead to a high time complexity uh in terms of calculation so i'm just going to say our algorithm if executed is going to be uh it could be as much as you know 2 to the power of n it could be right and then in terms of uh time complexity uh space complexity or we may be on as well because yeah because i don't see it being 0-1 yeah because i don't see it being 0-1 yeah because i don't see it being 0-1 anyway this is like our best attempt here and it didn't really work so let's go back to lead code and take a look at some you know solution or other people's code wow this is a complete solution let's take a look at number three whoa where are we okay we're at the same place uh what is this description oh it's a different question um time to buy sell stack with cool down right let's go to the cool down the one with the cool down right so there's a series of problems um right from lead code dynamic programming into sub problems right uh recursion yep enjoy the ride okay dynamics standard program is state machine intuition let's first take a look at the uh at the complexity uh o fn of one that's good enough yet another dynamic programming all right so let's take a look at the first animated programming problem solution right approach one dynamic programming with state machine intuition first of all let's take a different perspective to look at the problem i like other than print problems here we treat the problem as a game and the trader as an agent in the game the agent can take actions that lead to gain or lose of the game points and the goal of the game for the agents to gain the maximum points make sense right in addition we will introduce a call a tool called state machine which is a mathematical model of computation later on we will see how the state machine coupled with the dynamic programming technique can help us solve the problem easily all right in the following sections we will first define a state machine that is used to model the behavioral states of the game agent then we will demonstrate how to apply the state machine to solve the problem all right definition state machine uh has a state it could have held sold reset so how is when you already are buying something you're holding on or you're sold or you are in the state the agent has just sold a stock right before entering this state and the agent holds no stock at hand okay it's like on the day of selling right reset is where there's the cool down so the agent holds no stock and not seller stock did not sell a stock before more importantly this also the transients stay before the halt and sold so it's the cooldown state after the sole state uh the agent can no longer immediately acquire any stock but they forced into reset state right so reset is like the initial state or something like that uh at any moment the agent can only be in one state the agent would transition into another state by performing some actions namely action sell the agent sells a stock at current moment um or a action buy right yeah you can sell you can buy um yeah or you can rest or take no action at all right so okay this is a state machine um nice so first you start from uh um reset right like start from initially reset and then if you buy you get into health and if you sell you're getting to hold but your next action is gonna definitely lead you to a reset uh right and then if you're in held if you rest you can still be inhaled yeah so this is like kind of like yeah a nice state machine representation notice that in all states except for the sole state uh by doing nothing we would remain the same state uh which is why there is a self-loop uh which is why there is a self-loop uh which is why there is a self-loop transition yeah right so deduction now one might wonder how exactly the state machine that we defined can help to solve the problem as we mentioned before we modeled the problem as a game and the trader is an agent in the game and this is where our state machine comes into the picture the behavior and states in the game agent can be modeled by our state machine right stock price and things like that given a list stock price our agent would walk through each price point one by one and each point agent would be in one of three states held sold and reset that would uh that we defined before and each point on the agent would take one of the three reactions which will then will lead to the next state as the net as the next price point now if we chain up each uh state at each price point it would form a graph where each path that starts from the initial price point and ends at the last price point represents a combination of transactions that the agent could perform throughout the game okay now we're talking about graphs from state machines interesting let's take a look we have a price okay that's the price chart um day one day zero day one day two day three day four and these are the uh states so what do they mean minus infinity um the above graph show all possible paths that are game agent walk through the list okay all possible transitions which correspond to all possible combination transitions the trader can perform with a given price sequence so see if we had like the first one here um if we are at sold which is uh quite unlikely because we cannot oh we can right like if we just buy and sell it on the same day right if we buy and sell it on the same day we will go into you know the cooldown or reset state and then we can either go to we can either take a buy action and go into uh go into held or we can just stay idle and go stay in reset right something like that uh and on the other hand if we just hold right if we just hold on onto the first onto the we just hold on to the first you know uh on the first day right if we yeah there's a because at the beginning i think we're in reset we cannot be sold we cannot be in hell because we don't hold anything so these are two like invalid states the only valid state at you know step zero or even before you know day zero is where we were in reset right and then we could choose to you know keep doing nothing and we still stay in this reset state or we can go to held by you know purchase this stock at uh at today's price which is one dollar and we get into that state health state yeah and then once we're in held we can either go to store or we can go to we can stay in health right okay now i'm standing starting to understand the sequence and what does those values mean the ghost to find such a path in the barcraft that maximizes the profits okay those these mean the profits right so if we add our start at the state of zero and if we pay the price of one to uh to hold this uh stock we're at you know profit minus one if we then sell it then we jump into plus one because now we have get a gain and we just you know cash that stock now we're at gain of one if we continue to and because we're selling it on day to day number one here uh on day number two here we have to cool down so that the profit stays and then on this uh on the day three on day three um we can either just hold on to it uh what does hold on to it mean like if we hold on to it um because we just sold it right like we sold it at uh day one so now on date number two we have to do the cool down so then um right and then we can only start buying on day three so if we do buy it uh because it's free right we're still at zero at a profit of one but then on the next day if we sell it we're going to have to prove profit three so here on this day if we just uh don't do anything after we sold it how can we go to the value of two i mean that's quite weird isn't it ah it's pretty weird because if we don't buy anything how come the disc goes from one to two yeah i'm a little bit confused in each nodograph we also indicate the maximum profits that the agent has gained so far in each state each stated stitch step and we highlight the path that generates the maximum profits don't worry about them for the moment we'll explain in detail how to calculate them in the next section okay algorithm in order to implement the above state machine we could uh define three arrays hold sold and reset which responds to the three states that defined before each element in the rate represents the maximum profits though it could gain at a specific price point with the specific state okay so you're talking about something like uh maximum uh reward to go right in terms of dynamic programming at each state for instance the elements sold to represents the maximum profits we gain if we sell the stock at the price point uh price two right according to this date and that's like on day number two right according to the state machine we defined before we can then deduce the formulas to calculate the values for these state arrays as follows soda i equal to hold i minus 1 plus price i how the i equals to max how i minus 1 reset i minus 1 plus minus price i reset equal to max of this and this here's how we interpret each formula so this is like a recursive uh formula for all three possible states um you could have used like uh one array just you know use different you know maybe uh one two three to represent you know each uh whether in each state or not um but uh i guess you could do this too right um in the previous state uh still can only be held therefore the maximum profit of this state is the maximum profit of the previous state plus the uh revenue by saying the stock at the current price how die in the previous state of how could we also held a does transaction or the previous reset uh requires a stock reset find the maximum profit and what are we doing here uh that's one good noticed above in order to calculate the value for each array we reused intermediate values this is where better diameter and programming comes into play more specifically we only need the intermediate values at one step before the current staff as a result rather than keeping all the values in the three arrays we could use a sliding window of size one to calculate the value of max solar and reset in the following animation we demonstrate the process out of how the three arrays are calculated uh by each step right this is like very typical dynamic programming but somehow i'm not seeing it somehow as a bright product we not only would we obtain the maximum profits at the end but we also could recover each action that we should perform on the past yes that's the optimal control law that we know what dynamic programming provides although this is not required by the problem in the above graph by starting from the final state and walking backwards um following the path we could obtain a sequence of action leads to the maximum profit at the end this is pretty cool uh okay complexity analysis time uh there yet you have another dynamic programming approach by the way um just for a quick summary i think this dynamic programming is really a pretty principle way of problem formulating it's just that i don't have you know i guess the patience today uh to fully understand this thing here so i'm gonna just skip it for now and take a look into the next one here uh in another dynamic programming intuition definition target function price cooldown price minus price plus mp what is mp maximal profit that we can gain for the price sub sequence from the index i right this is actually a pretty awesome way of formulating uh the sub problem as well yeah these two subsequences this might be you know similar to what we are doing but it's still you know a little bit complicated but then of course you're gonna have a time complexity of on2 which sucks and a space complexity to go in so definitely this is not something to learn but uh maybe we can take a look is a hard question for me this should be marked as hard i don't think i would want to work for a cup compound this company or interview insane difficult for interview questions state machine plus dp equals nuclear bump yeah i mean this is definitely not easy okay it's definitely not easy so i think what we're going to do when we come at this again is that we're going to really study this dynamic programming formulation plus state machine like state machine is basically a uh a transformation of perspective of this problem um i mean we kind of like was trying to transform our problem into a different perspective as well but you know trying to break the chain split the problem at those uh back to back peak pick dip drops um but we didn't make it through right like i mean this looks promising but then the number of things that we still have to consider after the split it seems like it's like an o two to the power of n problem uh rather than you know making it simpler so it's not a crisp split so to speak so uh we gave that up and we were looking at the solution and the solution is telling us okay you're probably gonna have to do a state machine um transformation of the problem perspective in addition to using dynamic programming this was kind of actually quite mind-blowing to me i mean this is mind-blowing to me i mean this is mind-blowing to me i mean this is definitely some a principled way of doing it but you know from the first round i also realized that there's something i don't quite understand yet so yeah i'm gonna probably take it offline now uh and then i'll um i'll digest this and then you know in the next video trying to um you know uh show you guys what my digestive understanding of this solution is and just make a video on it all right so um today we actually didn't submit any code but uh um uh well i will come back um just a few hours later you know you can still consider this as part one of today's challenge i'm gonna come back and i'm gonna uh finish this up i'm gonna basically digest this uh dynamic programming solution and then i'm gonna come back and solve it all right so this is part one guys i'll see you in part two
|
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,696 |
hi guys welcome to tech geek so today we are back with the daily neet code challenge problem that's jump game six uh that's basically lead code medium one six nine six question before beginning this i'd like to request you all please like share and subscribe to my channel in case of any queries any questions any issues with any upcoming placement sessions or any particular thing you'd like to know do let me know in the comment box i'll be there to help you out please join my telegram channel the link given in the description box to know about the new updates of any videos that's coming up if you want to like interact with me regarding any particular interview process then you can ping me there it would be easy and you'll get response within few hours itself so let's see what the question has now okay coming back to the question they say that you have been given a zero index integer are in numbers and an integer k so we have been given two things you initially you are initially standing at the index zero that's uh the first element we are standing okay i hope uh you can see now as we have to move okay so we need to see that in one move how many jumps we can make so in one move the integer k is the at most steps we can take that means it could be one to k any steps before without going outside the boundaries of the array now you must keep that in mind that taking k steps won't let you move out of the array so somewhere what you have to do is if you are at index i you can move from i plus one to minimum of these so i'll just let you know this afterwards so you can reach the last index and you want to reach the last unit so your destination is this you have a score okay your score is the sum of all the elements that's numbs of jail that you have visited when you jump so you have to sum up the elements and that would be your score you have to return the maximum score that you get let's see some example let me explain some let's see this is one we have minus one minus two we have zero then four then let's say it's seven and let's take one negative minus five and three okay so this is the array that's giving to you and they are giving you an index so sorry the number of elements so let's say the number of elements k here k is three okay so what does it mean initially you are at one okay now you have a score is the sum of all the elements visited so initially the visited sum will contain the zeroth element that's one okay now you have to see amongst the three jumps that's you among the next three elements you can jump on any one okay so what we'll do we'll take the maximum of this so what you have to do you have to take a sliding window kind of thing you have to check okay for us this is the first window from which we need to extract the maximum y maximum because we need to get the maximum sum so according to me or both are negative so this is maximum zero okay coming to the next maxim that's the next window now will be remove the first one and take the next one okay four so here maximum is four next let's come to the next window again we'll remove the first one and add one last one at last again maximum becomes seven now as we can see again we need to move we will remove zero take the next elements okay now see this way if you are born okay just keep that in mind in this way you are doing you are going wrong why because in the sliding window we remove the first and then take the next ones but if you do in this way now this is where the problem occurs that's what i wanted to tell you that coming from here you took seven as max again four seven minus five again seven is maximum so will you add seven again no why because that was visited once so this sliding window is not how we need to refer how this window would be slided let's see that i hope this point is clear like why we won't go over this one okay we began from here now we check the first step is again the same from one you can take three steps like you can take any of these steps you can take one two or three okay max is three until you reach the last so obviously here the maximum is zero now as you know the maximum is zero you won't take the sliding window like this now you will take the sliding window after four zero that's visited one okay that is what has to be clear so it will avoid a repetitive visits too now you can see from this the maximum is seven now this is visited so after this the node will be cut so here the maximum is and now from three obviously we cannot go anywhere and yeah in the second one we took a window of two because it was said we have to take less than this or like three or less until we cross this because if you take three then we'll move out of the boundaries okay this is what it was so while considering the sliding window concentration you need to keep that in mind that whenever you are going through this you should consider the elements that's the sliding window or your constraint path after the path that is visited and that should be either k or less than k from i plus 1 depending on the condition that it doesn't process so now coming to this line that was given that any index that is from i plus 1 to minimum of n plus 1 or i plus t so this is what they wanted to say either take minimum of i plus k this was 0 1 2 3 4 five six and seven okay so this was it now you are here that's three so you can go with three plus one that's four with 3 is k so i plus k that's 6 depending on this that n minus 1 and 6 which is less so obviously 6 is less so this is the window now coming to 5 i is 5 i plus 1 is but n minus 1 is 7 and i plus k is 8 so which is less 7 so that's where we'll pick the minimum of this so that's how you will consider the finger so what you do this with dp this is actually what we did we are creating kind of an array we are storing the maximum sum of that particular i index we'll keep that we'll add it in this way okay now let's see how this particular code will look like how the process is so what we'll do will create a score array that's tp we initially have zero one as i told you that you'd always consider the first one okay after considering the first one we'll do dq and uh we'll add the zero one again we'll check this now again pick up first and peak of last white you can see how we were going in forward okay why we are doing this because you know that q will store the index of the decreasing scores okay you can see q offered zero okay we'll uh store the index of the decreasing spots from i minus k to i minus 1 so we need to check this now get first which we are using this peak first this will give us the maximum score in score i minus 1 to score i'm uh sorry score i minus k that's how and in the last step we'll get the maximum result so this is actually order of n just a single traversal and you have your answer so if in case any queries with the solution any approach related issues you can let me know you don't need to make any particular case for the negative ones as you're taking out the maximum so maximum would be any of the numbers even if there are negatives then it would consider the negative maximum in the case i need to say like if you have a window of this so obviously the negative maxim here is minus one that will reduce the negativity and increase the sum okay i hope the solution is clear if there's any doubt please let me know comment in the comment box and do let me know do join my channel too if in case there are any queries we will be there to help you thank you
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
1,323 |
Hi gas welcome and welcome back to my channel so today our problem is maximum number 69 so what has been given to us in this problem statement, here we have been given a positivity in the name of wait in which what is there is only the digits and not those six and Nine is okay, what do we have to do, out of these we can change maximum one number, we can change one digital so that what we get is the maximum number, then look here, I have taken three examples, see what to do here. You have to make this number maximum on the right and you know that there are only 9 and 6 in it, so what will you do now, the obvious thing is that we will look from the left side as we go and see which six comes first, if six comes, then put it in 9. If you change then what will become of your 9969, then maximum you can change only one number, so now which one will you change, you will change the one on the left side so that what will you get, if you get the maximum number, then this is the maximum number you will get. Look in this example here. There is also a nine, we will not change it, because either we can change the nine, if we change it to six, then what will become the maximum, what will not become, it has to become the minimum, we will not do this either, we will not change this either, it is six, we will change it, so what about you? This will become nine, right, then look at this example, if you already have this, then it is six, no, do you want to change it? If you change six, then the minimum number will become not minimum, but this will become minimum, right, so what will we do here? How will we solve this problem, what will we do, it has given us this number waiting, okay, we have to change it, if we want digital change, then what will we do, we will change it in sting, okay, so I understand you in this example. What will we do in this, we will change it in the string and go from here, okay, from here the index will remain ours, we will see whether it is six or not, okay, we will move ahead, whether it is six, what is six, change it to 9 and from here, what do you do, return it. 99 69 Okay, this is done, it is not found even here, it is not found here, so finally what do you do, you turn this number to the right, then I show it in the code, it is quite edgy, so here See what we did, first we changed this number into string, you string function, your C plus is there in it, to change the string in number posting, it has been changed into string, now what we will do is we will check whether there is any character. If we get a six, we will change it to nine and break it. Here people will do it. And finally, what will we do with our string? What will we do with it? We will change it while waiting, so this is the function here, what should you do while waiting for the string? To change, you will attend it. Okay, I hope you have understood. If you like the video, please like, share and subscribe. Thank you.
|
Maximum 69 Number
|
maximum-69-number
|
You are given a positive integer `num` consisting only of digits `6` and `9`.
Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_.
**Example 1:**
**Input:** num = 9669
**Output:** 9969
**Explanation:**
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
**Example 2:**
**Input:** num = 9996
**Output:** 9999
**Explanation:** Changing the last digit 6 to 9 results in the maximum number.
**Example 3:**
**Input:** num = 9999
**Output:** 9999
**Explanation:** It is better not to apply any change.
**Constraints:**
* `1 <= num <= 104`
* `num` consists of only `6` and `9` digits.
| null | null |
Easy
| null |
1,302 |
People came to them welcome to the video only coding tips or again problem pain cold play list no more than 120 values for this deep sleep for example values for this deep sleep for example values for this deep sleep for example Video like and Share and subscribe the Channel Please subscribe and subscribe the Thursday switch off the The Subscribe and subscribe the Channel Then A You Know That It Gives You Samudra Notes Long Schezwan To Return To Give An Initial Email Account Variable Battles In 10 Ok And Start Working And Person Data Structure For The Giver Tips And Chappal Sandals Le Number 90 Veervar No Veer Is The Children Two Three One Two Three Children Live With To The Point When You Have No Clue E Wonder Dip 100 From The Beginning Isse Track Number One Navya Two Children 2310 Exchange The Notes In Giving To Check For Children To Children Below 6 Points To Do That Thing For Child 666 10.22 M Not Just Your Life But Nose Pin Hai Navel 10.22 M Not Just Your Life But Nose Pin Hai Navel 10.22 M Not Just Your Life But Nose Pin Hai Navel Chakra Children For Preserving Su Child Witch 70 Voice Rose Level Number To 9 Add Text Labels To Next 20 Years Child Officer Wing Child Which 700 Have Any Thought And Action Point Then Okay Techie Discretion Firing Directional IS Not Have Any Children Actually With Values Which Can Children Actually With Values Which Can Children Actually With Values Which Can Stop Pocket 2018 The Can Go To The Next So Let's No Distinction In Child It's Been Shot This download blue at any point 6 and preventive accounts with remarkable contact with them equal than one year and third level from Begusarai to children but all children of seven internal ho that winters one pad 2018 those children also selected for 2019 Ashwamedh Loop Slow Work You Have No Clue Do Maximum Do Bluetooth Class Chemistry Li BDO Vinod Ji How To Check The Notes Take Now 200 In The Last Not The Number To Computer Against State Bank Account - 110 In The Last Not The Return To Subscribe Now To Your Data Subscribe Pankaj on P-notes in detail ever this note Pankaj on P-notes in detail ever this note Pankaj on P-notes in detail ever this note more than this Name of the curious from now on Cigarette molecule Okinawa can do cycle declare account pimple 16 same quantity 120 nm going to confirm the first features must subscribe our video the mode on inside every time I was not sure what is us for example for all elements in the very first time element to question awadhi to or search for this letter right side 100MB to take current se plate mean equal and nutrients to new note and difficulties to currency notes issued after example For example it is not one ok according to choice children is new note select channel subscribe now to receive new updates face a requires bluetooth settings and right so they can give in place of fans give right you can give nude ride point mintu various dasharath Son of Stuart Pearce asked in tension why is the final Vikram Mantu and Snow White and the First President and finally after all they can just give the thing again until the last lesson - topi ke ki - topi ke ki - topi ke ki android platform oil condition I will give volume chart so this bank account - give volume chart so this bank account - give volume chart so this bank account - Let Me Clear Another Cute Little But Its Contribution To Let Me Love You To The Tree Again From Which Country In The World - 121 In The World - 121 In The World - 121 A Cute Ancestral YouTube At Any Place Of Countless Presence Can Give Star Plus Website Suna A Final Note 700 Mike You To Family After All E Side Reaction Science Notes 80528 The Valley Of Events But How Can The Second Do It Even Vari Vanditam * The Second Do It Even Vari Vanditam * The Second Do It Even Vari Vanditam * Returns And Subsequent Events Of India Can Give Returns Subscribe Drop Cube Solve Oil Note Of Latitude 29 2010 Activists And Journalists Who Can Give The Statement Free Mode That Star And Ritz In Nude Equal To On A Cute Boy Friend So First Time Income Tax Note 7 The Types Of Cancers Editing 100 Plus Equal To New Notes Well In This Point Notes First Time Is Insult 7 Question Different Modes 797 Systematic Swelling Prevented Thum S Naipaul There Note Selector Magh Month Election Committee Come Seven Plus Seat Vijay Ko Entries Updated Research Cute Vikram Se Zzz Term Europe Rid Of Thum For International In This Pregnancy Its Surface Yesterday Morning Rustam Roy That His So In Flying Jatt Versus amazon school admin to back end if not even assembly school near so let's check the same thing it nh-24 final in a storage space fine leg when vitamin C again setting on think it cut solution rectification wrestling
|
Deepest Leaves Sum
|
delete-characters-to-make-fancy-string
|
Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 100`
|
What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.
|
String
|
Easy
| null |
452 |
welcome to Sheba code in this video we will solve a leak code problem in under three minutes the problem is as follows we have a list of number pairs representing Balloons with each pair representing the range on the x-axis representing the range on the x-axis representing the range on the x-axis where the balloon is located specifically for each balloon we are given two numbers X start and X end which Define the range where the balloon lies our goal is to burst all the balloons using the minimum number of arrows here an arrow can burst a balloon if the range of the balloons location includes the arrow to solve this problem it's important to remember that every balloon must be burst eventually at some point and that the X end value of each balloon can be thought of as the last opportunity to burst it with an arrow using this information if it's possible to burst a group of balloons together the last opportunity to burst them all is simply the minimum of their X end values which is equal to 3 in this example therefore if the balloons are sorted by ascending order of their last opportunity coordinate X and it's optimal to iterate through them and greedily burst each balloon at The X end point if it hasn't been burst yet consider the following simple example here we start bursting the first balloon at its X and coordinate for the second balloon we can see that it has already been burst and don't have to do anything moving on to the third balloon it is not burst yet so we burst it again at its X endpoint which is six we can skip the fourth balloon because it has already been burst finally the fifth balloon has not been burst yet and requires another arrow overall the minimum number of arrows required to burst all the balloons in this example is three let's take a look at a C plus implementation if there is no balloon we can simply return zero otherwise we surf the balloon's array by the ascending order of their X and value we start by bursting the first balloon at its X endpoint since it has the minimum last opportunity point and we want to burst as many other balloons as possible therefore we initialize the number of arrows as one and the last arrow point as the first Berlin's X and value we then iterate through the array for each balloon we check if it has already been burst by comparing the last arrow point with the current Berlin's starting point if it has already been burst we do nothing and Skip otherwise we reset the last arrow point to the current balloons X and value and increment the number of arrows I hope you found the solution we presented helpful and easy to understand if you have any questions don't hesitate to leave a comment below
|
Minimum Number of Arrows to Burst Balloons
|
minimum-number-of-arrows-to-burst-balloons
|
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Medium
|
253,435
|
211 |
hi guys so in this video we'll take a look at problem which is related to tri data structure now tri data structure is a quite unique data structure in a way that it's not commonly used like especially in colleges and courses uh we come across data structures like stack linked list queue array and we don't come across try much so that's one point and then other is uh if we are interviewing for companies like fang and all that then they expect us to know the tri data structures so that's why it's kind of special or kind of different from other data structures and if you're interested in knowing what are the real world usage of try then applications like auto complete or spell checker or few kind of word games they really like tri data structures and they really use that so having said that today we'll be looking at problem design add and search word data structure so this obviously just says that use tried researcher uh in real interview will not be told like okay use trading structure and solve this so just keep that in mind so one more thing about this problem is this is really popular in facebook interviews and amazon interviews more so in facebook interviews and i'll tell you a secret this problem was actually asked to me in my amazon interviews so let's look at the problem description and then we'll see how this data structure works and how we can use it to solve this problem okay so this is actual problem description in this problem they're asking us to design a class word dictionary and this class just has two methods ad word and search word so let's look at this example so in this example they're calling adword three times so bad and mad those are adword calls and then four search calls obviously search for pad would return false because it doesn't exist search for bad would return true so this is simple but the actual complex part is in the search word they can give us dot now if you know regular expression dot can match any word so that's the complex path and that's where tri data structure shines out now search for dot 80 will return true because that can match any of the three word remember dot can match any letter and a d will match a d and then search for b dot should return true because that can match bad so that's the whole problem so what we'll do is we'll understand how we can design tri data structure and then we'll try to implement in code okay so before going into solving this problem let's first take a look at the triad definition so a typical tribe definition or class would have children array so that'll be like in case of lowercase characters will have 26 characters so we'll have a children array of 26 and then we'll have a marker to say that this is the end of the word kind of thing so in this case we have a boolean now remember that there can be variations of this uh class so the basic idea would remain same but let's say that if we have to have more characters as in like lowercase characters uppercase characters or numbers or all those things then instead of this uh tri array of 26 children we can have a map which will have key as character and then value as the try data structure so that's one variation now in our current problem our search method requires us to return true now imagine a case where search method requires us to return a word or the list of words that match the search so in that case instead of this end of word marker will have the string word itself at the end so when we reach to the end of the word we say that yes this is the word that we matched and then from search method we can return that word so that's another variation of try and in fact there is a problem on lead code which deals with finding xor of all the numbers in array and the hat uses tri data structure and in that case the children array size will be 2 because it will be holding 1 and 0. but anyways that problem is for some other day right now we'll just deal with this word problem so now we'll actually see how our try class performs when we start pushing words into it so we'll take words like mad mars bad and dad and then we'll see how our try spans out when we add those words one by one so let's start with the word mad first so before anything what we do is we have our root object which is obviously of type try now it has 26 children so 0 to 25 and now we'll take the first letter in the word mad so what we'll do is all of them are null and we'll go to this letter m which is 13th character in a to z so we'll initialize this 13th child in the array and we'll create a new try object at that instance by default our end of word is false so we'll just keep as is now this will denote that we have a word with letter m in our try now we'll move on to this new try object that we just created the children of this root object 13 children and in this try object which itself will have 26 children will denote the letter a over here by creating new tri object at zeroth position so that'll denote that there's a letter a and again end of word will be false because we are at letter a now in this a letter or in this try object will denote letter d by creating new try object at fourth position so that'll denote that there's a letter d so rest all the children in the arrays are null except m a and d over here and in this last try object all the children would be null the only thing we will do is we'll mark end of word as true so that'll denote that this is the end of the word mad so if we come here while searching return true and say that we found the word so that's how our try will look like if we add word mad okay so now into this root object or into this tri data structure we'll try to add second word which is mat so now we start with root and we say that okay go to this 13 children which is m and if it's empty then create a new object otherwise just use that so because we added mad there is already a try object so from root we just navigate to this try object now because we already have a we'll just navigate to this try object instead of creating a new one so we are repeating m and a because mad and matte they both have m and a so we'll keep them same now into this third try object which is the children we already had d and we created neutral object and we marked end of word true similarly for t we'll create a new try object and we'll mark end of word true so for dnt we have new try object with end of word as true and remaining all the children's are null so that's how we'll say that okay this tri data structure has mad and matte so when we search for those will return true so just like this let's quickly add the remaining words which are mars bad and see how our complete tri data structure looks like okay so this is how complete tri data structure will look like so let's look at the mars path first so just like mad and matt we already have m so we'll just navigate to that try object again we see a we already have that try object so we'll navigate to this and now we already have a dnt so we'll create a new object for r now we'll navigate to that new object try and we'll create an another new object for s so this will again be a neutral object and now over here we'll mark end of word as true because that's the end of mars now likewise for bad and dad we'll go to the root object we'll create new object for b for bad we'll go to the try object we'll again create a new tri object for a we'll go to that we'll again create a new object for d and for that try object we'll mark end of word as true and similarly for dad we'll create a new try object for d a d and then we'll mark end of word as true so this is how we add words into try data structure so now let's quickly write the code for this adword method and then we'll come back and look at the search part of it okay guys so this is our code for adword as we discuss we have our try class with array of 26 and then boolean for end of word and then we have adword method in this we have our root object which is of type try so we always start with the root object we mark our current as root and then we navigate to each letter in the word so if that letter in the current try object or if that index in that current try object children array is null then we create a new tri object and then we mark our current as to that index or to that children and then we keep moving to the next character and likewise if we think of mad we'll first build m then a then d and then at the end we'll mark end of word as true and likewise we'll repeat for each word so that's how we build tree like structure for our tri data structure so that's all about adword now that we know how drive works and how we push words into it we'll look at search method and since we have already built the data structure it's pretty easy to search in that data structure but let's see how it works and then come back and finish the code for that also okay so now with hard part of building tri data structure done we simply need to search into it so this is the easier part so let's see how we'll do that so for example let's see if we have to search mad into this try data structure so we'll start with the root we'll look at the 13 children which is m is it initialized yes so we'll go to that object we'll look at letter a which is zeroth object has it been initialized yes so we go to that object now we look at the fourth object in the children which is d has it been initialized yes so now after coming to this try since our letters are done we look at the end of word property is it true yes that's true and then we return true from our search method saying that yes mad is there in this tri data structure so let's look at a negative test case where the word doesn't exist let's search man in this try so similarly we'll start with root we'll look at m it exists so we'll go to that try now a it exists we'll go to this try and now over here we'll try to look at n if the try object or if that children has tri object now we'll notice that it's null so since that is null we say that n doesn't exist and we return false for from our search method saying that man doesn't exist so that's how the negative search or the false will return so that simple search now let's look at a search with a dot word in it so let's say if we have to find m a dot so whether the word mad or mat they all will qualify for m a dot so let's see how that'll work so we'll start same we'll go to m then we'll go to a and this is our a try object now over here we have finished letter m we finished letter a we're at dot now dot means we can match any letter now in this case for dot we look at all the children's which are non-null so in the children's which are non-null so in the children's which are non-null so in this case will be d r t and we say that all of you are valid children so i'll go to all of those objects and try finishing my search so we'll go to d so m a dot so dot matches d and we'll go to the star object and we'll see is end of word true because we are done with all the letters so this will return true so technically we can return true from our search method for but for the sake of this example let's continue now for r we'll go to this try object and since our letters are done we'll look at end of word property will not look at s or will not look at the next try because m a dot our letters are done now this end of word says false so we'll return false from this try or from this search and likewise for t we go to this object we look at end of word it's true so we can say that yes mat also matches m a dot so likewise we can say that mad and mat they both match m a dot and m a r s doesn't match m a dot so this is how we search in our tri data structure so let's go back finish the search method and then submit and then run the code okay so this is our code for search method in the word dictionary search we simply call the search method in the try class and we pass all the letters in the character array and we pass the starting index as 0. the reason why we have character index over here is because we can recursively call the same method at different positions so we'll see why so we start with the current try object and we loop through each character so for now let's look at simple characters so let's think of example mad so if you are searching for m we look in the current children at the respective index if the try object exists we mark our current to that try object if it doesn't exist we return false saying that this word doesn't exist so that's a negative test case so for simple search m a d mad will keep navigating to the current pointer and once we are done with all the letters finally at the end we look at the end of word property if it's true we return true if it's false return false or if it's null then also will return false so having said that now let's look at the logic where dot comes in the character so think of our example m a dot now we have done a now dot com so in the current try object we look at all the children's and for the children's that are not null we repetitively call the search method recursively called the search method and we say that start looking for the next character so dot has matched the current character which is not null and start looking for the next character and if you find the complete character list and if you're returning true then we'll return true from this method so that's how dot works so that's all about the search and add in the word dictionary using try data structure so let's submit the code and let's make sure that we pass all the test cases so there you go we pass all the test cases with this code so this is java code i also have c sharp code both the version of code are readily available for you guys the link is there in the description box you guys can go to the github link and then take this code and run it so that's it guys i hope you guys understood how try data structure works and you guys can use it in different various applications so if you guys like the video give me a big thumbs up and subscribe to the channel it really helps me out and if you have any feedback any suggestion positive negative anything just let me know in the comments box i'll try to respond and that's it guys keep on practicing keep on coding and i'll see you in next one
|
Design Add and Search Words Data Structure
|
design-add-and-search-words-data-structure
|
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the `WordDictionary` class:
* `WordDictionary()` Initializes the object.
* `void addWord(word)` Adds `word` to the data structure, it can be matched later.
* `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter.
**Example:**
**Input**
\[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\]
\[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\]
**Output**
\[null,null,null,null,false,true,true,true\]
**Explanation**
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord( "bad ");
wordDictionary.addWord( "dad ");
wordDictionary.addWord( "mad ");
wordDictionary.search( "pad "); // return False
wordDictionary.search( "bad "); // return True
wordDictionary.search( ".ad "); // return True
wordDictionary.search( "b.. "); // return True
**Constraints:**
* `1 <= word.length <= 25`
* `word` in `addWord` consists of lowercase English letters.
* `word` in `search` consist of `'.'` or lowercase English letters.
* There will be at most `2` dots in `word` for `search` queries.
* At most `104` calls will be made to `addWord` and `search`.
|
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
|
String,Depth-First Search,Design,Trie
|
Medium
|
208,746
|
938 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 938 range sum of a bst let's read the question prompt given the root node of a binary search tree and two integers low and high return the sum of values of all nodes with a value in the inclusive range low high so if we were given this tree here as an example and we were given that low equals 7 and high equals 15 then we'd want to return 32 how did we get 32 well essentially what we want to go do is go through the entire tree and then find the values that are inside this range and add them all together so let's go through this and do a naive solution to this problem so you know we'd start at the root is 10 between 7 and 15 right that's the range that we're working with okay is 10 in that range yes it is okay so now we can go into the left subtree is five in that range no it's not so we can't consider it okay let's go to its left okay is three in that range no it's not so we can't add it what about seven uh we're allowed because it's inclusive so seven would work so we'd wanna add seven to our sum then we can go into tens right subtrees and then we see okay 15 is that in the range yes it is um because it's inclusive okay so we've identified that we need to add 10 15 and 7. so when we do that we do 10 plus 7 plus 15 we see that we get 32 so that's how they got the solution there right so that's 32 well okay so that's the naive way to do this where basically we just go through the entire tree and check every single node is it within the range and if it is no problem the reason why this isn't the best solution is because we're actually given a binary search tree so there's no reason to check every single element now if we got to this 5 here we know that the property of a binary search tree says that every element in its left subtree must be smaller than you know the parent node so if we knew that 5 wasn't able to work then there's no point of checking anything inside the left subtree because all these values would be less than 5 and if 5 didn't work then anything less than it won't work and that's why we can just skip the left subtree and we could have drawn directly to this right subtree so we can use the properties of a binary search tree to actually cut down our search time and instead of checking the entire tree we can you know make use of the fact that it's a binary search tree and cut down our search space and therefore not have to check every single node let's go to the code editor and see how we might implement this in code okay we're in the editor let's write the code for the solution but before we do i think it's important to mention that this problem can be solved either iteratively or recursively now the choice of what solution you choose to go with is entirely up to you but i will caution you and say that in most real world scenarios you probably aren't going to be shipping recursive functions into production obviously if you make a mistake and you have some sort of infinite loop your aws bill or whatever cloud provider you use is going to be massive so typically you want to use the iterative solution and i would recommend writing the iterative solution for whatever problem you encounter that can be solved either iteratively or recursively that being said we will go over both solutions just because a lot of the times your interviewer may say okay i see that you solved it the iterative way can you write the recursive solution so it is important to know both but if you had a choice i would always solve it with the iterative solution and explain to your interviewer that you know we have the potential for overflow if you know our stack gets too large and that's not really something we want to do so for safety you know we'll stick with the iterative solution um okay so let's write the code so the first thing that we need to do is check what happens when we're actually given an empty root in this case you know we can't sum anything if we don't have anything to sum over so we would just return 0 here so we're going to say if not root we can simply return 0. otherwise let's define a variable to store our result we're going to say ands equals 0 and we need to stack since we're going to be doing this iteratively to hold our kind of recursion here pseudo recursion so we're going to say while stack we're going to say the current node that we're working with is going to be stack.pop and what we want to do is we stack.pop and what we want to do is we stack.pop and what we want to do is we want to check whether the node we have is um you know within the range that we need to sum over so we're going to say if low less than or equal to node.val less low less than or equal to node.val less low less than or equal to node.val less than or equal to high we're going to whoops we're going to add that node value to our answer so we're going to say ands plus equals to node val now what we're going to do is we need to check whether or not we need to go into the left subtree remember from the diagram if the value uh is greater than uh the left uh sorry if our value here for node.val is greater than node.val is greater than node.val is greater than low then that means that we're allowed to go into the left subtree if it's too small already then there's no point of checking the left subtree because the property of a binary search tree is that all values in the left child are going to be less than you know the current parent node's value so we're going to say if low is less than node.val node.val node.val then we're allowed to go into the left subtree so we're going to say stack.append stack.append stack.append node.left node.left node.left and we're going to do the exact same thing for the right so we're going to say if node.val is actually less than say if node.val is actually less than say if node.val is actually less than the high and then we're allowed to go into the right subtree so we're going to say stack the append node dot write and actually one thing i forgot to do is that we may not have a valid node here so we're going to actually say if node because it could be the case that we append a node uh dot right that or in node.left it is actually null so node.left it is actually null so node.left it is actually null so obviously if we try to do these checks on something that's null um it will you know blow up our code so we actually have to make sure that node is uh non-null here so apologies for that but non-null here so apologies for that but non-null here so apologies for that but we seem to have fixed our mistake cool so we have that and then at the end all we need to do is simply return our answer let's submit this and double check that it works and here we go cool so that works that is the iterative solution um it is in the worst case we need to sum over the entirety of the tree so you know we could be given a low that is like you know this integer minimum and then the high would be integer max then we have to sum over everything in our uh tree so in that case you know we'd have a big o of n runtime and then since we're using a stack here basically um you know the stack could potentially end up holding um you know all the nodes so it'd be a big o of n on the um space so that is the iterative solution now let's code up the recursive solutions let's just wipe everything except the root check can stay and okay so we're going to do this recursively so i'm going to just define a helper function here we're going to call it dfs we're going to say def dfs and we're going to say self oops no sorry this won't be a helper this will be outside yeah so we'll say def dfs so this will just be a method here on the class solution we're going to pass in the node low and high and we're going to say if node we're going to say basically going to do the exact same thing we did before so if low less than or equal to node.val so if low less than or equal to node.val so if low less than or equal to node.val less than or equal to high then we're going to say self dot we'll just call it range sum or we can call it answer it doesn't matter and we're going to add to it the node.val node.val node.val and then again we need to do the checks for the left and the right if we're allowed to go into those trees so we're going to say if low less than node.val then we're going to say node.val then we're going to say node.val then we're going to say self.dfs into self.dfs into self.dfs into the left subtree passing low and high and then we're going to say if node.vowel is less than going to say if node.vowel is less than going to say if node.vowel is less than high then we're going to go into the right subtree so we're going to say node oops node.right node.right node.right low high and that's all we need to do for the dfs function now let's define our function for the answer here so we're going to say self.range sum self.range sum self.range sum equals zero and then we're going to call our dfs function on the root pass in low high and then at the end all we need to do is return self.range sum self.range sum self.range sum and let's submit it double check we didn't make any bugs cool uh so the time complexity of the recursive solution is still going to be big o of n right we could potentially need to touch every single node in the tree so that's not going to change uh the space complexity is actually also going to be big o of n and the reason for this is even though we're not defining any extra you know space for the you know storing you know the stack like we did iteratively uh we do have the implicit space used by the actual recursive stack so we do need to count that and consider it um as you know big o of n uh space so for both the iterative and the recursive solutions we're looking at big o uh big o of n runtime and also big o of n space so that is how you solve a range sum of a bst i hope you enjoyed this solution if you did please leave a like comment and subscribe check out my other videos if you're preparing for on-site interviews and preparing for on-site interviews and preparing for on-site interviews and happy coding
|
Range Sum of BST
|
numbers-at-most-n-given-digit-set
|
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`.
**Example 1:**
**Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15
**Output:** 32
**Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**.
| null |
Array,Math,Binary Search,Dynamic Programming
|
Hard
| null |
933 |
welcome to october's leak code challenge today's problem is number of recent calls you have a recent counter class which counts the number of recent requests within a certain time frame implement the recent counter class now recent counter initialized initializes the counter with zero recent requests and ping adds a new request at time t where t represents some time in milliseconds and returns the number of requests that has happened in the past three thousand milliseconds or three seconds specifically return the number of requests that have happened in the inclusive range t minus three thousand t is guaranteed that every call to ping uses a strictly larger value of t than the previous call so that makes it a lot easier now we could look at this example here we initialize our recent counter it's going to return nothing because it's going to be an empty class of some sort and we ping it at one time second and we'll just return one when that happens because that's obviously the first one only has one request in the last three seconds now at 100 milliseconds we have two in 3001 we have three but in 3002 we only have three because the range now is from 3002 to 3002 and this one that we made at the millisecond one no longer is within that range so what's the best way to do this i think the best data structure to use here would be a cue just like the picture here we can just initialize some sort of cue append every single request to the right and what we'll do is have some sort of loop where we'll pop off the ones on the left that are no longer within this range that way we can keep track of everything that we need historically and once we get rid of it we don't really care about it anymore because we are guaranteed that these t values will always be or these t values will always be greater than the last one all right so let's do that let's first initialize a q right here we'll call that q and use python's dq there and what we'll do is when we get pinged we'll take our t and we'll first add that to a queue right and that and now we need to pop off everything on its right so while there is a queue while there's anything inside rather and self.q the very first one self.q the very first one self.q the very first one is less than t minus 3000 that's the case we want to pop it off the very first one so we'll do a pop left and then we can just return the length of the queue now to make it a little faster we can just initialize like a count right here and i'll call that self count zero and we'll use this to kind of keep track of how many pings we've been given uh that way we don't have to like calculate the length every time in case it's like really large and expensive so right here we'll just subtract count and this just keeps track account and really all we need to do is return that so make sure this works looks like it's working let's submit that there we go accepted so that's it thanks for watching my channel and remember do not trust me i know nothing
|
Number of Recent Calls
|
increasing-order-search-tree
|
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`.
| null |
Stack,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
| null |
1,020 |
hello and welcome to lead programmer today we are going to solve the question number of enclaves so we have a binary Matrix grid binary Matrix means the Matrix consists of only 0 and 1. here 0 represents a C cell one represents a Lancel now they have defined a move so what's a move so let's say we are at this Lancer so from this land cell we can either go right we can either go left we can either go down or we can go up so that's a move but a valid move would only be from one land cell to another land cell we cannot go from one Lancel to water cell or from a water cell to a land so that's not a valid move now the objective is to return the number of land cells in the grid for which we cannot walk off the boundary in unlimited number of Moves In unlimited number of moves so how many other times we move we shouldn't be able to walk off the boundary so let's look at the example one so if you look at this particular Lancer we can easily walk off the boundary right if we look at this land cell okay from this Lancel we can either go to the list answer from here we can go here but then we are stuck right uh there's no possible move uh in this particular cluster using which we can go off the boundary hence the answer over here is three because for these three cells we cannot walk off the boundary no matter what so if we do a breath versus a depth first search here we do not reach the boundary if you do a breath versus dip so search here we do not reach the boundary and same for the cell hence the answer over there is three let's look at another example over here if we do a breadth first search here we can easily Walk Off The Boundary same applies to this case same applies here so if you do a breadth first search adapt for search here we can walk off the boundary if you don't do a depth first of breath first traversal here we can also Walk Off The Boundary so hence here the answer is zero because for all the cells we can walk off the boundary but the objective is to return the number of cells for which we cannot walk off the boundary okay so now that we understand this let's look at what uh the way of solving this should be it is kind of uh hinted from the way I went with examples so we just go through the entire grid and we care only about the land cell so if you encounter a water scale we just skip so we just skip all these and if we encounter a land cell okay for the land cell we do a depth search traversal or a breadth first traversal it doesn't matter any type of traversal would work but if we reach the bound if we reach off the boundary or we reach the boundary during the traversal then we know that particular cell will not be counted in the solution because we can walk off the boundary so if you do a depth first or breadth first search here we know we can walk off the boundary hence it's not counted in the solution uh in this as we saw before it's if we do a depth versus such we cannot reach the boundary and hence it's not counted in solution uh so that's one solution that's one way to solve it so we just keep doing breath first step of search for each land cell and keep track but I like another way which is a smarter way to look at this question it's a different way of viewing the question so let's reverse our thinking let's go to the smarter way let's reverse our thinking so one thing we notice is for all the boundary cells so these cells refer to the boundary cells for all these boundary cells we can walk off the boundary so uh all the boundary cells from all the boundary cells we can walk off the boundary now if from a boundary cell we can go to an internal cell so I'm referring to all the cells which are not boundary cells as internal cells so if from a boundary cell we can have a valid move to go to an internal cell then we know that internal cell can also reach the boundary in any number of moves so if we encounter a land cell in the boundary then we tried a depth first or best first search from that cell and all the cells that we encounter cannot be considered in the solution because we can walk off the boundary from all of them so in this case if we do a breath first or death research we just stay here so that's fine but we know this Builder cell is not counted in the scenario and that's it because all others are water cells and we do not care about the water cells so we ignore them and at the end we know that we just have these three internal cells remaining so that's the answer whereas in this question we see okay as soon as we encounter this Builder cell we do a depth first search and we encounter we reach all these cells and we know that all these cells will not be included in the solution because we can walk off the boundary from them so essentially the idea is we start from the boundary cells for each boundary cell uh which is a land cell at the boundary we do a depth first or a breath first search and all the cells that we encounter during the traversal we convert them to water cells because we don't care about them we do not care about them in the solution after that's done for all the boundaries uh land cells at the end we just count the number of remaining land cells in the solution so for example in this case if we do a depth for search we convert this to a zero and at the end we just count the number of remaining um land cells how many lances are available none so the answer is zero so let's see how to implement the smarter way because that's easier to implement um add faster much faster so if you have a mean function number of enclaves we have a result variable and that's the one we returned it keeps track of the number of land cells uh we just represent water and land by zero and one we go through the entire grid and we care only about the land cells so that's the check we do first and another check we do is we only care about the boundary cells so we see if uh the cell lies at the laundry how do we check that so I represents the rows so if it's the zeroth row or if it's the last row that's I equals 0 or I equals the length of grid minus one or the column it's the zeroth column so J is 0 or it's the last column so that J is length of Grid at 0 minus one so if that's the case we call either a BFS or DFS and that BFS or DFS will change the grid and appropriate land cells to zeros for now let's uh let's assume that's good so after all that is done after this block is done we move on to this block where it's pretty simple we just go through the grid and count the number of lancels we increment rests if we encounter a Lancel and that's what we return at the very end so now look let's look at both BFS and DFS so I'm assuming you guys know what uh bfsdfs is like a general idea of it and how to basically implement it let's quickly walk through the base uh through a quick idea of what BFS or DFS is so uh let's say we have a graph like this so a DFS on this particular graph would be okay we first come here then we come here so we explore the depth first and then we might come here so we first go to its depths first and then explore the rest so that's what depth for search is now let's do the let's do a breadth first search on the same example so this was the example that we had for a breadth first search we essentially start here okay so this is the first note now we go through all its neighbors you want to explore the breadth first so we do two three four so we explore its neighbors first so we explore the bread first and then we move on to the next level over here so that's the general idea of breath first and depth research great let's look at the depth first search solution first so we pass in the grid we pass in I and J uh I and J was passed here that's the location of the land cell we are running the DFS on and then we just pass how land water are represented uh so if the cell that we encounter is not land if it's water then we don't care about it we just return but if it is land then we want to convert it to water because remember uh for each selfie encounter it cannot be in the solution because for that cell we can walk off the boundary hence all the cells that we encounter during our traversals should be converted to water as stated earlier so we convert the land cell to a water cell here and uh then we wanna explore the neighbors of that particular cell so first uh and we want to ensure that those neighbors are valid for example let's say we are at the boundary where I is 0 so we cannot pass in I as negative one because that's an invalid location so we're going to check if the index you're passing is valid so for that we do here we check if I minus 1 is valid and then we call the DFS we do a recursion we call the function again if not we just don't same thing for I plus 1 uh same thing for J minus 1 and J plus one and we do the same thing and we pass in the indexes as appropriate and that's it that's the DFS solution let's also look at the BFS solution which is very similar but I have implemented it in a bit of a different way let's look at so uh breath first again we explore the breadths first so we go level by level so we explore so if we have a cell we look at all its neighbors first and then the neighbors of neighbors and so on great now so how do we Implement a BFS we do it using a queue so let's first populate the queue by the starting indices so we put in I and J so while the queue is not empty we look at a level there we for we pop in the index so a represents I and B represents J so we first check if the obtained index is valid so we do it by H bigger than equal to zero Bish to bigger than equals zero a should be less than the length of grain and B should be less than the grid of zero so we do that and we care about if the grid is a land cell or not if it's not a Lancer we just continue we just don't care about it and if it is a Lancel then we convert it to a water cell and if it is a Lancel then we also care about the neighbors of that land cell hence we come here where uh we just have an array visitor and uh we have all the neighbors here so a minus 1B uh a plus one b a b minus 1 a B plus ones all these are the neighbors of A and B uh we just put them in an array called visitor and um we just append all other elements in that visitor we could have also done Q dot append uh four times uh but this is just another way to do it we could have also checked the validity of the index before inserting it into the queue uh that's just another way to solve it but here we did a check over here so if we don't do a check here then we have to do a check before we insert it into the queue um yep so that's the BFS solution let's look at the time complexity so the time complexity of this part is the Big O of NM where n represents uh the number of rows M represents the number of columns so we go through each and every cell so that's the big of NM which is linear to the number of cells in the grid um and over here we go through then all the cells and we do uh BFS so uh it might seem worse than linear in this case because we have a nested for here and we call another function which goes through a potentially many cells or potentially all the cells but one thing to note is we convert that we convert cells from land to water and we just ignore water cells so effectively we go through the entire grid only once so this would also be linear to the number of cells in the grid so o of NM and uh hence the overall time complexity of this solution is linear sense of NM plus of n m is equal to the O of NM according to the rules of time complexity or uh okay so I hope you found this helpful please subscribe to the channel thank you
|
Number of Enclaves
|
longest-turbulent-subarray
|
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
53
|
126 |
hi guys my name is jasmine and today we're going to be taking a look at one of the more challenging lead code problems and it's called word ladder 2. now this problem is an extension of the word ladder problem and they're quite similar but they're a little bit different and we're going to be taking a look at it today so without further ado let's actually get started okay so let's go over the problem description well given two words begin word and end word and a dictionary called wordless return all the shortest transformation sequences from beginword to the n word or an empty list if no such sequence exists each sequence should be returned as a list of words starting from begin word uh and then some words after that up until uh sk which as noted here s k is equal to the n word so basically what it says is that we need us we want to get from begin word to the n word now here um let me just explain actually what uh transformation sequence is first well transformation sequence from one word um to the another word or in this example n word using a dictionary that is given to us as the input here is wordless is a sequence of words uh that starts from begin word and with uh the n word however here we have a set of words that have to be in the word list now they uh the important thing here to consider is that each word in this sequence only differs by one from uh one single letter from its adjacent uh words for example s1 only differs by one letter from begin word and the same goes for s2 only differs by one letter from s1 and so on so basically what we need to do here is we want to get to from begin word to transform begin word to end word now along the way we have to use all these words from the word list to that to help us do that now here's the thing we need to um place them in an order that um each word only differs by one letter from it from its adjacent words so i guess you'll understand better if with an example now one thing to note that is that this question only needs the shortest transformation sequence so there might be other ways to go about this problem but what we need here is the shortest path so let's actually start with this problem okay so here we have big n word hit and n word cog and this is a word list a list of words that we have here now one simple way to solve this problem is we can use a graph to represent all the words and find the shortest path like this so the hit word is our starting note here and cog is our last word here now along the way uh we have to like um place these nodes in a way that uh each node only differs by one letter from its adjacent nodes like for example hit only differs by one letter i and o here with hot and hot has dot and lot that only differ by one letter here for example is d and l that diff are different uh from h but all the other letters are the same so uh this is how we're gonna go about it now how do we find the shortest path well here's the thing uh we can actually um let's actually like traverse all the paths and see which one is actually the shortest so the first path that we can take is we can go from hit to hot well they only differ by one letter and then we can go to dot they also only differ by one letter and then we can go to doc one also differ by one letter and here we can go to i hope you can see that each word only differs by one uh sorry by one letter now there's this is path one okay now let's actually find path two so another way to go about it is we can you know start from here are the same as the previous path however instead of choosing dot we can actually go to lot and then go to log and then go to here so this is our second path now what's the length of this path well the length of this path is 5 and this is also 5. so they have the same length now if you recall and the question says we have to return all the shortest path so meaning that there could be more than one shortest path so another thing is uh well there's other ways to go about it too actually let's say we want to go from hit to hot and then go to dot and then we want to go to lot and then from then we can you know do the same thing as path 2. so as you can see this isn't the shortest path you know the length of this path is actually 6. so it's not the shortest path if we want to go from after hot we want to go from dot to lot even though they only differ by one letter uh this doesn't give us the shortest path you could uh try the same another path from hot and then to lot and then we can go from law to dot and then uh the same as path one the rest is the same as path one now it's possible but it also gives us the length of six so it's not desirable when we have uh the short another other routes that give us a length of five so we choose these two paths so basically we want to go from hit to hot and then hot to dot and then from da to doc and so another uh one another path this is like um our path one this is path two they both have the same length we can go from hit to hot same as uh the above however we have the option instead of going to dot we can go to a lot and then after that we can go to log and finally we arrive at so we should return a list that contains all these words as our shortest transformation sequence like basically we return two lists that contains this sequence and this sequence now one way to go about it if you recall um and these sort of questions when we wanna find the shortest path in a graph is to use bfs now how to implement it i'm going to actually go into details in the next section but just for now keep that in mind that if we want to go from one node to another node and we want to find the shortest path that's basically what bfs does so now before we actually move on to the next part let's review some of the constraints of this question so it says that begin word all the words length are between one and five like no word has more than five length uh the length of each word is five uh maximum now um the length of every word is the same like end word and begin word have the same length however as you can see here every word in the word length in a word less length is um the same as the begin word so basically what it says is that um all these words here have the same legs like for example hot dot dog and lot and cog have basically all three letters in them and also the beginning word has three letters so they should all be three the length of all of these um words are three now all of them are in lowercase english all the words are unique in the wordless and begin word and end word are not the same so they're unique they are different uh they're different now um one other thing to mention is to mention here is that uh no two um in the word list that we're given here we should have all the words that we're going to use in these paths including the n word but it's fine if we don't have the begin word included in our word list you know but all the other words that we're going to use in this path uh must be in the word list okay now let's actually move on to the algorithm part all right so let's actually move on to the algorithm section like i've mentioned um there are a couple ways to go about it you can use dfs or a combination of bfs and backtracking which is the solution we're going to be overviewing in this algorithm section so uh first things first if you remember anything from bfs is a graph traversal method which aims to find the shortest path possible by traversing level wise from the source node meaning that we're gonna go over the source node and then after that we're going to examine each level each node in every level and then move on to the next level and after that to the next level that's why we have level here and uh the data structure we're going to be using in this um algorithm is q um that's the data structure we use in bfs so we're going to in each level we're going to push the current words into the stat into the q sorry and then after we're done uh traversing that level we're going to pop them out of the queue and move on to the next level now we have a current word and then we have a new word which is the combination possible combinations that are extracted by changing each letter of the word and if it matches any pattern that also exists in the words list we're gonna actually store it in the hash map and after we've done uh traversing the current level we're gonna move on to the next level and increase the level by one so the first thing we're going to start with begin word now we're going to push it into the queue and it's going to be our current word and we're going to actually um see all the possible combinations so how do we see all the possible combinations well um here we change uh each uh letter from a to z first we start with the first character in the word and change it from a to z and see if it matches any pattern in the words list now you have to also note that here we don't we ignore hit because it's the same as the current word so we ignore it but uh once we do it uh with the second character in the current word we find out that there is a combination hot that also exists in the words list so what we do is we pop hit out of the queue and push hit into the queue and uh we're gonna actually store uh stored in a hash map like this and uh we also have to after we found uh this pattern we also have to go uh over to the next character and last character t and do the same thing uh change it from a to z and see if we find any matching pattern so what we realized we haven't found any matching pattern so uh we're done here uh so we're gonna actually mark hot as visited so we've already visited it and after we move on to the next level we're going to actually delete it from the words list because we've visited this node and we don't want to visit it again so that's why we deleted from the words list so here because the first level only contains the source node and or our begin word we're going to move on to the next level and we're going to eliminate hot sorry hit so here we move on to the next element which is hot current element and uh we're going to see we're going to repeat the same algorithm here and change the first letter of the word from a to z now first we encounter a dot so dot is a pattern is a matching pattern that also exists in the words list now we mark it as visited and uh we're going to store it in the hash map and what we're going to do is we're going to push it to the queue and pop hot out of the queue and we do the same thing until we get to lot so here we also have another matching pattern and so we mark it as visited and push it to the queue and also store it in a hash map we're still on level one by the way so after that we do the same thing with the third letter but we don't find any matching pattern so we move on to the next word so here the next word exists in the next level we increase the level by one so once we actually move down to the next level we're going to eliminate the previously visited nodes that we've marked like here dot and lot we're gonna actually eliminate them uh in the new words list so we'll go over dot so here we have dot and we're gonna repeat the same algorithm here as well um we don't find any matching pattern by changing the first letter um by changing the second letter we don't find any matching pattern either but if we change the third letter um to g we're gonna find uh doc which also exists in the words list so mark it as visited and push dot out of the queue uh sorry pop dot out of the queue and push dog in we also have to store it here like this and we're gonna mark it as visited and here we have doc so we're still on level two by the way because we're we have lot to examine so uh our current word is going to be lot we do the same thing here until we find lock so it's a matching pattern um so we're going to actually uh mark it as visited uh we're still in the same level like i mentioned and we're gonna store it here lot log it's a matching pattern and uh we're gonna uh pop it out of the queue and push log in once we've done this log and log we're going to actually move on to the next level which is the third level and we're going to actually eliminate log and lot sorry login dot so here we only have cop in the third level so the current word is going to be dog and we're going to go over all the possible combination for the first letter and the word dog um we get cog out of it which also exists in the words list now here uh we're gonna store it here and push it to the queue but we're gonna mark it as visited however in this because we're in the same level um there is another word log which also uh can transform into so that's why we have we don't eliminate it uh once we're still uh traversing the same level after we've done uh traversing the level we're gonna delete it so we're also gonna store um log we're going to store a lot of cog here like this and we're still on the third level and we're going to pop log out and push cog in so and also eliminate from the words list all together now here we are we can change our current word to cog but since cog is our n word equals our n word we're going to stop here because we've traversed the whole all the possible combinations and we got to the end point which is what the question asked us now after that we're going to use backtracking to find to store all these like patterns into a list so now that we went over the bfs part uh we have to find the length of the path we just traversed so the length of the path is level plus one which our current level is four plus 1 is going to be 5. as we previously discussed in the problem explanation section the shortest path length is also 5. so why do we use backtracking so here is the important part we need to find these paths and all the possible paths and return them in a list so we need to store all these paths in a list and then return them as the question demands as the output so what we're going to do here is we're going to go over now that we have the map we're going to go over all the possible transformation transformations starting from the first the begin word which is hit and then we'll see what it what we asked what this part what is the next possible transformation well the next possible transformation is hot according to the map that we've created so it's going to be hot here and we need a list to store the current path into it so this is going to be a list we're going to store for now we're going to have hit and hot so after that what is the next possible transformation after hot well there are actually two transformations um there is dot and lot so you can choose whichever you want uh we have to like choose uh one of these at first and then we'll backtrack and choose the other one but for now uh i want to go with um dot so after dot we um actually add it to the current path and then after that what is the next possible transformation obviously it's dog so we're gonna add doc to the list as well and then what's the next possible transformation well it's which is the end word so now that we've reached the end word we're going to store this list this first path into um the set of paths here which is a list that contains all the possible shortest paths so we add it to here and then here we're going to backtrack this is the backtracking step so we're go we're going to go from cog to dog and then what is we're going to examine it again so what's like the possible transformation from dog to well there is no other transformation so we're gonna remove a from the list of the current paths and we're going to backtrack again we're going to go to the previous dot and then we examine it again what is the another transformation we can have perhaps well according to the map there's no other transformation it's only dot so uh we backtrack again and then here we have another trend and we remove it from the list by the way current path we remove it from the current path so now we have hidden hot and now we're at hot and what is the next possible transformation well um another transformation we can have is lot so we add it to the current path and here and then after lot is dog sorry it's log and we add it to the path and after that there is which is the end word and we stop here so this is the second path which is the same length as the first path is also five and we first add this one to the set of paths like here okay so after that we backtrack again from where we are and examine if we have any other path if there's any other path that is left and we haven't like discovered it yet so we backtrack again we go from to log and remove from the current path so like this we remove it from the so there's no other transformation from log to cog uh there's just one and then we backtrack again then after that we backtrack again and then there's no other transformation other than these two so we backtrack again and we remove it from the list so we reach to the begin word and obviously there's no other transformation other than hot so we remove it from the current path now the current path is empty and we only have two possible paths here stored and this is the final answer that we need to return okay so let's actually examine the code java code for this problem so the we have a couple data structures for this problem and the first one is explained earlier is a hash map called a json list it contains each word and its neighbors neighboring words that are only different by one letter and this is our current path it's a list that contains the current path that we're in and the third data structure is the shortest paths this contains all the shortest paths possible and it's a list of lists because we can have more than one shortest paths now this find ladders is our main function and it takes three parameters called begin word and a list of words called word list and since for the bfs section we need an unordered data structure an order an unordered list so we can efficiently remove the words when we don't need them anymore we remove each layer we instead of using a list we use a set so we copy all the words from the word list here and then to create our graph we actually um call the bfs and i'll explain all these functions in a minute and since every path starts with begin word obviously we first add the begin word to our current path and then we backtrack this is the backtracking step and if we can find here we can find in our current path we can find a path between beginward and the n word we're going to store it in our shortest paths and return it as our answer now let's actually examine the bfs function here this is pretty much just like a regular bffs and it takes three parameters a set and two strings begin word and end word as explained earlier we use a queue data structure for our bfs and obviously the first word to add is the begin word and we after we add it to the queue we can remove it because it's our first layer and as explained earlier we remove each layer after we're done examining it and here if the word list contains begin word we're going to remove it from our we're going to remove beginward which is our first layer and it only contains one word uh from our word list so here um while our q is an empty uh what we basically want to do is uh we're going to find all the neighbors of each word and save it in our adjacent list now here we have a visited list which contains all the words of the current layer that we're visiting so we loop in order to do that we loop over our queue and start with the most front element and we save it in the current word because we don't need it anymore we have to pop it out of the cube and here we find all the neighbors of that current word um using the uh find neighbors function uh and i'll explain this one in a bit uh so after we find all the neighbors what we need to do we have to add this to our adjacent list we have to add the current word and all of its neighbors to that list so we loop over all the words in that neighbors list obviously we add each of them to the visited list and then if our we don't have the current word in our adjacent list we add it with an empty list and then we can add the words that empty list now if that's not the case if it already exists in our adjacent list we only add the particular word that we loop we're looping over to the list of its adjacent nodes the current words adjacent nodes and after we're done doing that as previously explained we have to remove the words of the current layer and in order to do that we loop over the visited list and we remove each word from our word list now what is the function find neighbors so here's the find neighbors function it's a very simple one takes a word and finds all of its neighbors it takes a word and a word list because we want to see whether it exists in that word list or not and this is our neighbors list here we store all the characters of our word uh in a um career ray uh called careless and what we basically do here uh we change um each letter in that word to see whether it creates a new word that exists in our word list so we save it the original character in our old care and then we loop over each um letter in that word and uh we change it from a to z see whether um it creates a new word if c equals um our old character uh meaning that it's the same word or we create a new word that does not exist in our word list we skip it we don't need it if it's that's not the case then we add it to our neighbors list and then change the ice character back to its original form and ultimately returned the neighbors so our final function is backtrack here we take two inputs source and destination basically we want to see whether there is a path between the two if there is we're going to store it in our shortest paths so like i said if source equals destination meaning that we've reached the destination we're going to store our current path that we're on um in a list and then add it to our shortest paths because there's a way however if that's not the case if our if that's not the case we haven't reached our destination what we do is that uh first off uh we're going to loop over all the neighbors of our source whether we can to see whether we can find a path between the neighbors and our destination so we add that ice we add the ice neighbor to our current path and then we recursively call backtrack with that ith word to see whether there is a path between that and destination so we continue this until we reach the destination now there is a third possibility and that is if our adjacent list does not contain our source if it doesn't we skip it we don't need it we can't do anything with it now let's actually put this code in late code and see what are the results let's submit our code here hit the submit button so it was successfully accepted now let's talk about complexity well the complexity the time complexity of this code is nk squared plus alpha now n is the number of words in the word list and k is the maximum length of a word um and uh the reason for that is um we here we have the fine neighbors function and uh the complexity of this um part is k squared and because we want to find the neighbors of n words it's going to have the complexity of n k squared ultimately and in the backtracking step we're going to find all the possible paths so it's going to be a constant like alpha and as for time uh for space complexity uh because we have we copy all of our words in the word lists n words with uh k length um in a set we're going to have nko of nk as our space complexity now i hope you enjoyed this tutorial and i'll see you in the next ones
|
Word Ladder II
|
word-ladder-ii
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`.
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\]
**Explanation:** There are 2 shortest transformation sequences:
"hit " -> "hot " -> "dot " -> "dog " -> "cog "
"hit " -> "hot " -> "lot " -> "log " -> "cog "
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** \[\]
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 5`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 500`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
* The **sum** of all shortest transformation sequences does not exceed `105`.
| null |
Hash Table,String,Backtracking,Breadth-First Search
|
Hard
|
127,2276
|
352 |
hello everyone let's solve today's lead code problem data stream is disjoint intervals this is a design problem we will have an empty stream when add no method is called we add the input value to the Stream and get intervals method is called we return a list of disjoint intervals start of Y and end of I and it is sorted in this example we call add num with one so we add 1 to the Stream we could add num and three we call add num with seven now we could add num with two it's different two can be merged with one and three because they are integers next to each other so the return of get intervals is a list of intervals from one to three and seven to seven and we could add Norm with six can be merged with 7. so the return of the get interverse is a list of interverse from 1 to 3 and 6 to 7. we can solve this problem using two concepts at first we need to maintain sorted list when new item is inserted we can use bisect module it has insert function insert can insert an item into array maintaining sorted second we need to maintain an array unique we can use hash set let's do this example we have an array for a stream and we have a set for uniqueness check we add 1 3 and 7. it's stored in the Stream array but when ethno mode 7 is called 7 is not stored in the array because it already exists in this hash set and when at Norm with two is called two is stored in the array locating sorted if we call get intervals we process the first interval 30 is 1 and end is 1. and 2 is next to the one so the end is updated with two and three is next to the two so and is updated with three and seven is not next to three so we add the second interval start is seven and end is seven when ethnum with six is called 6 is stored in the array locating sorted if we call get intervals we process the first interval start his word and the end is one and is updated with two and is updated with three this time 6 is not next to three so we add the second interval start is six and these six and then and is updated with seven so this is our return value okay let's cut it in the init method we declare stream array and the uniqueness check hash set in the ethno method if input value is not a hash set then we insert the value to the sorted list maintaining order using bisecting sort and we add the value to the hash set in the get intervals method we are iterating the sorted stream array if we've already had an interval and its end is next to the current value it is just one less than the current value then we update the end of the interval or they are not next to each other or there is no interverse yet then we add an interval initialized start from value and to Value okay we made it add nums time complexity is Big O of n because the bisect insert is linear algorithm to get interverse time complexity is also big or oven because these four Loop and the space complexity is bigger oven because the stream array and the hash set but we can omit the number so space complexity is because of n I hope you enjoyed this video and it was helpful and I will see you soon bye
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
417 |
welcome to march's leeco challenge today's problem is pacific atlantic water flow given an m times n matrix of non-negative integers representing the non-negative integers representing the non-negative integers representing the height of each unit cell in a continent the pacific ocean touches the left and top edges of the matrix and the atlantic ocean touches the right and bottom edges so the pacific touches these rows and columns here and the lining touches these columns and these rows here now water can only flow in four directions up down left or right from a cell to another with a height equal or lower so we started at this one well we can move to all these cells here as long as they're lower than the particular height so find the list of grid coordinates where the water can flow to both the pacific and the atlantic okay so uh this problem it's definitely going to be a depth first search or a breadth for search solution and instead of trying to figure out which cells can go to both the pacific and atlantic it'd be much easier to start backwards and create some sort of visited set starting with the um the endpoints here which would be hitting the pacific ocean what we could do instead of looking for heights that are lower we'll look for try to traverse up down left or right to heights that are going to be greater if the height is lower we can't go that way because that means it couldn't have come from lower to higher right so we're going to only go down paths that the height is higher or equal to it after that we'll create some sort of visited set showing all the cells that the pacific um that can reach the pacific ocean and we'll do the same for atlantic we'll get a set of all the coordinates that can hit the atlantic ocean once we have those two we can just get an intersection of both of them and that's going to be our answer because if it can go to both the pacific and the atlantic from this coordinate then that means that should be in our answer right okay so uh let's begin let's start off by initially initializing a couple variables i'm going to start with the m times m n which is going to be the length of matrix and the length of matrix 0. there's also an edge case if not matrix which return empty list so the first thing we need are going to be a list of the starting coordinates for both pna pacific and atlantic and i also want to have some sort of set uh i'm going to call it vp and va for visited pacific and visited a and this is going to keep track of all the cells that we could actually reach the ocean to for both the pacific and the atlantic all right so first things first we need to have our starting coordinates right or it's actually the ending coordinates but here in our algorithm that's where we'll be starting so to do that we know that we have both the rows and columns what i'll do is just say four let's see row in range of m we're gonna add let's see this is the row and this is the column so for p we're gonna append a tuple with the row and column zero now for the atlantic we also want to do uh something similar but we're gonna do the row and the last column here so that's gonna be n minus one okay now we want to also have for all the columns range of n we're going to add p append see the first row and every column and with the ionic the last row and every column so now we have all our starting points okay great so now we need our depth first search function uh what i'll do is pass in the row and the column as well as the visited set because these are going to be different to keep track of that let's see so first things first we want to add to our visited set the row and column next thing we want to do is traverse the four directions that we can travel right so to do that um let's see i think i can just initialize that up here and we're going to create a couple tuples here so one negative one zero one and zero negative one whoops okay so for uh we'll call it d i d j in directions we're going to calculate our new r and new c to equal r plus d i and c plus dj oops and we have a couple conditions that we need to make sure we're in so first things first we not got to make sure we're inbounds so the new r has got to be greater or equal to zero but less than m and the new column needs to be greater or equal to zero and less than n we also need to make sure that our starting point here is less or equal to the new one is all right less or equal to yeah so a new one that we're going to needs to be higher and finally we need to make sure that we haven't visited so and let's see new r new c not in visited so if that's the case then we could continue our debt for search to the new r the new c and pass in the visited side now we don't need to return anything because this set will be getting updated and it's called by reference so we have all that so now all we need to do is for everything in p we'll call it the first search so let's see four x y in p i should call that rc p we'll call our deafer search for rc and vp right and we'll do the same for everything in the a okay so let's make sure this is working because once this is finished we can just return the intersection just use the and symbol here return a list of all the coordinates that intersect okay so let's make sure this works okay that looks like it's working it's all out of order but i don't think the order matters here so let's go ahead and get rid of this print and try submitting there we go accept it so ty complexity-wise this is complexity-wise this is complexity-wise this is m times n we're gonna do that twice but since it's only twice it's equal to m times n space complexity we do have our sets and we do have this so yeah space complexity is also m times n but you can also try to attempt a breadth first search um in some ways that's much cleaner and it might be faster um probably not it's about the same but breath or search might be more intuitive so you can also go in that direction as well okay hope that helps thanks for watching my channel remember do not trust me i know nothing
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
20 |
hey so welcome back in this another daily code problem so today it was called valid parentheses so this is actually a very popular question it has over 20 000 different upvotes here and so it's an easy level problem that I was actually asked in an interview once um and so you're given a string and you want to return a Boolean and all that you want to do is see return true if this string is valid now what makes up a valid string is that you're given a set of parentheses here and they're either open parentheses or closing ones and there's the three different kind of parentheses or bracket types and you just want to make sure that for every open parenthesis there's a corresponding Closing one but you want them to appear in the right order and so say if you're given an open parenthesis here you want a matching Closing one but let's say it's a kind of circular opening one and then a square one then you want the closing brackets to appear in the reverse order so you'd have a square Closing one and then a circular one but let's say that you have a kind of circular opening one and then two closing ones you would want to return false in this case because you need it to be kind of mirrored across the middle here where you want them to be matching so you want this kind of another opening bracket here all right and that's basically the problem I find think about in hierarchical nature works the best where you kind of look at it like it's these kind of children of each other or a chain that kind of goes down here and you just want to make sure that they all line up perfectly and so to do this what we're going to use is a stack and the reason why we want to use a stack is just the way that you push and pop from a stack whenever you pop from it's going to be popping in reverse order that you input it in and so it just works really well where you're just going to push to our stack all the opening brackets and then whenever you see that okay it's a closing bracket you expect the top of the stack to have the corresponding matching opening bracket and if not you just return false okay and so it just allows you to very easily perform that kind of reverse order popping of the stack um using these closing brackets so let's go ahead and write the code so first thing is we're going to create our stack and we want to return true if our stack is empty at the end of this program and so we're going to want to iterate through every character in our string and handle two different cases the first one is okay does this um character is this character a opening or is it a closing bracket okay and so one thing that makes it a lot easier is if we just Define a lookup table and so we can say okay this closing bracket corresponds to this opening bracket and we just want to repeat this for all of the three different types okay and so this just makes it really easy so that you don't have to handle like the three different kind of switch case or like if else statements in this program so it's just very easy way to quickly look up what you expect the matching open or closing bracket to be okay and so if this character is not in this set of keys then you know that oh I think I did this wrong um we want to make these the square ones and these are the opening brackets on this side oh I'm just going to do that there we go so yeah so the closing brackets are on this side and the opening ones are the values for these keys so if our current character is not in our key so not in the map here then we know that okay this is a open parenthesis parentheses until you wanted just a pen to our stack otherwise we want to process is a closing parentheses and so in that case we want to say okay if our Stack's not empty and what's at the top of our stack I'll just move me over here we want whatever is the top of our stack to be equal to the mapping of this current character and so that's just going to convert the current character which is a closing one to the correct corresponding opening bracket and since we're pushing these open parentheses to our stack here we're expecting that the top of the stack has the matching like open parentheses for this current closing parenthesis okay might take a little bit of drawing out to really fully understand that um but you just want that whenever we see a closing parenthesis what's at the top of the stack to have a matching open parenthesis and we can just easily translate it using this hashmap and if so we can just pop from our stack and otherwise we know we just want to return false here and that's just because well okay if the Stack's empty and we have a closing bracket then naturally it's false but then also if the closing and open parentheses don't match then in that case you also want to return false here all right and so that was successful for the test cases and submitted it was all correct so the time complexity here is just o of n because you iterate through all the different characters inner string just once this is finite it'll only ever have three so it doesn't like scale with the input size or it scales well it just it won't like become exponential it doesn't have anything to do with the space complexity really so this is finite but what does have to do with the space complexity is this stack here that we're using which will be at most of N and so it's just an O of n time complexity and oven space complexity so yeah that was today's leeco problem I hope it helped a lot and good luck with the rest your algorithms thanks for watching
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
81 |
hi everyone today we are going to solve the legal problem number 81 that's just a search and be rotated are you part two so in this we are given an array single array which is in which the array elements are rotated by an unknown pivot and if an input array a becomes like this so what we have to do you just have to find the given target in the table in the Harry that we have given for the first simple approaches to just I cleared through the entire attic look for the given target if you find it we just go down it right over but for this particular problem I was practicing going through my binary search algorithm so in the lead code section when I putted it like the filter all these problems in binary search this was the problem so easily I think that you need to and also keeping the keeping in mind the level arts medium we would first try to sort the array there are two ways of sorting the array first using the inbuilt erased or salt method which uses dual quicksort algorithm to sort the array which is a bit faster than using a single pivot quicksort algorithm for understanding a quick sort algorithm I will highly recommend you guys to visit the each four weeks website they have a dedicated section quicksort you can refresh your knowledge from there and once we have this hotter sorted array we will just use the binary search to find the given target if we find it we return true otherwise it will return false so let's track the target for three like and like we will also keep a track of the array element and the myths that we calculate so in the binary search we basically look for the in the sorted array we get we calculate the mid and from the mid we move if the target is greater than what we are sorting we start moving right into target is let's start moving left which is we D command D low we start coming from the mid only left side of an area so if you are looking for the target I am in 3 so we'll force any slaves know as 0 and high as length minus 1 which is 7 minus 1 which is 6 and we first start with 0 less than equal to 6 to come inside first it was first trying to calculate the middle while your value is 0 plus 6 minus 0 by 2 so the made of wood we first kind could you take 2 3 so array element that makes 3 it's nothing but 2 so we first aid the offense ladder condition where 2 is equal to 3s false to greater than 3 is a main choice so according to the else condition will increment hello from 0 to 1 and our high is okay 6 so 1 less than equal to 6 to come inside and calculate the middle so 1 plus 6 minus 1 which is 5 2 is 2 so 2 plus 1 is 3 so either keen mid would still remain 3 and using the same I got a seam approach will now increment the low 0 2 from 1 to 2 so we keep a track with 2 less than equal to 6 this so 2 plus 6 minus 2 which is 4 by 2 is 2 so 2 plus 2 is 4 so now we incremented the mid from 3 to 4 and the fourth eric limit is again 2 so this 2 I just added because we have we had the same execution for when the mid was updated to 3 so since at the air element we have 2 so the execution would still work like 2 is equal to 3 is false 2 greater than 3 is again false which means that we need to increment value which is 3 less than equal to 6 - when you try to calculate the low - when you try to calculate the low - when you try to calculate the low octane which is 3 plus 6 minus 3 by 2 so 6 minus 3 is 3 by 2 is 1 so low it is again incremented to 4 so again the same execution with the array element 2 will increment the low how 3 to 4 so 4 less than 6 true go inside and calculate the marriage so which is 6 minus 4 is 2 by 2 is 1 and 1 plus low which is 5 1 plus 4 sorry the low values for some it is updated to 5 so I had to file we get the array element as 5 so again 5 is equal to 3 is false file greater than 3 which is true so this time decrease the value of high increase instead of using the value increasing the value of flow so we decremented from 6 to 5 now what we are going to do is years like this try to see for less than equal to 5/2 see for less than equal to 5/2 see for less than equal to 5/2 update D now it's time to update the value Osman so which is 4 plus 5 minus 4 by 2 so 4 plus 1 by 2 so 1 by 2 is nothing but 0 so I made a value would again become 4 for us so for at the area next we have element 2 so 2 is equal to 3 is false and 2 greater than target is false so we will decrease the value of hi count 5 4 and we'll check the condition for less than equal to 4 is true so this condition is 4 minus 4 is 0 by 2 is 0 and plus 4 over here would give us the very value to be four again and the other element will be 2 again so going through the execution this time the low value would be implemented to 5 and so 5 less than equal to 4 is a false condition this while loop would be exit the while you won't do the executed and we return false stating that the look we are looking for entire element of 3 which is not present in an array and the function should return your false so that's the output we are expecting for the example of example number 2 so if we submit the solution if we run this it should pass and if we sum so we see the runtime of 40 milliseconds so the just in case I should I will show you the difference of what of using an inbuilt function which is erased or thought we should see a Dickerman decrease in the runtime you see we saw the keys of 36 milliseconds so the first approach which I was talking about was this one where I just loop through the entire array look for the target if it is present return true right away or return false this is the simplest approach that we can follow in order to solve this problem thank you
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
289 |
Hello Guys Welcome to Vikram Midning Question Thursday subscribe and subscribe the Video then subscribe to The Amazing subscribe The Amazing Hai Turn Off Side Ambrose 10 Meter Defined Variable Mein Nine Administrator Affair Logic In Every Cell Minute And Ho Laharan The Phone To Ajay Send me on number to check fuel president Mirwaiz gave MP3 a nominee shopkeeper number flying officer in Odisha billu direction are not new to believe that under the running column the traitor was inside the boundary of hua tha ki and s w na body up pollution advantage mili So entry mandi account of the number should declare discount outside accepted download 10 minutes remember account of the number of life lord difficult acid subscribe like and subscribe mid tours of mount 2.3 tours of mount 2.3 tours of mount 2.3 that i updated the result of the idbi jeevan no animals in the already Subscribe Like Subscribe Result Complete The Best Result Video Subscribe Amazed Over Again That And Copy Old Values Are There Into The Main English Kinare Village Virendra Is Code Jhala That Egg Subscribe Result Confusion Joint Committee Successfully Not Come Into The Afterlife Question Acid Subscribe Will Mist subscribe and subscribe the Channel subscribe Video subscribe button subscribe aur niyudh acid attack a minute ago when you have tube light subscribe this Video not appointed bhi amused with a ko putra date vinod atav verses page subscribe if you mez loot condition videoron its subscribe The Amazing Loot Subscribe 12345 In The Adheers Alive In You Stole The Twelve Verses Where I Am Id subscribe and subscribe the Channel Please subscribe this Video Subscribe Lootb Skin Ko Achhi To Position Alive Flight Divert Loot Time In Adhir Va Subscribe
|
Game of Life
|
game-of-life
|
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
**Example 1:**
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
**Example 2:**
**Input:** board = \[\[1,1\],\[1,0\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 25`
* `board[i][j]` is `0` or `1`.
**Follow up:**
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
| null |
Array,Matrix,Simulation
|
Medium
|
73
|
201 |
What the hell, hello, USB CD disk o88 infection does not end. Using a process from the top, especially the cuttings. It is necessary to talk about the most pathetic for the damage I have done in the garden. For example, is it a decision for the 5 people we wet in a restaurant for our martyrs? Angelica Immediately longing for them. So what does this mean? -6 -6 -6 went to his ties he damaged and we car [ __ ] went to his ties he damaged and we car [ __ ] went to his ties he damaged and we car [ __ ] clip 55 in our world the eye emphasized So we have six with us We also take a then what kind of so with winning now we will also drink when I wake up Actually it means 30-31-32 of means 30-31-32 of means 30-31-32 of I also look at it in the garden I mean, if it's over, we think it's Murano, of course, my Lord, to our patients. Come on, let's go out, I'm the name of this, Red, without stopping. Now call, we find these feelings normal, leave it. What's the news, it's called Muslim, so get over me, narrow constants, you're leaving the month from here and there, I'll do it, but Now the number means if the inslow beauties Neşve the opponent writes like this 60 Because come with me it means Hatice in the entrance 12 music what does it mean what sexual intercourse what does Torbalı come we have the last one you are this and there you are this and there you are this and there are cables If we see from the piece of Hatice's son He also It's normal, let me go all over the world, I'll go and see from here, what gum came out in our games a year later, that carpet, Normal, normal, its name is ice, normal, Berno, I 'll read it together, I 'll read it together, I 'll read it together, I mean if you don't know, 8/13 mean if you don't know, 8/13 How is your grandmother's wound? Do you see? Come, this is on our table, I'll give it, I wrapped it, these were it, and it's traffic. Goodbye of the set, but I mentioned this on our right, you are talking about leaving it behind and throwing it back. Look, I accept the structure as the center, they will talk about our health, if it is not clear, what do we mean, what is the place, what did we put in this for me? Because I'm standing in a place, thank you for this, Hatice called my husband. You don't become the party in our world until this happens, it's normal, there's normal, it's normal, leave it to the nozzle, our footed time, the ball, Elif, the next, no, the situation, I went, this was left-right velcro, the 90's, that mind, the figure, I'm here, what happened, come again, labne cm 'e commercial Özge because it was one ourselves Morgan Me on my channel he was all handsome I left from there as well as I got it apart from that I'm tired of this Hello friends this was the streets of Istanbul next to tecavi let's leave it at our job then took an oath in this world there were two so How is it practically? Yes, we can stand it. Look at me now. I can't find it. What happened? Okay, let me be in the garden. Hospitals. General. Look, this camera is 300. I want to compete here. Because it won't come first. So this month it 's disgusting 32/40 's disgusting 32/40 's disgusting 32/40 what's more into our artist If even Strike stymest What's the news Look at me let's say object Isn't there a picture in Kayseri let me start to eat because Isn't it all of you How can we leave this aside like China's and our wholeness We will play. This is how we invest there, cow, but I will say something else. Vodafone period, let's watch the lesson. Hello, they will take over, I ran away, okay? The chest So it's my girl. There 's a whole detail. That's why she's 's a whole detail. That's why she's 's a whole detail. That's why she's angry with me. It stands out well. You didn't have medicine here. So, it has this feature. It's a note that she thinks is behind a whole. People's morale. Ryland Star. It's easy for a long time I came Hello they were selling our onions Please I mean We got off Did you go to your village He was Özer the nuts for our living that rap is second from NASA all this man my father and waste Oh how with the number I need to work Because after his list he should take a break he threw it You give it to be visible during use, it's my money, they work hard, it's math, but we have both desks, send it to me, I did it from there and the sun and times today, what bag do you do with us, we don't need one, he called me about and said, lied to me in this video. You have to paste today, get out of the island, increase, Rezzan is ours, but ice, Oh, he sent a message, I want his song, because ice is also good, so be of this, I took it out, there is a note, University Faruk, how are you, is there a note?
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
239 |
everyone welcome back and let's write some more neat code today let's look at a sliding window problem a hard sliding window problem sliding window maximum the statement is pretty straightforward actually so we're given an array of numbers and we also are given a number k which is going to represent the size of our sliding window it starts at the very left and then works its way to the right and so since it has and so since it's size k there's only going to be k numbers inside the window and for each position that the window is in we want to return the max value so you can see that this is our input array and our window is going to be size 3 so this is our first window and the maximum value is 3 so then we see and then we add a 3 to our output array so the output is going to be an array next we see that this is the next position of the sliding window and the maximum value in this case is still three so we put a three in our output and the next position we see that this is our window the maximum value is five so we put a five in the output now you might recognize one solution to this problem immediately for each of these windows why don't we just scan through the array right like it's pretty easy to find the maximum in an array right like if we had one two three we just check every value and see okay this is the maximum and then we just shift our window by one into the next position right and we keep doing that until we're done well the time complexity of this is going to be roughly since the size for our window is k how many windows are we actually going to have let's say the entire input is length n in that case we're going to have roughly k times n minus k that's how many windows we're going to have right and so this is going to be our time complexity but i'm asking is there a better solution can we actually make a linear time solution where n is the size of the input array and the answer is yes and i'm going to show you how to do that right now so i'm going to show you the best solution but one thing you have to notice first is this so let's say this is our input array we have four numbers and our window size is going to be three so k equals three notice how these values are in increasing order right one two three four okay so we notice that now look at our first window we have one two three we see that two is greater than one we see three is greater than two now that's good and so we scan through every element one's not the max two is not the max three is the max so then in our output for the first value we're gonna put a three okay and that's great now we shift our window to the next position so now i'm literally just gonna repeat that process the brute force way now i'm gonna check two okay now i'm gonna check three is greater now i'm gonna check for four is the greatest so we add 4 to our output and so then we're done we have our output but we just did it the brute force way but do you see the repeated work that we just did as soon in our first window we saw one two three we know three is greater so we basically eliminate two and three and then when our window is at the next position it's over here right one is no longer a part of our window so we don't need to worry about one what about two well two is inside of our window right it's at the leftmost position but since we know that this three is greater than the 2 anyway why would we ever need to look at the 2 ever again it's never going to be the maximum and let me just make it even more obvious let's say our window size is six and this is our input array okay so our so for our first window we have to check okay the one another one and then a four so the four is our max that's great so we can save that and then we shift our window to the next position and see we're repeating all that work over again the one as soon as we see this four we know that these elements as far as we're concerned are useless to us we never have to look at them again they will never be the maximum inside of our window because our window is going to continue being shift to the right position and the 4 is still going to be in the window even after these elements have been eliminated and so the data structure we're going to use to eliminate these values is a deck or a dq and i'm going to show you the algorithm and just to repeat myself basically what i'm saying is if we have a window and we see a value that's greater than values that are previously in our window then we can eliminate those values from our window and what you're so i'm going to show you the algorithm and what you're going to notice is that the values in our deck are always going to be decreasing order so this says decreasing so we know our window our sliding window is initially size six right k equals six so we're gonna take the first one put it in our window the second one put it in our window and then just repeat that right we have five ones we're gonna add all of them and then we get a 4 so since 4 is greater than the value at the top of our deck or at the rightmost position of our deck what we're going to do is we're going to pop this value off what we're going to do is pop the top of the deck right and now we're going to make the comparison again we see there's still a 1 so 4 is still greater than the top of our deck so we're gonna pop this we're gonna pop that we're gonna pop all of them and after that we're gonna add the new value for and so what are we gonna add to the output so we have an output array what value are we going to add to it well the leftmost value in this case we only have one value is going to be what we add to the output so a four and so we're done with this comparison we don't have to look at it again and we don't even have to consider these elements anymore and now we shift our window by one position so we're introducing a new element five so before we add the five to our deck what do we have to check is five greater than the value at the top of our deck it is because the top value is a 4. so why would we ever consider the 4 as the maximum value ever again when we know there's a 5 right next to it the answer is we don't have to so we remove the 4 from our deck and then we can add the 5 to the top and then we know that there's only one value in our deck and it's also the leftmost position we are going to add that to our output and now we're done this is our output but what's the time complexity of this algorithm first we took each one added it to our deck right we did that for every single value that was expensive and then we also crossed out we had to remove every single value from our deck but adding and removing we know adding and removing is an o of one operation to our deck and we had to do that for every single value in here potentially but that's still o of n right the result is o of n which is why this is a really good solution and i'm going to show you one last example and by the way this is called the type of problem this is called a monotonically decreasing q and the reason is because our q is always going to be in decreasing order which this next example is going to demonstrate and the reason we're using a q rather than a stack is because we want to be able to add and remove elements from the beginning in o of one time but not only that as our window shifts like for example our windows here next our window could be here we want to be able to take an element like this and remove it from the beginning and we want to be able to do that in o of one time which is why we need a q so let me quickly just run through this last example so we have our first window over here eight and seven so we add eight to our q and then we look at seven well seven is not greater than eight right that's just not true so we're allowed to add the seven we only want to remove smaller elements if they exist but in this case that's not true so we add the seven and notice how these values are in decreasing order we have a and then we have a seven right they're in decreasing order so what that tells us is since we want the max value in our sliding window we can just look at the leftmost value in our deck and then add that to the output so i'm going to add 8 for the first sliding window the max value happens to be eight okay now the next sliding window we have seven and we have eight okay the first thing to notice is that the eight is no longer in bounds so we gotta pop from over here right and we wanna do that efficiently which is why we're using a deck but so before we add anything we pop next we see the six well 6 is not greater than 7 that's not true so we're allowed to put a 6 here to keep this in decreasing order and now the max value in this window is 7 which is the left most value in our deck so we add it to the output and lastly we look at the last sliding window which is these last two elements and we know that the 7 is no longer in bounds right so from the leftmost position with it which is this we pop from our deck we make one last comparison right we just added a 9. let's take a look is 9 greater than the top value of our stack is it greater than 6 it is what does that mean that means we have to pop from this we have to pop from the top of the stack the rightmost position or rather the q i don't know how many times i said stack but we're going to pop from the rightmost position in our queue and now we are allowed to take the 9 and append it to our queue so we add the 9 now we know that this is the leftmost position in our rq and we know that in this window nine is the maximum so we did this correctly right so we can take the nine add it to our output so this is the result that we're looking for and i hope this demonstrates a few of like when you actually run through examples it shows you like what you need to know it shows you why we're using this data structure and it shows you why it's so efficient so now with that in mind the coding solution is not too bad so we are going to have an output array to put the values in we're also for our window we're going to have some pointers so left and right pointers these are going to represent where our window currently is they're both initially going to be set to zero and we're also gonna have a queue in python we can do collections.deck and so we're gonna run collections.deck and so we're gonna run collections.deck and so we're gonna run this until our right pointer is no longer inbound so while right is still in bounds so we want to our q we want to be able to append the value this value right r and instead of doing nums of r i'm just going to do the index itself so this is going to contain indices because we know we can take an index like r and then easily find the number that maps do by just taking nums of r right but before we're even allowed to append a value to our queue we have to make sure that no smaller values exist in our queue so while the queue is non-empty and the top the queue is non-empty and the top the queue is non-empty and the top value in our queue or the rightmost value in our queue is less than the value that we're inserting nums of r which is the current index we're at so while smaller values exist in our queue we just want to pop from the queue just remove values while that condition holds and only after we do that are we allowed to add the new value to the queue we also if our window if the left value is out of bounds then remove the left value from the window so if our left index left is currently greater than the leftmost value in our queue then we can pop from the left of the queue so basically we know left and right represent our window so if our window is out of if this value the leftmost value in our queue is out of bounds of our window we're gonna remove that we have to remove that and this part is kind of an edge case uh since we're since we are starting at our window being uh left and right both being at zero we have to check that our uh right plus our window is at least size k so if we want to update the output we have to make sure our window is at least size k so that's basically what i'm doing here and for each iteration of the loop basically for each window we want to append our output with the maximum so we know the maximum is the left most position in our queue and we want not the index but we want the actual value itself don't forget like me to update your pointer so we know right is always going to be incremented so at the end of our loop we can increment right left though is only going to be incremented once our window is at least size k so we're going to put that inside of this condition and now the only thing left for us to do is return that output and it works and we know that this is the most efficient solution with the time complexity being linear and the memory complexity also being linear because we are using a data structure our q so i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
154 |
A Loved One Most Going Student Ko Delhi Silent Point Minimum In Routed Through The Nominated Element Must Subscribe Apps Net Speed Simply Wind Pipe Se ZF Unmute Buddhi Festival Solution Wedding Gift A Title Always Want To Find Out The Most Optimistic Marriage Sutra Click the subscribe button on the right side and subscribe my channel and listen to these data but a great specific them Gautra Flowers and welcome to all of you and click a new and oct12 order rupee cleaner search in two point question modified on I let May Explain Villiers Up-to-the-minute Subscribe With Us Who Here Breaks All Records Length Of And Withdraw With Us Main Surakshit Hai Character Se Nickle Type Handed Over For Cricket Championship And So Will Simply Answer Request To Minimum Of This Is R common voucher without the right the land and all the cents and determine the shop main tujhse bhojpuri and editing and answer new to be in turn ask each any1 tint nose pims utkat minimum set kar do main nachu ki aaj instruction moment plate light ka phool hai ribbon solitaire mode of institution of account it 2.0 feed it 2.0 feed it 2.0 feed 198 * point approach 15th surendra ko 198 * point approach 15th surendra ko 198 * point approach 15th surendra ko enterprises tanu subscribe please subscribe ki and minus point and nurses thursday ko i 9 point to point se z f the central sex do tiffin aaj number plate a Sanam's Playstation Ki Garlic and Request U Not Right Today Bengaluru Simply Decrement Diet is A Value Only Instrumental Flute is Pyorrhea Discriminating Right Test Record Exams Page Number to Right Moot Element and 30 Near to Me Difficult Questions Page Type Limit Decrease Right Element Subscribe to A Recorded Simply Rotate Improvisation Father Kulbir One Died On Lips Ki Ravana The Part Of Any Time Complexity A Improvise And Play Karo Main Itna Dhund Previous Thing Set And Left In Zoom Element Meaning Last Quarter Of The Match Referee Element Which Oil Is Quite Difficult To [ Sangeet] Find [ Sangeet] Find [ Sangeet] Find Your Position That Dataless Time Complexity Of Trophy Mein A Love Comes Ped Solution Record Only Spare Time Complexity Of Minutes Ago Yo Anuradha Pandey Soch Sample Gotra Of Login Solution Invited To Draw Login Equal Website Midding Midning In Two Parts Divide Into Two Parts Subscribe Agree With U Bluetooth Setting A Smile Left And Right Enjoy This Particular Only Will Behave In Apart From 10 Minutes Limit Will Be Simply Left Right Left Plus Tight Miniclip Yes Bittoo Timeliners Product Complete Control Over All Times Pe Torch Light Elements King Sexual Phase To 8 Month Can Go 205 Robbers That It's Only Can Coupons In Danger Boil Almost Scars And Effective To-Do List Phone Number To One Ko Obscene Phone Ko To Me Can Simply That Pragya Chanted For Advanced Translation But oo all to phate par difficult rule hai so hindi dictionary app phone number of but aap is please ke andarche failed in this world will definitely be compared with and nonmetals class subscribe to in the meantime center is traffic havaldar to now shabnam mid day a factory liye Meaninglessness Element with Pain and Elements Raw Simply What Will U Na E a Fantastic Background Plus Form Aa One Minute Place and Daughter and Stop Not Agree Students Should Give Me to Murthy Understand Tubelight Simply Transist Question That Akshay Apni After The Can Find Something Which acts of law of previous song subscribe a which alarms pimples setting on this end portion ungli pe Thursday previous song aisa tweet doing in this approach voice mail ko subscribe Video subscribe hai mein improvement share and quote ball stump and definition ungli patel e Agree With U Ek Sachhe Sadhu Account Today's Question And Share Complexity For All Of Them By Simply Border Of .in Subscribed That Ek Sachhe Sadhu Account All Free Part-12 That Ek Sachhe Sadhu Account All Free Part-12 That Ek Sachhe Sadhu Account All Free Part-12 Uttar Pradesh Should Fight Chest Solution Thank You
|
Find Minimum in Rotated Sorted Array II
|
find-minimum-in-rotated-sorted-array-ii
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:
* `[4,5,6,7,0,1,4]` if it was rotated `4` times.
* `[0,1,4,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` that may contain **duplicates**, return _the minimum element of this array_.
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[1,3,5\]
**Output:** 1
**Example 2:**
**Input:** nums = \[2,2,2,0,1\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* `nums` is sorted and rotated between `1` and `n` times.
**Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Hard
|
153
|
1,799 |
After finishing a small amount of rice, the Ricoh Atlas sound for your interest lists and muscle and operations on the main advantage of Michael cuesta calcium vitamin integration and I want operations in its position with some paper in the one Who uses Advanced nourish Endless Love is integrated time favorite Common divisor between the two new version and then You're ever Used some place for tourists so you can use them again I read the sea products imported summarization and some fiber computers Sting Together Again to compute Army fix was rejected comment divided between local purpose of just So you blew up in the series of the Earth and precomputed age is cultivated Speed the fun that age is cultivated Speed the fun that age is cultivated Speed the fun that will use and decided to make sure you saved and decorated is a very low ride the heris land of nod Mobifone search fake Girls azzaro Ok She knows her make way for every detail of special with Common wealth of any precomputed I know We can have a suggestion for which the workers parameter is a valuable 5 Plus the week and use of which We can't help a little prayer with Vietnamese investors will happen to All these great hand to the sentences to make a set with the rest from one to know that acts as a result We want them to say it because it is to work wish for you need to the mood of fundamental anh Ok milk cook Bac Lieu name chi stand Again to work hours IV sootopolis tract infection with Asus economies Ok jika Ada fun and personal tiross What is special the biggest cities number instead of aeropostale a sentinel professional ok here just really nothing YouTube your present life of the opposite specialists are introduced some States That is Rude to adjust address you do is the best I don't have any number two nights you acknowledge the usage of Faith and then here and converting live valable 5 set to work late because I need to person in respect of nowhere to vitamin YouTube brings excavator from Facebook nè field I Will Keep updated to special Winter Night sambas In itself and our candidates solution with my Be The Best Coffee resist velit vel nulla Sit Back To where you need to take a purpose which we don' t take you made some reasons which we don' t take you made some reasons which we don' t take you made some reasons appear the full ap we don't want to be compared beige repeat and self test English usage of wight beautiful cities ex-white ok fear To The Voice UK purchase ex-white ok fear To The Voice UK purchase ex-white ok fear To The Voice UK purchase unit is currently available on all aspects of keeping here is that process sunness loop Wheels lights and sward retain their opponents from our English on which also visited Vina melt with over I was the first bluv 7 2 7 inches into the A first come first release of my love Lee Sin nothing is the Wake of purpose of this and will Sing Ok see What the face You're my parent operates to the Movies list friend how much how my aunt and Check it against terrorism skirts I eat What happen if you waited atrus another and use of Action with installation service people have applied in the mood of foreign aid to develop personal values Which is Kind develop personal values Which is Kind develop personal values Which is Kind attention It is adjacent invalid-meta attention It is adjacent invalid-meta attention It is adjacent invalid-meta the first step is the way you want to this is an easy spirit and experience For Christmas It is afraid to your saves list of the cost of your English of legitimate work to say is apparently have six 5 Plus Friends My current mood is scared straight ahead and want to have you set a Coffee occurs in adults and gretel Witch hunters embrace The west's doesn't Take some use And now You're sure to be The set array of Vietnam Alistar available for and neck Spotlight English for now our head My je-xu Tam Tinh for now our head My je-xu Tam Tinh for now our head My je-xu Tam Tinh server addresses of International Miss Word Excel And you can adjust and you can easy solution is almost All The Witch The First Time the free computer city officinalis à when baby We have a secret tackle and record on the music Coffee the way that was a problem that do not restrict use And discard The vessel is the best little helper born our performance and the crazy English will integrate with other major causes which member will I review Crystal sound speakers it rain Soul and tagged with one or you can to Love muzik Is Here they can also extended for example Together Save The Earth quake III Arena takane a'pieu already correlate live show Want you can use And Again to have to pretend that we don't hate these Steps will you have made fun of service gives a great Year party is you I hate you can use dirty akiha can't wait Are you already have it all to you can't understand you know Vision to go to the forests and respect and Don't Forget to do after The cat is it me you're in and you're looking for some and I think that you need for you to address for your patience and dedicated to All I need is you play with comments everything about this and sisters Twisted Switch jarrod stech cortex et quinta people that is restored to find the time consumer reports with any body knows the products Are Happy to be Used in the comments sasete Premier League Thank you for Android
|
Maximize Score After N Operations
|
minimum-incompatibility
|
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.
In the `ith` operation **(1-indexed)**, you will:
* Choose two elements, `x` and `y`.
* Receive a score of `i * gcd(x, y)`.
* Remove `x` and `y` from `nums`.
Return _the maximum score you can receive after performing_ `n` _operations._
The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.
**Example 1:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 2)) = 1
**Example 2:**
**Input:** nums = \[3,4,6,8\]
**Output:** 11
**Explanation:** The optimal choice of operations is:
(1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6\]
**Output:** 14
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14
**Constraints:**
* `1 <= n <= 7`
* `nums.length == 2 * n`
* `1 <= nums[i] <= 106`
|
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
|
Array,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
| null |
814 |
hey what's up guys it's Nick white here and I do tech encoding stuff on twitch and YouTube and I do all the way code problems so check the description you can find everything that you need about me personally and I do all of these problems so you could check the videos I probably got it up by now I got a ton of them up this one's called binary tree for pruning I've done like all these binary tree problems almost so it's a medium problem a pretty good problem it says we're given a head node root of a binary tree where all the nodes values are either 0 or 1 so we're giving the week to a binary tree means you have a left and right node the children node and the node values are Warner 0 1 or 0 and we want to remove every subtree that does not contain a 1 so basically we're gonna traverse this tree and if we find a subtree that doesn't contain a 1 so we see like here this doesn't contain a 1 this is a subtree see this subtree right here but it has a right child of a 1 so that we're not gonna delete this node but this is a century where the left and right now they're null so that technically doesn't contain one we're deleting that and here right this is a subtree where there's no ones with any throws so you gotta get the idea we're just reversing and deleting a subtree so don't contain so first thing we're gonna want to do with 3 problems is just if it is no then we are going to return otherwise we're gonna call our helper method contains one on the root and then we're going to return because return we're gonna just modify the main tree that we're given and then we're gonna return the root because it's still going to be the root of the new tree which isn't a nutrients the same tree we're modifying the tree in place so public boolean it contains one it's going to be a method that we use that will tell us whether our node is a subtree that contains a one so we're gonna pass in a node here if we know it is equal to null we're just going to return the flouse right because it doesn't contain a one then we're going to have these new boolean values called Left contains where we do a recursive ball on the left if the left doesn't contain one then we're just going to set node left to null and remove that subtree completely and if the right doesn't contain we're going to set the right to null that's up three completely so we just remove the node if it doesn't contain because these will just keep doing recursive calls and it'll check the whole subtree so you can just take that one node out immediately and we're discarding the whole subtree so if we find that the left doesn't contain the right doesn't contain we just set it to no and then all we have to do after that is return that node dot val is equal to one left or left contains or right contains because this is gonna give us our this is gonna return true if we do see a one which is what we need to do when we do all these recursive calls if you see a one then we would see the left contains the right contains and it's also checking that along with or each of these left and right contains so if the value is a one or the left or right container on that it's safe and that's pretty much here we just return it and we'll submit it and this is should work see oh sorry we're putting the word always good to check stuff like that and that's it success so that's pruning a binary tree think that's what let's go up binary tree pruning pretty easy problem right there even though it's a medium but I like it was pretty good let me know what you guys think in the comments about explaining it sorry about the boning and there's people talking but yeah check out the other videos and thank you guys very much see ya
|
Binary Tree Pruning
|
smallest-rotation-with-highest-score
|
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**Example 1:**
**Input:** root = \[1,null,0,0,1\]
**Output:** \[1,null,0,null,1\]
**Explanation:**
Only the red nodes satisfy the property "every subtree not containing a 1 ".
The diagram on the right represents the answer.
**Example 2:**
**Input:** root = \[1,0,1,0,0,0,1\]
**Output:** \[1,null,1,null,1\]
**Example 3:**
**Input:** root = \[1,1,0,1,1,0,1,0\]
**Output:** \[1,1,0,1,1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 200]`.
* `Node.val` is either `0` or `1`.
| null |
Array,Prefix Sum
|
Hard
| null |
219 |
hello everyone this is kharid and today we are going to solve a legal question called contains duplicate number two so the let's read the problem statement given an integer array norms and an integer K return true if there are two distinct indices I and J in the array such that the value of I is equal to the value of J and the difference between the indices I and J is less than or equal to the given k so let's understand that more by reading these examples so in example one we have an array which can consists of four values so here we have a the value 1 is a duplicate and we have it here and here so we have met the first condition we have to check if that condition is also met or not so the difference between the index of that value and the index of that value is less than or equal to K so the index of this value is 3 and this value is zero so three minus 0 is 3 which is less than or equal to K so we should return true another example here we are given uh we have a duplicate of three ones this one and these two ones and we should now check the second condition if the index of that one is and minus that one is less than or equal to K so this one is two and this one is zero so two minus zero is two which is not less than or equal to K we should uh make the same comparison with the second one so three minus zero is three which is also not equal to three which is not equal to one and now we have these two ones and the index of that one is three minus two is one which is less than or equal to one so now let's look at the constraints that we have so we are not getting uh an empty array the length of that array must be from uh from one to that number to 10 to the power five and the K value is between 0 and 2 to 10 to the power five to the power 5 yes so the way of one way of solving this problem is by using um Maps and we should iterate first of all we should iterate over that array and store each unique uh value of that array so now for this example we use two or one and the index of that one so one and the index of that one is zero and we all will also store two and the index of that two is one and so on until we meet the duplicate value in that case we will make the conversion and we will check if the index of these values are less than K or not in case it is uh less than or equal we will we should return true otherwise we will keep iterating till we uh like till the end of the array so let's start coding we will initialize our map now we will make an um a for Loop that will iterate over the array so we will start it by zero and tell the nums dot lines and we will increment each iteration by one so as we said we will store each unique value in the map so if not if that value is not exist in the map if not map that has that value notes I we should set it to the map so the way of doing it is like this map.set and we should set is like this map.set and we should set is like this map.set and we should set the value itself and its index I otherwise like in this case we are sure that value is already stored in the map so it is a duplicate so in case it's a duplicate we have checked that uh condition we are now we have to check this condition so if map dot get that value nums I yes minus V minus v i itself if that is less than or equal to K we should return true I think we should get that value in the absolute so we are not getting any negative values like this uh so if these values are not uh if the difference between these value the index of these values are not less than or equal to Q I will update the uh the value of that of the current uh value so I will set it again set nums I and the new value of I like this and I will keep iterating till the end of the array otherwise in case we didn't get any match we will return false at the end of the code so let's test that out we are getting here our an error let's try to understand that we should return here the numbers I not the I itself yes oops we should like make that out of the foreign order error and now as we can see here we have successfully um solved the problem let's verify that by submit it uh I hope you enjoyed that video see you in the next one
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
216 |
okay this is really the problem 216 is combination three find or validate the combination of k numbers that sum up to so through any staggered number and k is the target length of the subsequence and we need to follow those conditions only number 1 through 9 are used digitally and each number is used at most was written a list of all possible combinations that the rest must not contain the same combination twice and the combination may be returned in any other so during this case example number one case with length is three and n is seven the target stem so crossport and two and one are seven there are no other valid combination because we cannot choose the number twice time because if we choose three but in this case the point is already used to the united states three if we got already this one so this is the only way in one case to generate the subsequent sum of seven so we need to first decorate the recursive function and we need to decorate the variable storage subsequence and apply this little list and this is combination and it's not permitted to select the right factor number twice so thank you sequence is the same as the target k10 we need to check the there's some other sequence register target number if that will use these conditions are correct then we just extrude the output into the sequence and all the password digit is one from one to nine so you can particularly write it and we just call the because you function with the updated start index and increase number like this and okay let me make the other one just to rather than this icing like this from the numb because it starts from 0 to 10. okay the number is that i need to try to zero from zero to nine okay so we i just need to push some one because and i need to put my spawn here because no means one is stored at the index of general but three pass one from here this is one i started from one so one minus one zero so lumps at the index of zero is one so it will work okay it worked like this okay it passed all the tests guys thank you for watching this video and please subscribe this channel and please click good for me to create the better content that might be helpful for you thank you
|
Combination Sum III
|
combination-sum-iii
|
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true:
* Only numbers `1` through `9` are used.
* Each number is used **at most once**.
Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order.
**Example 1:**
**Input:** k = 3, n = 7
**Output:** \[\[1,2,4\]\]
**Explanation:**
1 + 2 + 4 = 7
There are no other valid combinations.
**Example 2:**
**Input:** k = 3, n = 9
**Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\]
**Explanation:**
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
**Example 3:**
**Input:** k = 4, n = 1
**Output:** \[\]
**Explanation:** There are no valid combinations.
Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.
**Constraints:**
* `2 <= k <= 9`
* `1 <= n <= 60`
| null |
Array,Backtracking
|
Medium
|
39
|
886 |
Hello everyone welcome to my channel so today you may have Flipkart Samsung may have Flipkart Samsung may have Flipkart Samsung Okay let's move ahead so here I have leveled all the people okay and here I have given about their relation okay dislikes van kama 2 1 3 2 4 What does this mean? Dislike van Kama 2 What does it mean that van and tu jo hai nahi van tu ko hate karta hai tu van ko hate karta hai, so there is a relation between the two, you see this is van. And this is you, man, there is a relationship between the two, what is the name of that relationship, is it hit, right, both of them hit each other, right, and by the way, the van hits you, and you hit the van, right? Those people who hate each other, it is okay to keep them both in separate groups. Bye Partition means what happened. Bye Partition means two brothers. Bye Partition means two. Can we divide them into two groups or not? That has to be checked. Okay, by partition, just like van and you are hitting each other, so you ca n't bring both of them in one group, this group is van, this group is you, if we take man, then van will be here, you will be here, okay. After that, what is the second one? 1 3 means that one and three also compete with each other, so one is here, and three will have to be kept in another group. Okay, what is the third group, you are in the group, you are already here. Neither will we have to keep four here. Okay, so look, it is correct. We have divided all the people into two groups. Okay, we have divided them into two groups. And look, they have been divided correctly, is n't it? Van Kama Four is in a group, then Van Kama Four does not insult each other, see where it is written 1 4, it means that this is the correct partition, what is there here also, you are less three, you are more three, so look, you are more three. They don't hit each other, meaning they are fine remaining G2 means both can stay in a group, okay, I take the man, stays here in the input, here stays in the input, if van earns four also stays, then van and four hit each other. But look here, if 1/4 is put in a group then the answer is wrong, look here, if 1/4 is put in a group then the answer is wrong, we have to separate the four but what is there in the question, there should be only two partitions, here there are three, so this is what we have to find out. Can we do partition or not? Okay, we have to send True or False whether partition can be done or not. So let's see and understand. First of all, clear this thing whether the relation is given or not. Look at the relation, it is given here. But this is a relation and numbering has been done, people have been numbered and labelled, so it is clear that brother, this is a graph question, okay, this is a graph question and how to do this in a graph question, see, my index is 012, right? Okay so you see van and tu relay van and tu van earn tu jo hai what does it mean that van jo hai hits tu ko van jo hai add tu ko and similarly tu also hits the head van. Okay, after that 1 is 3, so as soon as the van hits you, it also hits the van three and similarly three will also hit the van, after that you will make four and then 21. How did we get the graph? The question of the graph is and We have just converted the relation into adjensial. Okay, this is understood. Now how will we know whether it can be done by bipartite or not? It is an obvious thing that our graph is being made, should we first make the graph and see. The graph is formed, this is van is going to two and three, right arrow is two, I take it, ok, you are also going to four, ok, you are going to van, ok, this is our graph, now we know Whether you want to do it or not, then remember, Van and you have become each other, so let's see, there is bye protection here, what is happening here, see, Van and Four will be in our own group and you and Three will be in our own group. I will be fine now but this is fine meaning it is very good to understand like this but how will we solve this in the court ok so let's see further how this will be solved so first of all let's see our approach closed that route four How can we think about this question? Okay, first of all, let's see that one, three, you are four, one, two, three, what comes to our mind first is that it is given in the question that we can do two partitions, right? Now we are here, we are processing Man Lo Van Kama 2, so Van and Tu will have to be kept separately. Okay, so first let's check that you are not in the set van. Han, If you are not in the set van, then here Van. Ok, let's keep tu in set tu, okay now let's come to van ko three, okay so van kama three, van ka van and three will have to be kept in different places, so first of all in set van. Let's see, if you keep van in the set van, then there should not be three there. Right, if there is no three in the set van, then you can keep van, then it is okay, van is already set, now you keep three on set but see three. Before placing it on the set, we will check that there is no van in the tattoo. It is okay. There is no van in the tattoo. Is there any relation between you and three? Are you and three a group? Do you head the other one? That also has to be checked, so is it so, otherwise three A can be done here, okay, now let's come here, 2 is near 4, okay, so you and four will have to be kept in different places, okay, so first let's see the set van. Main tu hai nahi hai set tu me tu hai han sed me tu hai toh set tu hai toh can't keep four in the set van. We will keep four in the set van. Okay and when is four kept in the set van? We have to check that in the set van. If there was already a van in the set van, then somewhere we don't do 14 heads, do n't we? Here, somewhere such a van is not comma four, so it means this is the right solution for us, okay, so we have processed all the addresses. Took and we saw that we have distributed it to everyone in 2 sets, there was no such problem anywhere that you have to keep checking the condition set many times that if you take the van, then first of all check that the van is already in the set van. Or it is not there in the set, it is okay, after that if you are going to put the van in the set van, then you will have to check whatever is already there in the set van, it is not being used by the van, so it is beautiful, what has happened? You can also try but this is very un-you know very but this is very un-you know very but this is very un-you know very slope approach is fine but our man should have learned this approach, you can explain in the interview that it can be solved like this but now it comes because it is based on the graph. If you have a question, then there will be something in it, if you know how to solve it from the graph, then let's see our approach, you can see how to solve it from the graph, then this is our input ready, okay, we have shown the gas agency list. Had given, we will make it, okay now look, now you can think like this, if you have to divide all the notes into two parts, some notes will be here, then reduce one, give different names to both, then different marks. Let's mark them as we take them, do it like this, we will mark those who belong to the group van, we will mark them red, okay, we will keep their color red, either we will give them a number, okay, we will give the van number and they belong to friends. We will mark them green, okay, we will not mark them green, either we will make them numbered, we will make them zero, okay, it is clear till now, so now look, now we have to number the notes. 1 Some notes will be van, some will be van. The notes will be zero, those with note van will come here, in this group, those with zero will come here, now if you want to number all the notes, you will have to go to all the notes. To do the numbering, you will have to go to all the notes. What means, we will have to traverse our graph, okay because we will have to go to all the notes and name them, some will be signed by van, some will be signed by zero, okay, how can you do this with DFS or So every time I tell you with BF, these two are very important, so now we have done a lot of DFS, so let's do one less, today we solve it with BF, okay, so look, the first thing you had to know is that we Will we have to do a towel or not? It is okay if we have to do it is an obvious thing, so we will find out that we will have to make a traveller, some notes will go in the group van, according to whether you are in this relation or not, we will keep checking the relation and in the end we will see that somewhere. There is no conflict, there is conflict, it means return falls, new distribution can be done, if not, we have assigned everyone properly, if there is van energy, then it means we will do return through BF, okay, if it is clear till now, then we will do it from BF tower. Now let's see how to do it okay let's see how we are just going to do it so let's do BFS what should we have for BFS should be K right so this is our K okay why is this mine now look first of all start Let's do it, let's start from the van, okay, and we will have to make noise at one place, okay, which note has been colored, like, we have distributed it, we have assigned it to some group, at least one Let's reduce it, we will keep one vector, okay, this is a kind of vector named widget, but in this we will also keep the information of color, which color is it, neither is note number, one is note number three, nine is number four. Right now we will assign them, there is no color yet -1 -1 -1 -1, everyone's color will be no color yet -1 -1 -1 -1, everyone's color will be no color yet -1 -1 -1 -1, everyone's color will be ok now, and what is the color, if there is zero then it is green, ok then it is ok, we started from the van, ok. And we put the van in K, okay, and I take it that we put the van in K, that means that process has been done, okay, so if that process has been done, then let's put it here. Let's mark its ray name, let's keep the color, okay, we have named the color, okay, we have marked it here and what color should we sign it, let's mark the van as red, okay, we have assigned the van to this red one. Diya, it's okay, the van guy who is in the group is here, so now the thing is, the van who is there, he keeps harassing you and three, so you and three should not come here, brother, this is clear in this group. Meaning, you and the three are the notes, you and the three are my notes, their color should not be one, if there is one then it will be false, both of them will come in a group, their color will have to be kept reverse 0, right, their color will have to be kept different. Let's start, first of all we have popped it, let's go to the van, okay we have sinned the van, okay now we have popped it, after that we have to see where we can go with the van, meaning the van. Who has relation with whom does the van hit, so we have seen that a good adjuncil goes in it, so what are you and three, then it is okay, you and three are whom he hates, so first of all we will see where. Now we have come to you, so you do n't have any color, you have never been through the process, so if I came to you for the first time, then okay, that is, let's reduce one from CR, let's change you to K, okay, don't red it. Can means van can't Ok tomorrow let's make the ring green so its green because van tu hit each other so van tu ka could not be kept in one group till here it is clear ok remember We gave you a team but remember it was in the neighbor of once and there was also three. Let us come to three. Okay, now we come to three. Okay, so when we come to three, let us first see the color, which is the color of three. Now remember, the van does not fill the van's worth, or you earned three from the van. If yours is less, then the color of the three is not equal to the color of the van. If it was not equal, then there would have been a mess because the van. And hit three. Tomorrow cannot be equal in both of them. There should be different colors. If the process is not done then ok let's do the process then what will be its color? Which is the color of the van? Which is this van? Its color is red. If not, then we will have to keep its color opposite to that i.e. we will have to keep this also zero, we will have to i.e. we will have to keep this also zero, we will have to i.e. we will have to keep this also zero, we will have to keep green, three will be kept separately, three will be kept in a separate group, so we have kept three here, we are okay and pushed three here, you see BF. Nothing else is going on, it is clear till now, okay, this is done, now we have come here, we have forgiven you and 3 of the van, okay, now we will process 2 and 3 again, here you are our. After that let's see where you can go from Tu, if there is any relation of 2, then Tu's relation is van four, van nikali van kama 4, so first let's come to the van, okay, so first of all, check the color of the van. It is not equal to the color of 2, no, it is not, no, pay attention, where was the relation with you, the van was equal to four, okay, so first of all, we picked up the van and are looking at the van to see whether the color of the van is equal to you. So no, absolutely not, both of them, one is green, one is red, so that means, let's go from CR, okay, one more thing, let's check whether you need to push us, why not me, because this is a mine van, already ready. If there is a process then why won't you put Tu again? Okay, if Tu's story is over, then Van Ko is okay, he is not equal to Tu, because Tu's neighbor Van earns four, if you hate van and four, then four's color is yours. If it cannot be equal, then four is not equal to you, because four is still minus one. Look here, and four minus one means that four has not even been processed, so we can group it into K. Okay, so why should I group four? So what will we give but the color of four, what will we keep, whatever color you have, we cannot keep it, if your color is green then we will have to keep four red, because whatever you are, it hits the four, so the four which is your color. It cannot be equal, it is green, look here, what will have to be kept, we will have to keep van, it has become zero, ok, van and four are also there, here we have written 3, okay, look at equal, it is red, that is, van and the color of three is zero. That means if it is green then it means it is not equal i.e. is not equal i.e. is not equal i.e. if we are not mines van then no this is not mines van means three process has been done then why would we put three then again we checked the van that the color of van is equal to three. So no, it is greater than CR safe and the color of this van is not a minus van, it means this process has been done and it is correct that the process has been done, look, we have signed the color of the van, so why should we sign the van again? We will not put it, its ok, now let's come to you, ok, here it is relative, red means CR is safe, the color of both is different and the color of you, see, is zero, which means we have assigned it, we were doing the process. Do not put Tu in K again, okay, we have signed all of them and so on and we have completed the process, the story is over and we did not find any conflict anywhere, please note that conflict was not found, which means our answer is true, right, red. It is 143. Look here, you are van and four, and the 3 that is green is absolutely correct, it was very simple, we just had to do the coloring and we will just convert the story from whoever has heard the story, whatever story has been told in the court. It has to be converted in the court, just nothing else, after that just see the last thing that sometimes it is 123 and some graph is also given like this, it is okay that those who have not been visited will run BF on them like if on the van. If we run BF, then 123 will be processed, their coloring will have been done, but 456 children will be left. It is clear till now, okay, so this was simple. Now coming to our part, which is ours, we have to convert the story into code, okay? Let's convert it, so let's start recording. You must have understood the question. Easy question to understand. Okay, let's come to the direct code and of course I will do the same as I told the story. I will just convert it. I am in the court. Okay, what have I done? He said, first of all, we make the adjacency lace, which I have told how to make these vector offs. Okay, what should we name it? DJ keeps it. Okay, now what I said, let's make an ID ADG. Okay, vector off and These people have given a vector named Back Dislikes. Okay, if you hit Brick U = Back of Zero, then there is a relation between the two, that is, it was created by adding Ajaz Jo Hai. In the beginning, someone's color is minus Van, which means no Van. This process till nine is ok, its size will be kept as N + 1, right, there are till nine is ok, its size will be kept as N + 1, right, there are till nine is ok, its size will be kept as N + 1, right, there are notes from the beginning till the end, ok, now let's come to its processing, what I told you is that there can be different components of the graph, ok, so all the notes You will have to check whether the BF of all the notes has been run or not, otherwise for others this is equal to you van I <= coloring of them has not happened means that process must not have been done then color off if mine is van means they are not the process is this yet? If the processing has not been done then it is okay then we will run BF on them, okay and if BF is run, check bye is okay and what else are you sending the current note, what is the current color, you are sending the color, okay then it is simple for you guys. I push the current note and if it is pushed then I color it, I take its color, I have kept it as a van, now it is okay, I have kept the color of the starting note, okay now it is simple until you see it. If its coloring color is not going to be where it is going C, if the color of U is equal, then both of them hit each other, they should not be for color, then Bhai will return false, if it should not be equal, then it is okay and Second key, when will we put V in K? If C processing has not been done, then the color of V key is C. If you are equal, you are mine, that is, if processing has not been done, then we will push it to K. It is C and we will push it into K. Meaning, once the process is done, then sorry, its color is also changed. What will you keep in the color of C? You do n't want to keep the color of U. Right, so if you look carefully here, what will you keep in the color of U? It is clear till now, this is if K. Nowhere have we done return first, meaning C is good, we will start returning last. Okay, let's run it and see if it has passed all the exams or not Great, let's see by submitting it. You gas in next video thank you
|
Possible Bipartition
|
score-of-parentheses
|
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group.
Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_.
**Example 1:**
**Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\]
**Output:** true
**Explanation:** The first group has \[1,4\], and the second group has \[2,3\].
**Example 2:**
**Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** false
**Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups.
**Constraints:**
* `1 <= n <= 2000`
* `0 <= dislikes.length <= 104`
* `dislikes[i].length == 2`
* `1 <= ai < bi <= n`
* All the pairs of `dislikes` are **unique**.
| null |
String,Stack
|
Medium
| null |
455 |
hey everyone today we are going to solve theal question assign cookies okay so let me explain with this example so G = let me explain with this example so G = let me explain with this example so G = 153 and S = 153 and S = 153 and S = 412 and your goal is to maximize the number of your content children and output the maximum number so children with smaller grid factors are easier to satisfi so I think it's good idea to sort both arrays and check from the small number so in this case so D should be 1 3 5 right and S should be 1 2 4 and then description said this is a i index and this is a j index and uh every time first of all we check both index number and if um they are less than each length of array so we continue in this case I and J are zero right and then length of array the three right so we continue and then um so let's focus on the first child and uh this child has one for grid factor and the current cookie is one so this child is satisfied with one cookie right so in that case um so we move I index to next because this child is satisfied and then every time um so cook index J move to next even if uh children is not satisfied so J so now again check both index number and they are less than length of each array right so that's why we continue so in this case so current child has three for grid factor and the current cookie is two cook cookies so um this um child is not satisfied with two cookies right so in that case um we don't move I index only move j index to next so that's why I said even if uh children is not satisfied um we move j index to next and then check both um index again and uh less and length of ARR right so that's why we continue and now um this children this child has three for grid factor and current cookie is four cookies right so now this child is satisfied with four cookies so in that case so we move I pointer to next and then we move j poter to next and then now um J is out of bounds so we stop iteration and then all we have to do is just return um I because uh we can uh make two children satisfied right yeah 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 a code first of all we sort both array so G do and S do so and initialize um index I with zero and the J with zero and then start ring while I is less than length of G and J is less than length of s in that case we continue and if so current children GI is less than or equal current number of cookies so s and J so in that case um current children is satisfied with current number of cookies so that's why we count um that child as one so that's why we move I index to next and then as I told you every time so we move a j pointer so J plus equal one yeah actually that's it after that return I yeah so let me submit it yeah looks good and the time complexity of this solution should be order of n log n plus M log n because we use two SS here and the space complexity is I think o n or order of log n um it depends on the language you use so in Python building sort function use like a team sort which is a on space so that's why um total space should be two order of 2 N and uh we can eliminate the constant number so simply space complexity is o n yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Assign Cookies
|
assign-cookies
|
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number.
**Example 1:**
**Input:** g = \[1,2,3\], s = \[1,1\]
**Output:** 1
**Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
**Example 2:**
**Input:** g = \[1,2\], s = \[1,2,3\]
**Output:** 2
**Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
**Constraints:**
* `1 <= g.length <= 3 * 104`
* `0 <= s.length <= 3 * 104`
* `1 <= g[i], s[j] <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Easy
| null |
68 |
hello everyone uh welcome to i'll go pundit today we are going to solve the question number 68 uh text justification so this is a famous question has been asked in the last six months across multiple companies like intu twilo uber amazon so this is a very famous questions and it's been categorized as a hard question so given an array of words and a width maximum width format the text such that each line exactly max with characters hence and is fully justified you should pack your words in a greedy approach that is back as many words as you can in each line pad extra spaces when necessary so that each line has exactly max with characters extra spaces between words should be distributed as evenly as possible if the number of spaces on a line do not divide evenly between words the empty slots on the left will be assigned more spaces than the slots on the right for the last line of text it should be left justified and no extra space is inserted between words and there are additional notes here a bird is different as a character sequence consisting of non-space sequence consisting of non-space sequence consisting of non-space characters only each word's length is guaranteed to be greater than 0 and not exceed maximum width the input area of words contains at least one word so in short this is the text just justification in the microsoft word so uh everyone has used a justification where it will arrange it will evenly distribute the space and it will arrange the line uh to left and right so this is the text justification so the constraints here given are there are three constraints basically if it is a last line then it should be left justified and if it is not matching the necessary maximum width then you will add additional space into the right hand side of the line and the second constraint is if there is only single word in a line then it will be again left justified then there will be you will be adding uh additional spaces on the right hand side if it is a regular line uh then you will be evenly distribute the uh space in the in that between the words basically so let's take an example of word uh the example so this is an example of text justification so that's the words input and the maximum width is 16. so the output will be the first line will contain this is n so and there are additional space added between this ease and second one example of text you can say that additional line is added between example and off and the orphan text is it's there is only one space and the third line which is the last line and it is aligned as left justified and then additional spaces are added on the right hand side for easy of uh explaining the solution i have already completed the solution here so let me do the walkthrough of the problem so like i mentioned that we can do this in two-step process first one is look in two-step process first one is look in two-step process first one is look through the array and collect maximum possible words for each array item and also keep track of another array which contains maximum letter count in that position so basically i'll be looping through the words the input words and every time when i look through it i'll be collecting the words and whenever it reaches the maximum width i will be assigning that into a groups setting and second step will be once we have the groups array then we have to distribute the space evenly okay so let's do a code workthrough so i have defined two constant and two variables here groups and a line then i'm looping through the words so initially i'm pushing the word into the line which is a temporary array and then i am joining with a single space if the length of that line is greater than maximum width i will pop the last added element last added word and then the line will be added into the groups with the empty speaker joining with the empty space and then the word which i popped earlier will be added back to the temporary array so this process continues until you have all the words considered and then when you complete the complete this loop for sure the line dot length will be always not equal to 0 because there will be always one word which we will be missing it out so add an additional condition if the landlord length is not equal to 0 we need to push that particular line back into groups so this step will basically collect all the words it basically collect all the lines for the particular group study okay so now the second part will be how do we how do you how do we distribute the space evenly across each line okay so there are three cons constraints as i explained earlier so the last line should be left justified no space to be added in between words then we have to evenly distribute a space for all other lines the third one would be if it is a single word again it will be the left justification as well as add padding spaces on the right so here we'll be looking through the groups which we created in the previous step so with this if condition i'm basically checking the first and the third constraint which is last lane as well as single word so if it is a last line or if the length is only one if there is only one word in the line that's an easy one so we can easily calculate the difference how much space we need to add it and add that into the uh element okay so that is an easy step the second step in the how do we distribute evenly the space for other words okay so you need to calculate the space so here so take this example this is n right so if we thought without having this distribution it will be this is n so here the count will be uh one two three four five six seven eight nine ten the total length is ten but what we need is sixteen right so there is a difference of six spaces is required in addition okay so the spaces will be six so now we can do a loop so what we're doing here it is we're looping through the space total require space and then looping through the split element so each time when we look through the word in the line we add additional space all right so split up we already split it based on the uh based on the space then we add one element say so this one will look like after the first iteration for after the first loop so this is okay and if i compare then it will be like this them okay now second one i add a space here so now the third one will come it will add additional space on the first one and it will go here same way it will go it will add another space here so this way it will evenly distribute uh starting from the first word onwards so it will evenly distribute it and every time we reduce the space by one all right so this loop will continue as long as you have as long as the space value is greater than zero so once it is done it will split it will exit the loop and then we can simply join all the words using uh the split judge split or join method which and then we can ascend to the groups of five and finally uh we can return the groups and this will be a fully justified lines array of lines all right now let's try to run the solution so i have tried i tried with a very big array which contains more than 30 or 30 40 characters and looks like i got it wrong so let's see what's happening here why did i get it wrong ah okay so by mistake i deleted one line all right so let me put it back and okay now if you can see that so it's running it and you can submit the solution you can see it is 80 milliseconds is faster than 59 50 almost 15 percentage of uses so this i hope everyone understand the solution so this is a very frequent ask question across multiple companies and it's a pretty good one actually it's hard but it's very uh it's a tricky one actually basically so yeah see you next time
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
343 |
hello i don't have a name but you can call me now and today i would like to talk about the third dynamic programming practice question integer break in this question we'll have an integer of the inputs and we need to break this integer into certain parts for example 10 can we break into 3 and 4 because the sum is 10 and then we can multiply this integer to get a new integer and the problem needs us to maximize this integer and in this example 36 is the largest integer so we can directly output 36 and that's the confidence is that we need to break it into at least two pieces so if the input is 2 we cannot output 2 but we need to break it into 1 and then output 1. so as usual the first step is define the recurrence and we can define the recurrence by trying it out so if we need to solve the problem n equals to 10 i will try to break it into 9 1 8 2 7 3 6 4 and 5. and see how to break it will return the greatest answer and here to bracket 9 1 we are not actually breaking into 9 1 because 9 can be further break into 4 and 5. so here i'm meaning i break it into the maximum break of 9 and i'm bracket with the maximum break of 1 and there's the recurrence and after defining the recurrence the lookup table is very simple what is the problem of other subproblem with size n equals to this integer from 1 to n and the dependence is from right to left because f10 is dependent on all this sub problem for example f10 is equal to 9 times four which is breaking ten into six and four and then break six into three and three after breaking six in the fifth and three times three is equal to nine and is the greatest integer break of 6 and the greatest integral break of 10 is f6 times f4 which is 9 times 4. so we will first fill the table with the base case and the first base case is n equals to 1 and here actually the problem will not ask us to input a one but here i set one as one because the information we need is actually one if we are using this answer we are we have already break the integer into at least two pieces and we do not need to further divide the one into several pieces so we can directly use one if we need to use it to solve the later problem and similarly for input equals to 2 or 3 the output should be 1 and 2 respectively but here i write 2 or 3 because when we use this answer to solve the later problem we did not need to further divide two or three into several pieces so the information we need is actually two and three instead of one and two and then for solving four i can use the recurrence i will divide into one and three or two and two so f one times f three is equal to three and f two times f two is equal to four and 4 is greater so i will choose 4 and for solving f5 i will try f1 times f4 and f2 times r3 is greater which is 6 so our output 6. and after filling out the whole table 36 is the answer we need and as mentioned the 2 and 3 are special case and i do not write the true output in the lookup table so in this two case i will treat them as special case and directly return the answer so the program look like this first i will directly return the special case and then i will initialize the lookup table as this and n equals to 0 is an invalid input and it will not be used in any case so i can just initialize it with any number at once and for the first free number i will initialize it as one two and three and then i will solve this a problem from left to right so i will solve f4 first um for it's a problem i will try all the case of integer break for example f10 i will try 1 9 2 eight three seven four six and five i will try five cases here and which is equal to ten uh divided by two so i will try five cases here and try from one to five and each time i will try answer j times answer i minus j for example when i equals to ten and j equals to one i'm trying one and nine and i will pick the maximum answer from the all this case and finally i will append this answer to the local table and finally i will return this integer as the answer and that's all for this video bye
|
Integer Break
|
integer-break
|
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58`
|
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
|
Math,Dynamic Programming
|
Medium
|
1936
|
647 |
has been asked by Facebook Goodman Sachs Amazon arobi Apple C Google Bloom Cisco xedia auna Capital Microsoft wmart Labs work day LinkedIn and so many companies hi guys good morning welcome back to a new video in this wey PR palic substring now the folks who will watch the full video can please skip the next 5 seconds and folks who just want to skip this video and our first time we will discuss all the approaches from very Brute Force then Brute Force optimization then better approach and then another way of the better approach which means DP which means in top down and bottom up both and then the most optimal approach which is in the last and then on top of it on top of the most optim approach again two approaches which are actually which you would not want in interview but still we will just show you that what it is cool let's start off uh that's so many approaches right yeah it is uh but yeah let's start off it says pic substring as simple as that we are given a string s and we have to return the number of palindromic substring now you know what's a palome is something which reads same forward and backward as in if I say a r y r a don't know what word is it but yeah a r y a so you can see it is same and same so this is a palindrome okay now substring is a part of a string continuous part of a string so if I say r y r a this is a substring a r y a r a this is substring this is subst string so all these are a substring now we have to find out the number of palindromic substring which means I will have again very I'm not doing anything I'm just reading the question out loud I will just say I will get all the substrings now you know that how many number of substrings are there in a string simply substring is nothing but a piece of block inside a string in I can keep in so that I give get a piece of block so I can simply say the number of substrings or number of sub arrays in an array as simple as that can be nothing but o of n Square so I will have n Square substrings now for every n Square for every substring I will have to figure out if that substring is a paland room or not now as we saw that Parr is simply nothing but something which reads same so I can simply say now if I want to know if this thing is a paror or not I will start off from the super ends right I will start from the very end of this and then if they are same great then I can simply go and find the answer for okay go and find if they are same or not if yes then go and find if they are same or not and so on so forth until I reach both are equal or they overlap which means in the case when the size is even where let's say a r a so a will be here then both are same okay r will be here and then both are same then again it will keep on moving like pointers keep on moving right so you will simply say that now it's actually a Parr if something over overpasses each other so that is obvious that for every n Square substrings I will have to go and check if that substring is a paror or not and for that we can simply either see either you can do iteratively which means you are standing here okay both are same then you can simply iterate and next try on for the smaller values which means this and this next smaller point is if not then ask recursion to do for you which means you just simply compare one of them and ask recursion to find the answer for the middle of them that's it so anyway again I'll show you that what it actually how it differs and all that stuff but still we have n square substring and we can find the answer for all the substrings so we know that okay to know it's a parm or not we will take o of n time to just simply on the entire string and know if it's a paranorm or not so one very basic thing which you saw was that's simple it's a simple boot force and see boot force is nothing but whatever came first to our mind or whatever came after read the question exactly so we try for the all these substrings and then I will check if that is a palindrome or not so you can simply see it's a o of n Cub time now in that I showed you let that I showed you that you can simply go and try by yourself these two values and ask your recursion to do it recursion to do and find if the middle portion which means if I am I and J I going ask I + 1 J minus one if that is a going ask I + 1 J minus one if that is a going ask I + 1 J minus one if that is a paror or not I can ask my recursion to find my answer but although for this for the technicality thing people might say okay now it is actual brood Force the actual better approach is optimizing this Brute Force but I think that it is much more not intuitional to think of recursion directly in this problem it is much okay to know the parador or not you can just simply use two pointers right it is much more intuitional to think again it's St up to you comment down below what you think it is more intuitional if you want to know if something is a paranormal not will you apply recursion on top of it or will you simply iterate as in used two pointers now if you are saying that you'll apply recursion then great so you can simply apply recursion and that's what we going to see in simple boot force that we will simply try on for all the possible I and J combinations and because we have to find out all the sub arrays or sub strings right then for that specific a combination I will find if that is a palr or not now to find that if that is a palr or not I can simply use my recursion how I can simply say the if I am at this specific two characters I and J if they are same go and find if the middle portion is also a paror or not so if they are same I can go and ask if I + if they are same I can go and ask if I + if they are same I can go and ask if I + 1 and jus1 is a paror or not if not then simply return or false and base case as I showed you if I and G both are equal or both over passes equal will be in the case when the string length is odd overpasses in the case when the string length is even so I simply wrden the one because I have reached the end super or overpass it so please return the end with this I can find my simple if it's a paror or not now because of this you can for sure know that this will take o of n Cube time because of n squ for the subst string and to know every string is a paror or not again of n time so time is of n Cub but space will also be o of n because of the recursion which you are using because the recursion so recursive stack will be there so it's roughly o of n by2 but still it's like roughly o of n so you will say okay the space the time is O of n Cube space will be o of n in case of recursion but as we as see according to me the more intuitional way to find if something is a paranor or not is two pointers I will keep two pointers like I and J and can inter from the super back and can figure out okay if that is actually a bendr or not so I can use two pointers which is a optimization on top of the Brute Force which you might have thought of but if I would have been at your place the first Bo for approach which I would have given or basically would have came to my mind in the interview would have been that okay time will be of n Cube and space will be o of one but still uh if this is also uh was on your mind that's still completely okay uh that is because it is actually better like okay you are getting from the most worst approach to actually the best approach so this is the worst which means time is O of n Cube and then space of O of n then we can optimize it by using two pointers in the same bu Force approach to actually get it as space of O of one now although my n is up to 1,000 but still you will see that up to 1,000 but still you will see that up to 1,000 but still you will see that this o of NQ solution will pass which should not have been the case because 1 E9 is not the complexity which should pass but still you will see if you just go and submit this code it will pass it should not have passed but that's the issue with lead Code test cases now coming on that we have to optimize it for sure because this will not pass now if we can simply go and check back what we were doing we were at this specific I and this specific Jil let's say right now if it matches although it is not matching right now but yeah if it matches then I would have gone inside so if I was at I and I was at this specific J if it matches because a and a is matching then I can go and ask for the middle portion which is I + G minus one middle portion which is I + G minus one middle portion which is I + G minus one that's it same way um same way if I was at this specific I this specific J right I can go and ask if I + 1 Jus one which I can go and ask if I + 1 Jus one which I can go and ask if I + 1 Jus one which means this portion is a palr or not now if I ask you if I was at this specific I this specific J wasn't it the subcase of what we saw previously which means this specific I this specific J if I'm going and finding answer for it okay that's great you found it again let's imagine there are multiple things in between it also let's imagine okay let's imagine X Y let's imagine this for now so you saw that okay I and J let's say you have got the answer yeah it is a Parr now let's say in the next step in future you were asked to find bro I N J is this a par or not then you can simply go and check okay I and J both string are equal then your recursion would have gone and basically your two pointers would have gone and asked for the inside string which is I + 1 G minus one and if you which is I + 1 G minus one and if you which is I + 1 G minus one and if you remembered earlier only I have found this answer it's the only thing I did not store its answer so oh which means there's a problem which is repeating and it will be very beneficial if I store the answer for that problem so I would know okay um if I store this problem answer that would be great for me I don't have to iterate on the entire string again so what I will do is when I would have calculated the answer for this portion of i g I would have said okay let's imagine this index as two and this index is 3 4 5 6 six so this index is one this index is seven let's imagine that so I would say that my DP of I which means DP of 2 comma 6 is actually a true which means that is a parent so if I'm going and finding the answer for 1A 4 which means 1 and 4 if sorry 1 and 7 if that is a par or not then I say okay 1 and 7x both are same then my sub my recursion on my two pointer would have asked me to go and find the answer for 2 and six but 2 and six I have already stored with me so I will not recompute that and thus I would not be recomputing again and again now uh many of you might have understood that the complexity because of this would have been reduced to O of n² because now you will go to all the substr strings but you will find that okay I will go and find if that substring is a parador or not but I will not be Computing that again and again for all the substrings if something has been computed already I will just use that so many of you would have understood it that in the above code which was O of n cube right now because you saw that was exactly above code right in that I was Computing a parent room for that specific substring but the only change which I did was now I am storing those values also which means I took a memorization for my like DP simple like although technically you will say okay it's not actually a dpdp intuition problem but yeah um you can just simply say okay you memorizing something you can simply use a DP for that now I know that I will use a DP I initialize my DP with simply inj because in both can be up to L so it is of the size of my actual uh string size now if something has not been computed then simply compute that and return that in your ppfi if something has been computed then simply return the value if it was true or false or a one or a zero in this case now Aran why did why you did not took a Boolean value for a one or zero true or false because bro uh you can see I have to also put a minus one just to say it's a default value so I need three values technically so I should be taking uh either I can make a bit kind of a like a bit set array you can also make um in integer sorry in C++ can also make um in integer sorry in C++ can also make um in integer sorry in C++ but yeah s integer will also work fine that's not a big issue for us so we saw that we will simply be using memorization now many of you would have understood it because of this optimization which means because of this memorization which we have did the time complexity would have been reduced to of N squ and for sure we are also using this entire Vector of NN so for sure the space will also be of n square but many of you would have been confused that okay Aran I can still see that you are going up to you are trying for all these substrings and for all the substrings you are again going and finding the answer for a string if it's paror or not so how again that operation can be o of n in the worst case right because if your I andj is here then you can okay maybe you have not recomputed that so you will just recompute that if in the very beginning you must have not recomputed that so you will be Computing that right so how will you say the answer is O of n squ so for the folks who know this can skip this portion but for the folks who don't know I'll just explain you in a very short way that let's imagine that you were at this specific I in this specific J right now if I say that you would have already computed the answer for this I and this now you might say okay that's a very edge case okay both I and J are here so I would have comped that answer so when I was at this specific the specific J I would already be knowing this specific answer so at one subring I went on in just over one operation that because one operation which means comparing inj and then I have already completed my answer in my DP so that is waa done for us for example other example is let's say I was Computing this I in this J I would have already computed this specific b and a but Arian what if I had not computed no worries if you had not computed this already then you will go and try for the smaller value which means you will go and compute this right now in front of your eyes okay I'll compute this I and J now when you will compute this I and J right now in front of your eyes okay you will say okay it's not a palr okay it is not a palr that's completely fine but you will also store that so that in future when you will come back on the same in again let's imagine you have multiple uh characters in between also when you would have come back on the same in because of this specific in you would have already computed its sub problem which was this portion and because of this you would have already known the answer for this in so you would never recompute this answer right so you saw that either the answer either this all the answers are computed because of this step or it was already computed and then I was using in for my parent answer it can be two ways for to summarize in the last example I can say okay this a and this a let's say it is matching again it is matching so and again I let's imagine I don't have the answer in between portion again if I had the answer previously then I would have already given an O of one time but if I did not have the answer I will go inside which means I'll go at this side this J okay let again say I did not have the answer for between I'll still go inside this side this now okay both are true so this will simply true but because of this I and this J this value will never be recomputed again okay this I and this J will never be recomputed again this I and this will also be never recut again so you saw that you have optimize it by not recomputing that again and again either because of child the parent will get recomputed o of one or because of parent my all the Childs will actually be Rec computed in that o of end time but as soon as I'm I will go on to my child next time it will be already had been reced by because of my parent and then I will return a off one time I can simply return so you can see that time is actually of n Square many get confused how it is of n Square so that's I have explained it now um although it's just Overkill to make its bottom of approach but still people are I don't know why but curious to know the bottom of this so for those who are C can listen this portion else if you don't want you can skip this entirely although I say it's good to listen bottom of approaches but I am not a big fan of it I don't know why but still again linear DP which means 1D DP you should for sure I'm not saying it's optional you should like no technique linear DP which onep you should for sure know bottom up for sure for 2 DP you can skip that also okay coming on back uh that we have again if I just have from the very bottom because it's a bottom up so I'm go from the very bottom and tell you how you can actually go about it again usually we have seen that from the top down code we can just simply convert line by line to bottom of code as we have seen the previous videos if you have not watched you can just go and watch their de inition building playlist but for some problems it is not very easy to build the bottom approaches so for that we have to go from the very scratch how things are working so if I just go on and make all the possible AR of the specific string or sub strings for the specific string then it will look something like okay starting off from a I will have a Ab as you can see a Ab ABA all things I have I written a Ab ABA again you can just have it a snapshot or you can write par with me also uh a and all that so I have done all of it for all of the okay starting from B itself B ba so I've get I've got all the possible substrings now very obvious answer is the one having a length of one right that's a palr for sure that's a palr a length of one is for sure a par now if I ask you a string s what's the normal base case you will give okay Arian in the very beginning you saw the base case which you gave was that okay if I and J both point at this location or because of the characters being same let's say A and A so I and G were here but it has to go and compare them as it Compares them the I pointer surpasses each other so I G was here and then it surpasses each other so I can simply say base case right something like okay one base cases that you just land on to the same character other base cases you land on to two adjacent characters right which means two Adent characters so I can represent the same thing by saying that okay one character itself is a palr so I can simply say the a right here is a palr okay let me change the color to pink baby pink cool uh a is actually Parr B is a Parr a is a p b is a p and C is a p okay great but again the next Bas case was of length two we have to go and have a check so I'll just say Okay a n because it to be same to be a par b n a ah it's a par a b now we have completed the base cases okay let's simply plot those base cases at least on our Matrix now how to make this Matrix simply okay we know that we have a 2d DP which means it's a grid it's a matrix now to Simply plot a matrix okay and if I remember my DP state was the I energy which means I is the indexes it's indexes so I know okay my one state will have all the indexes from one to from 0 to nus1 other will also have 0 to nus1 so I can simply represent the exact same thing as 0 to nus1 that's actually how you go about it but then you actually also realized that at every point I have to compare because if you remember in your simple DP approaches you compared the characters also at that specific I and J indexes so for the indexes also you would be needing their corresponding characters so I plotted the same on my grid also the character also but remember how you build up many people just start building and putting the correctors actually here it is not the case because of the DP State B indexes you firstly pled the indexes now because of the indexes you would want to know what characters need to be at that location so you actually plotted the actual characters also at that location now great uh now one thing if you have remembered or seen so far is in the simple approach also that your I and j i and J never went beyond again for this case for one just for just one case where your J went beyond your right and that we have already covered in a base case for us because I never because I considered this case Okay IJ so I know I is always in the left of my G so one thing is for sure that whatsoever values I will plotting in my DP Grid in this grid if I consider this entire portion if I consider this portion as my I index and this portion as my J index so I will never be going in such values where my J is less than I so I will never be going onto these locations where actually J is my less than my I so I will simply go on to the remaining locations which are empty in the grid now uh we simply PL the simply plot the base cases so base cases when I is equal to J which is this line specific line because you'll see in are equal INR equal and for sure the entire will be true because character equal to itself right and that's a length of one now other base case which you saw also was when you have two characters which means AB now what I mean by AB is I index is here G index is here which means I index is here which is zero as you can see Zero and J index has one so I can simply say that this is the specific column or you can also say that I + 1 is equals to you can also say that I + 1 is equals to you can also say that I + 1 is equals to your J that is the column of length two which is also a base case for you so is it equal a equal nah false b equal sorry B okay first Mark to b equal n false a equal yep a is equal which is okay true now what do a equal means a is at index 2 which means I index is here J is at the third index which is this specific index so you can see this is actually a Parr right that is the reason I can say this is a two again uh this a b uh false uh this B C uh false so this is how I have ploted my base cases so far so you will see after proing my Bas it will look something like this now when this portion is done let's compute the actual answers now simply go on to any location which means I went onto this specific orange location now when I say this location what it means I is 0 J is 2 I is z J is 2 okay this is the string now when you have to again just remember back the actual equation when you have to know if something is par or not then you will compare s of I and S of J okay I compare s of I and S of J and then I'll go and ask my bro I + 1 to J minus one go and ask my bro I + 1 to J minus one go and ask my bro I + 1 to J minus one go and find me if it's a Parr or not so I'll go and ask I + 1 gus1 if that's so I'll go and ask I + 1 gus1 if that's so I'll go and ask I + 1 gus1 if that's a b or not which means I'll go and ask my DP I + 1 and G minus one now if you my DP I + 1 and G minus one now if you my DP I + 1 and G minus one now if you go I was zero so I + 1 will be 1 J is 2 go I was zero so I + 1 will be 1 J is 2 go I was zero so I + 1 will be 1 J is 2 and J j- 1 will be 1 so it will be 1A 1 and J j- 1 will be 1 so it will be 1A 1 and J j- 1 will be 1 so it will be 1A 1 and you will see 1A 1 is a true so I have computed the base case value which is okay I + 1 J minus one it is a true and okay I + 1 J minus one it is a true and okay I + 1 J minus one it is a true and currently s of I and S of J is also a true so true and true is a and that's how you would know that this specific string this specific portion is a p or not and again you can just put a true here and that's how you can simply keep on Computing your answer so that is how you can build the answer now again this is The Logical approach but how you will code this up again you will code this up you will have to move your I and J pointers so again there can be multiple approaches for it but the easiest can be that if you go on and move your IE from the bottom your I will move from the bottom your J will move from the okay J as we have S okay for this specific again see it entirely depends on how you want to move it how you want to move something if let's say I want to move my I from top to bottom right so I know that firstly I have to compute all these values all these H case values then when these are computed again I'll not just put everything but I'll just uh show you I'll compute okay I'll compute all these values Bas cases base cases okay when this is done I need to compute this specific value I need to know these values like to compute this specific value which is 0 2 I need to know this specific value which is 1A 1 so that is a strategy I have to know that if I'm going in from the top to bottom then I should be going in my I considerably which means my I my J should be less than equal to my something like that I should actually make sure that I'm not going again I should not go also in this portion so make sure also that portion but uh other way is that if I go in from the bottom to top then I'll make sure that I'll go only in the end which means I'm going on my I is from bottom top which means my I is right now here I'll go only in the end portions okay because we saw that okay while going the starting portions it might actually um we have to handle these cases also uh these wrong crosscross cases so I'll just make sure if I at this location I'll go in the end so okay for sure for these cases when I and G both are there so always a true now uh let's move on and say we are at the specific I okay I is here and again I'm moving my I from bottom to top you will see why because I will move my J from this point I to actually up till the end so okay right now it is same so true and then I can move on my J here now the helpful reason I would I was able to move my J here was okay J will be here and the answer for this entire portion okay sorry the answer for this entire portion would all already have been computed and I only know that okay I only want this specific value if and only if I get something but although it's a base case so I will handle this by if condition although it's a basee I handle that by if condition so that previous portion value will not be used here technically now where it will be used let's say a random place this so when I am at this specific index which means I would have been at this specific I and I would have been at this spefic J and you know that I moving from the bottom top so the entire below portion would have been competed which means entire this portion would have been computed and I am as I'm moving my J from right to left so entire this portion also have been computed right so to come to know if this value is a true or false or this cell is a true or false I'll simply compare this specific I and this specific J which means B and B both are same again when I say this specific B I actually mean this B right here so I'm comparing this specific substring people get confused why the he's sorry why the F he's comparing this B and this B I'm not comparing this B and this B I'm comparing the indexes for them and indexes represents this specific one which is this specific portion of my string now this is same now I can go and ask for 2 comma 3 2A 3 was this value and which is this value and it was a true so the answer for the cell will be a true and that's how you can simply build it so the code looks pretty simple that you will go on and simply make your DP Vector exactly same as what we did above also now uh you will go and simply move on your I from the very back again you can also move on from the front but then you have to handle your J accordingly make sure you handle it accordingly now as I'm moving from the very back I can move my J forward easily now simple base cases first base case was when the length is odd which means I and J both are same okay simply have a one when I + 1 is equal to J which means one when I + 1 is equal to J which means one when I + 1 is equal to J which means I have two characters I and J is actually here right like this consecutive then if the characters are same then simply have one lse a zero and then for the other cases simply compare I and J and then if it is equal then go and tell okay if I + 1 J it's a true and tell okay if I + 1 J it's a true and tell okay if I + 1 J it's a true simply true else a false and then as you remembered I want to know how many substrings are palome so simply count add in the count how many are Pals and simply return that count again the time and space both is same of n Square it's just for you to know that uh the bottom approach but now if we go on and look back in the very beginning we saw that we have a two- beginning we saw that we have a two- beginning we saw that we have a two- pointer approach okay we can just move our pointers just to know if something par or not and now in the in since so long we have been just Computing and storing the answers if something is a paror okay if as you remember if I was at this specific I in this specific J let's say it is a right and if I would know want to know if this is a paror or not so I was saying I will while Computing the answer for this specific I this specific J I would be for short going inside which means I will go on this p and I'll go on this J okay same I'll again go on inside my recursion okay this side this J again same then I can go on okay that's actually the base case Okay the base case was actually uh this specific J and I but then okay now you know that okay it is uh equal a palr so like because of this you were storing okay this is a palome this is a pal this is a palome all that stuff why not you could start from the very beginning itself which means Start From Here itself I and J and then keep on moving forward okay this is one Parr okay this is next parent Ro okay because as you saw this is a parent roome so if this is par roome if only it's a then I only expand that okay I expand it and say I and J okay it's also Bome again expanded so at every expansion I'm increasing my count also because it's a par but you saw one thing Aran firstly you only considered that your starting point of a palindrome will be this specific I in this specific G you consider that okay which means you considering your P expanding like this what about the other pal DRS which means if this would have been a right just for the Simplicity then you could have expanded your parrum also from here then here right for how will you do that no worries bro I'll do that also which means I will try expansion from every point I will be at this point I'll try expansion from every point I'll be at this point and my J will be here I'll try expansion from here itself okay this expansion and again you know expansion will only occur when you have to move or you can move your in so you will not then I will have my in here again you will expand that expand okay so I got two from here when in is here again try expanding okay expand sorry expand again you have in so you know you try on for every in which means okay in here right and then you'll try to expand that so you go to Every index and for every index you're expanding up to the super n like length of n so you know for sure um you'll go to Every index and that's o of N and for every index again you're expanding entirely is again o of n so it's O of n Square operation for short the same as but we saw previously also but here's one catch AR you thought of that uh your Parr is of even length because you know okay the p is even length but what if the p is of odd length which means if I would have a b here then you expanded like this B ABA a like this why not why didn't you expand like this H that's a case yeah so I will handle this also how I'll handle this by expanding it like this IG okay then expand like this then okay no worri I cannot expand but yeah if I would have been able to expand it then I have let's say a here then I expand it like this so I will have to try for both the possibilities again it seems it lands back to the same problem the base case which we had where is it gone yeah length can be one length can be two so either try spanding as considering it as a odd length or as a even length so I'll try both the possibilities so I just say that I'll try for both the possibilities and try to expand that at every POS at every index and then find the answer which is the count so I'll go on and all the indexes I in I and then if I at this index I so for odd length I say J is this only this the this specific character only if I want the even length expansion I say I is here so J will be here so this is my even expansion it is my all length expansion so my J here is I itself my J here is I + 1 so I say for I itself my J here is I + 1 so I say for I itself my J here is I + 1 so I say for my J which means if this is the case which means it is a even length expansion if I is same as J it is a odd length expansion which I will be trying and try to find how many such palr can be there so it is a even L palome it's a or L bendr I want the count of those so again you will see I'll get the count I'll simply add in my main count which is the final answer and I simply get the count again this is the same paror function simply using two. approach you can also app but still we will not because we want to optimize the space and we'll simply go on and moving expanding until my I is more than equal to zero and my J is less than my size I can simply go and compare my SFI and S ofj if they are equal then I can expand that expand as in I - minus and j++ j++ and because in I - minus and j++ j++ and because in I - minus and j++ j++ and because that was actually a parand which means same I and same J so I can simply inre my count also and I can simply my count and that's how without using any extra space you have Sol of one time because you went on from the very beginning and then you tried to expand that and store and keep on storing okay that was actually a true so you were saying okay that's a par P par so that's a parent Drome cool that is so much it but you can actually optimize this more but considering it's a medium question we have already seen four methods for Solve IT you can still optimize it more you can use a suffix arrays it's actually Advanced concept suffix arrays uh if you want we can bring the videos on that also so basically you build the suffix trees and then because of LCA lookups you can actually optimize your time in O of end but this is the method which you or there a High chance your interviewer might also would have never heard of but he must have heard of the algorithm name as maners algorithm this is a standard algorithm for this paradrome kind of problem in this it's basically the same last approach which we saw a twoo approach but it is on like drugs or steroids and with that you can actually solve it in O of end time again it's actually a hard problem if you go on top of it but considering it's a medium we will not go on top of that problem but still uh just for your or curiosity it can be solved in both of these ways also cool thanks for watching see you goodbye take care bye-bye
|
Palindromic Substrings
|
palindromic-substrings
|
Given a string `s`, return _the number of **palindromic substrings** in it_.
A string is a **palindrome** when it reads the same backward as forward.
A **substring** is a contiguous sequence of characters within the string.
**Example 1:**
**Input:** s = "abc "
**Output:** 3
**Explanation:** Three palindromic strings: "a ", "b ", "c ".
**Example 2:**
**Input:** s = "aaa "
**Output:** 6
**Explanation:** Six palindromic strings: "a ", "a ", "a ", "aa ", "aa ", "aaa ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?
|
String,Dynamic Programming
|
Medium
|
5,516
|
315 |
you guys this is your house everything go in this video I'm going to take a look at three one five counts of small numbers after self we're given an integer array and I have to return a new account array the count already has a property where each element is number of smaller elements to write up itself like five to six one you need to return to because there's two one right after five and a supporter than five for two there one right only one or more than it I'm six only once with it in it and then for one there's nothing smaller than it so 2 1 0 so well if we do it brute force it actually need to count look through four five three elements to two element so obviously it's quadratic so how could we improve it well this analyze the example four five we need to count to six my right and for two we need to count six one so there is a duplicate six one so what about we think about two reversely so for six we check one and for two we check one six four five we check one six two so we it in each iteration we only need to add one to the previous previously checked number set right so what if there is some data structure in the checked numbers and we can get that faster than linear time well the first idea comes to my mind is that what about sort so from right to left we checked okay one then six pigs and one okay and then so bigger than one so for six there won't be one number right and four - well this is sorted so right and four - well this is sorted so right and four - well this is sorted so to check how many numbers are there's more than two what we use binary search we search it and find that it's only one numbers foot in it and then insert two in it and then it got five again we use binary search and define that two numbers more than five and he started so in this by this we for each number we will cost us log in to find how many numbers are there and we insert it but these are pitiful here to the insertion actually cost time we need to shift to the index for Ray so actually it still custom needed type I would say it's cost and yeah still quadratic so what's the structure that maintains we can do binary search and do insertion with the constant time could you do that hmm if we do planning research I cannot think of anything if link list it we could insert with constant time priority queue insert is log N it is something if you cannot only you know which one is the smallest or the largest so cannot improve that and yeah I'm stuck here so anyway allow me to implement this research implementation okay so of course we need to keep track of the result right last number there's nothing right after it so it's zero we push it and the highly reverse the result because insertion will cost more time and we'll will maintain a sorted list and put the last numbers in and now we will insert a final insertion position for each number we'll use binary search here start a cosy row and equal sort it done is minus one so cool binary search thing if sorted the middle one is bigger or equal to star D number then there might be some numbers smaller than it to the left right so we in not star as possible after this search start is the insertion position then the number is smaller than it actually is start itself because it's zero base and insertion at Hsu actually means there's a to number smaller than it so we start and we want to the insertion which is sort of a slice start zero and now yeah and finally we return the result so reverse so the core problem is hit this one actually this cost us a near time alternately be linked list no hospital so these costs in your time sad anyway for time is square not good man space is linear we use extra soda array so this is the best I can do yeah what's any other structure that we could insertion it with log n right if we can do insertion with log in by research put into each shift index the other linked list we can't a new binary search & pratik you we cannot do binary search & pratik you we cannot do binary search & pratik you we cannot do binary search what about binary search tree into the search will class law and insertion would be like linkless oh yeah I think we could she possibly improve to with the best tea because for the search Wow that depends how you organize your work BST right if you if the order if you just move through the numbers from right to left so the worst case it's still quadratic time because you will have a flattened linked list you search or Constantinian Nina type maybe you can shuffle the array first possibly improve with VST with n log n 2 and square well if you need some follow-up you can well if you need some follow-up you can well if you need some follow-up you can mission this and start working on it and shall we do here what ten minutes okay allow me to have a try okay for the VST I'll create a know the right class no instructor Wow for the node E will have the file and then we do in search we assert we step on a node if you get in it we go to the right that's right then we need to know how many numbers are smaller than it so these values well this count of smaller then it equals to zero mm-hmm yeah zero mm-hmm yeah zero mm-hmm yeah this is Lisa no and there is you see right so this equals blue try okay so now come smaller for nouns okay we create a root node which is noms okay I think we should choose what if there's duplicates why do you click it then we just count right bigger than it or equal to a smaller and okay there is kind of smaller this cancer cell goes one we use the last number as a root okay no lumps downstairs last one okay this is the root now we all create a function calling search okay search and insert which generate which accepts a node which will return the smaller numbers ah should we do it so let's start P equals root we'll compare this P to node while P the next position right the next position it is more oh I think we should use recursion or check you check on those antics notes against the target value if it's bigger then we will go to the next node but if there's nothing there we break okay we can we use while loop so okay so Wow P then we compare the node bow note well if it is equal to if node val is equal to the peepal then we should break right we found that find the insertion position and we need to increment not note that by paypal well P count o self plus one and do we return okay there's no need to break we've just returned P count cell Oh should return the count of smaller yeah that's it and so this is not the same so if piece val is bigger not P that but oh no about country note value is equal to P Belle then update peas if node file is smaller than piece file then we need to go to left right but if P left there is then P equals P left if not it's the P next uh-huh oh but if we said to piece to uh-huh oh but if we said to piece to uh-huh oh but if we said to piece left then we need to pee update the P counter of smaller lets goes to one right and then go to left yeah and if there is no they have to be here if there is no left node and smaller than it then we just appended right so piece left it was to note yeah and then the other case is bigger than it okay hey when it is bigger than it then when you speaker than it if the area is right node we go to the right so if P is right we go to right you don't need to update any numbers because it's speaker yeah II wait a minute when a node is going down I think we women we adopted the counts of note itself right the node may count of cell when we insert it like left we cannot we only insert to left when there is no left so begin in it smarter than it okay we only add update the nodes tag when it is bigger than the P right so say note about who is bigger than P then over here we update peak count here but we know update node count of smaller equal to e count of smaller plus P count of cell right this is when a bigger so we update the count of node and if there is P right now we're gonna set a two piece right and this will gonna be the next iteration yeah and then if there is no right node we append it to piece right equals P no P right equals nope so and when we set PF and node we break any we need to return 1 return the node kind of smaller right here returned the requests money I'm really I'm not sure where it is right let's try ok search and insert this is faction this is root now because the root is the right number right most number of course the result with the 0 and 4 equals monster names - to look for odd numbers and the names - to look for odd numbers and the names - to look for odd numbers and the result we just push search any search insert nouns right and finally here is we just passing a number I'll wrap a note here so return result reverse series actually then bow we wrap it note yeah this doesn't work I think yeah mm-hmm there is syntax me oh yeah mm-hmm there is syntax me oh yeah mm-hmm there is syntax me oh yeah whoa it works really Oh empty Wow in my word that's beyond my expectation oh so cool Oh wrong answer ah this is not right this is not good this is right until we get eight that is not right let's right like don't you hear we got wrong it's just uh take the last numbers to dispatch them they back so the error can become eight one two three four seventy six it seems that ever comes yeah if there is only kind of numbers so you probably come here that is okay 51 if it one is cool 9999 when we insert 99 there is some problem oh wow it's hard to park hmm hmmm this is wrong - still wrong this is right so I can reproduce this so let's draw some graph first we have 66 there will no duty in no duplicate and then we have 84 wrap it's just about mm-hmm and P is the route then they're mm-hmm and P is the route then they're mm-hmm and P is the route then they're not the same so and it's bigger than it so kind of slow moaner equals kind of smaller plus itself so 84 there's no rat so if you write equals 84 and then kind of smaller updated to 1 right yeah this is right tweak return ah mm-hmm it's not stable ah it's okay so mm-hmm it's not stable ah it's okay so mm-hmm it's not stable ah it's okay so one right the problem will become 99 okay we got 21 more than it so take my here about 9 smaller so 9 and 51 smaller than it bigger than it still 61 now we've got 9999 you get in it bigger than it and so 99 is here ah I know what happened yeah we're a set we set to the cutoff smaller to the P is kind of smaller let's just update it so here this motor is zero right and now add any source motor equities becomes one and then we got 21 us more than n so here should be zero but we did update the note here piece count a smaller plus one so here I become one right you see when we and we after insertion the account doesn't we it's a it's not updating anymore so we need to summon some d sup actually assignment it doesn't it's not just not what does not work it I see so after nines it's become two one zero no not zero but one here so he close one uh-huh I know what happened I need to uh-huh I know what happened I need to uh-huh I know what happened I need to know the count number need to Sun some up yeah now peace comes mother plus can sell this for we got one more okay let's just do this over again what to return is zero one zero two five two six okay so for 66 it's beginning zero we got 84 bigger than it and we set it to 66 kind of smaller equals zero I don't sell this one so we plus this one so it should be now it should be one right and then we got 21 move to the left and here plus one insert it and yeah it's still zero now we got nine instead it up did it update it yeah this is right 51 start it then here we get it so 51 will have one plus it's soft one so plus one so it become too right now we got 19 I know you get on it uh-huh we got 19 I know you get on it uh-huh we got 19 I know you get on it uh-huh and 99 will have it any so 3 plus 4 equals 4 and then cause this right and 84 ah there's a Dookie calculation so actually we're only counting numbers smaller than it so this only works for the route right this route if this only works if you're going to the right so only the numbers in the left part is right on the right it doesn't matter it doesn't work actually so the east one actually count is six and we're really 99 and we calculate it again so number of a smaller actually should only count the route right so count up smaller and then only count myself kind of smarter kind of smaller here I think we need to count not smaller that counts the left tree right count on f3 plus it and kinda kind of a and plus left tree so it is zero uh-huh I see it's not smaller but let's rename it count off left straight okay so we if the self update the can time cell mm-hmm yeah and we update we need mm-hmm yeah and we update we need mm-hmm yeah and we update we need smaller we update cut up smaller note up the left tree and return the note left tree yeah and when we go into the right we will counts the left tree plus its counter itself right so we are good like going to 84 we know 3 plus then the count kind of tree and then we should not return an account of its tree but we need to create a number which is a left count of smaller 0 okay if it's the same return count of left tree uh-huh tree uh-huh tree uh-huh it's live updates the P count up tree okay and then peel a equals B flat and return still original 0 and when we go to write like here every time we pass a node we collect the left trend count and the Southtown so this will pop the incremented with the count of slab tree and count of self right like this 84 for 84 itself and the left tree still 0 so returned because it is the same here so mm-hmm I think that's it mm-hmm I think that's it mm-hmm I think that's it god bless ya nice hope you pass sad stand-up passing and now we get if stand-up passing and now we get if stand-up passing and now we get if further well actually almost there why almost there still some problem maybe because duplicates we ever okay try right we can use BFS binary search for you find the failing test case okay this looks good Nix this looks good wait randomly so the problem is duplicates I think we handle so we kept 23 should be wrong it's okay what's the problem okay in 322 7 well Matty well this is good enough three okay this is the case Wow with oh I think this major issuing a my coat well even this okay this is easy to have to go once we return is last 423 we return 0 if you just wait when we count a flat tree the update okay let's see first we get 22 kind of small to 0 cells one we got 52 as we did here count of we will insert it 52 here 0 what right but the count will return one yeah which is good and we now we have 23 is bigger than it first model and with smaller than 52 so is 23 here and do an insertion you don't update them anything about no so the smaller is zero count will be one and we return yeah one cool it man then we got five boys five would be easier to work directly and then we will update this smaller left tree Oh move to left here is update it and then have did it five would turn zero I would get twenty three bigger than it mmm then maybe smaller than it so I know what happened we actually have the day here - - and we actually have the day here - - and we actually have the day here - - and find 23 we find the same 23 the account would be a kind of smaller and itself so - right so here we search to the left - right so here we search to the left - right so here we search to the left return count of smaller so it should be anything between kind of smaller so 1+1 anything between kind of smaller so 1+1 anything between kind of smaller so 1+1 2 so we should when turn - why didn't I 2 so we should when turn - why didn't I 2 so we should when turn - why didn't I return to which 5:03 2123 one you 52:23 one five one same twenty three women twenty three and then we now get 23 ah I know what happened P counts of left three and we plus the count of smaller when I going from 22 to 52 and the phone in here yeah this is a problem ah Wow this should be hard problem god bless come on yay finally wow this is very challenging I think so that's it let's last time complexity this well for worst case will be as we analyzed this world look through all the nodes but the insertion actually will well be constant time so I think you should be in luck in worst cases quadratic and the space we create a node right so it's a linear space okay so that's all for this one hope you helped see next time bye
|
Count of Smaller Numbers After Self
|
count-of-smaller-numbers-after-self
|
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
327,406,493,1482,2280
|
1,675 |
hey everybody this is larry this is day 19 of the leco february daily challenge hit the like button hit the subscribe button do join me in discord let me know what you think oh i got a brief spot okay today's problem is minimize deviation in a way um i'm still i'm in colombia's uh katahina so i've been not gonna lie i've been walking around a lot uh partying a little bit much uh so yeah so this video is coming out a little bit late probably not going to make the bi-weekly and probably not going to even bi-weekly and probably not going to even bi-weekly and probably not going to even make the weekly but we'll you know expect to see those videos soon but you know uh yeah and if you're curious about what i've been doing hit me up on my instagram below uh that's my travel instagram and hopefully i'll have some pretty pictures for y'all uh to enjoy and yeah anyway also in general i don't know have i always said this i've been drinking a little bit so uh so i don't remember but if i haven't then you know come hang out in the discord channel let me know how you did or think about this um the daily problem and where people share their code get code reviews get feedback just comment have fun whatever people do there's a group of a good amount of people there now so i'm really proud of it um today's farm is 1675 minimize duration in array so okay so you're giving it away numbers of n positive integers if an element is even divided by two element is odd multiplied by two so maximize the difference between any two arrays in uh two elements in another way okay um let's see well i think the first thing that i would think about is greedy and not greedy in a way but greedy in the sense that we're trying every possible things um the thing with one thing to notice is that if you multiply by two you can only do that once right because if you do it once then it's odd so then that means that for every initial odd number you can only have two possibilities right which is um the original odd number or the even number that comes before where the even number you can keep on doing it dividing it by two um to get it as small as possible so to minimize the deviation i think one thing that we'll try to do is divide it as much as possible i think that's probably a good way to think about it but another way of thinking about it isn't just greedy to get uh to get a final state but also um greedy on proof not brute forcing but like greedy and then checking um the evolutions of things as you go right and the way that i would think about this is that okay so you have like almost like you have a bounding box where you have a bounding box you take the biggest element and then the smallest element and that's your deviation right so then now if you have this uh rubber band right um well if your biggest element is odd then you're probably done because you can't really do anything with that one um and if you're done with that side and if your smallest element is um even then you also done with that side right so that's like your final state probably maybe or some variation of it um otherwise if your big n is even then you could divide by two right so that th that can only have um a couple of cases right one is that when you divide it by two well now your bounding box got smaller either by that number or another number that you know in the middle in between so okay let me actually draw this out a little bit because i think i'm just saying it with my hands uh actually you don't even see my hand because i've used the new thingy um but basically you have you know the small ascii art and the login right so um if as i said if this is even uh sorry if this is uh yeah if this is even then you're probably done with the left side because that means that you can't really get any smaller on the left side anyway at least not maybe that's not true per se at least not yet because there is a case where there's a number coming from the inside that makes it smaller maybe that's could be possible but anyway um but yeah if this is odd then there's no other way to uh you know again there may be a thingy but you're done with this number right um so then the thing that i would do is try to shrink this the span and so i think what i would do is just um on the bigger end because if you do it by two it um it seems more intuitive to minimize the duration so then we divided the biggest number by two to make it smaller and then this new the number but you know like it may just the number may be divided by two but for example this uh thing maybe move to uh the middle but there might be another number to the right so we have to think about that um but it either makes the thing smaller or this number goes to the left right so that's this is the other case um so then in that case we just check again to see you know the smallest number and so forth i think that's generally the idea that i'm going to play with i'm gonna yeah i'm gonna divide i think for me the intuition is to do it by two because so i'm gonna do all the even operation i think or like all this uh yeah order even operations and because you could keep on dividing by two uh multiple times uh and also because of duration it makes it smaller so the durations get closer right where if you multiply by two that's not the case so i think that's probably the thing that i'm going to try to do um so the first thing that i would do is i think you should use a heap that's to be honest um using a heap you know you keep track of the smallest number and large number then you can maybe re-juggle it later on then you can maybe re-juggle it later on then you can maybe re-juggle it later on right what i'm gonna do is use a sorted list because i'm lazy i'm not gonna lie uh yeah so then now uh we have to sort of list right i think this is gucci okay i always forget that well maybe not maybe i just haven't used it in a while i think in the past i actually do remember but that's why i run it before uh and making sure that everything's okay so just give me well this is the input is already sorted so that's a little bit uh whatever but this one now that doesn't really matter i mean i know how sorted this works so yeah and then now what do we do right now while um the last number my is equal to zero this is even oh well let's do uh best is you go to do right so that's the maximum difference because that's derivation um okay so then now we dotted by two right so then now best is equal to two so then we can always keep doing this and then now after that um i think now we can see if we can shrink the left side right so while oh and this of course is wrong but um because i have to do uh a man on this not just setting it a sloppy lobby strikes um what am i doing oh huh i actually didn't know that you cannot i guess that makes sense actually okay fine let's see same thing here i don't know if i knew that but i mean i think i probably did but i don't know maybe i'm just not remembering it today uh yeah so that looks good let's i'm gonna give it a submit i could be wrong on this one but i would like to see oh huh okay let's see okay that is just a big case um why is that wrong hmm is there a mod that i have to do this is not a mod question right okay good because everybody's funny but sad very last time i did like it a couple times but this maybe i did something wrong let's see right i just want to make sure that my code is right first because these are the only cases where you can spend the box right so usually i would analyze this but um but clearly uh this is a ridiculous like input to kind of uh be able to run through right so i like to manually test so i was hoping that i would get a wrong answer on the silly one but let's see if i'm they're making a wrong assumption we're keeping the one away too they should have okay well i guess there's only one thing to really what the f hmm what did we get uh my output is this and you could there is a smaller answer but that's the thing i'm trying to figure out is right how to get the smaller answer um so you only really need to care about the biggest number the smallest number right i mean until you know update it wow i guess this one um i thought this is it and or like something close to it so maybe i'm a little bit off by a little bit well the first thing to do is see if i can have a smaller case that is wrong but i mean i knew that i wanted to do it i just used a little lacy twins hopefully this as well nope that's good that uh okay i mean it's a smaller case but i guess it's not a small enough case uh same answers as before though so what i'm trying to do now is get like the s'mores case that it's still wrong so i could um yeah same answer so something weird about this wow i mean but this is so many i'm doing like a bisection of sort uh trying to figure out how to do it but uh it's a little bit tough uh huh okay so still long answer that's good incrementally this is slow and painful sometimes but that's how you learn but i don't why is that why is this wrong though that is what i want to know okay i mean we're making progress sorry if you're here hoping for a short one i don't know what i'm doing wrong so um so that's why sometimes i mean that's the problem with this greedy problems where we talk a lot about greedy problems and sometimes gritty problems have these kind of things where you think it should be good but you know you walk um uh it's this big thing but i'm trying to figure out why um i mean this is so many numbers let me see if i can think about this logically why this as well um try to come up with a smaller calendar example is why um sorry friends i have disappointed you oh how the hell why tell me oh yeah this is ridiculous oh and why i okay so this strategy hasn't been going well um it's some interact usually it's just about like two numbers or something right so okay let me try a different tag let me try to print sl at the very end okay so this is this sort of list okay that didn't help uh okay let's do it with other sort of this i guess i'm sitting on day c so i'm getting i think i'm gonna get a cold or something but uh okay but this is the wrong answer which is good uh or this is consistent so this is where everything is best and at the end we have this number of course because we multiply them what is it here let me just do it by two let's see huh so the smallest number was already even and the largest number is odd how do we get a smaller number then huh remember saying something silly the largest number is it's no the smallest number is even so you're not gonna make it any smaller huh i guess okay i guess i'm just wrong about my assumption i think and this is the case where um i guess this is the case with let me try something out really funky for a second i will just return the right answer yeah okay how do i generalize it though i guess that so the thing that i was wrong about was that um you can actually i guess i did say that a little bit earlier on um that you know because you can only do it once you might as well do it later because then this will later take care of it okay maybe that's a better idea i don't know let's see let's give it some real quick yeah okay yeah i mean i think the idea is that um and i think i was thinking about this but i think i just confused myself and try to i think that um this is one thing about um experience right is that sometimes you think um you can up you can simplify things and i think that's what happened here is that i prematurely optimized um not logically or not like you know people and people say that people usually mean like performance etc but for me i think i was just trying to like skip a step without really thinking it through um and in this case the reason why you want to do it what we have here is because um in uh is that um if we multiply all the odd numbers by even right then when this step is done the smallest number will be even um but also it means that if the number that we multiply by 2 becomes too big this would will bring it back down anyway to back to the original number so in a way it is reversible where if you divide by this by 2 it's not always reversible so because you may make a number too small um right like for example maybe you have like um for example if you have something like seven and eight you might make the eight a one um and then you just like messed up right like i know that maybe and there's some new ones about how i did it but uh but yeah um i think there's some like yeah um this makes sense uh so what's the complexity right well the complexity is going to be n log n because for each number uh maybe log n isn't quite right but for each number we add and we move um log n times right uh i'm using i think i'm just mixing n is y so let's just say n is you go to number or you go to length of nums uh and uh let's just say was it always you go to range of numbers right um which is integer which is 10 to the nine in this case actually um then the algorithm is going to be n times log oh wait excuse me um the reason why this is the case is because um for each number that we have you know we each operation is going to be taking log n times um and for each number we do log all of these right up to because for example if you have 2 to the 32 you would you can divide it by it um 32 times right so that's roughly the idea behind this complexity and then first for space this is gonna be linear space for the sort of list i think sort of this is linear right like if i'm wrong then i'm wrong on that one that's my bad but you could also use a heap for the same basically the same idea um just have to be keeping track of it um that's all i have for this one this was a little bit sloppy i think i jumped a little bit ahead and i missed the point and i if you couldn't figure out how to debug for nine minutes um yeah what did i do last time okay so last time i did use a heap uh yeah but i mean this one was the wrong answer how did i get it right by fixing it to do oh yeah so i fixed it by doing this i suppose by making all the odd numbers even yeah past larry is smarter all right how about the second time i did it uh same idea i guess well and both times i use the heap it's just that i times it by two first the past larry is so much smarter i don't know the last couple of days i've been a little bit off i suppose um yeah anyway that's all i have for today let me know what you think uh as you can see i don't know this has been a really weird week but you know that said i'm having a good time here in uh katahina so you know it is what it is uh thanks for watching though stay good stay healthy together mental health and i'll see you as soon as i can bye
|
Minimize Deviation in Array
|
magnetic-force-between-two-balls
|
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109`
|
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
|
Array,Binary Search,Sorting
|
Medium
|
2188
|
41 |
hi friends welcome back today we are going to solve lint code problem 189 first missing positive uh before we start looking the details of this problem i just want to mention that i often create lead code coding solutions in java as well as java jet we interview helpful material videos uh where we discuss you know frequently asked questions and how to answer those questions as well as about data structures and algorithms that are getting asked in you know initial telephonic rounds as well as uh online uh screening so uh please subscribe to the channel if you haven't already subscribed you know on this channel you will get a lot of good material for if you are preparing for java interviews so please subscribe to the channel so let's look into this problem now so given an unsorted integer array find first missing positive number so positive number is like more than zero right so that will be the positive number so um they have given us these examples here so and they are saying that uh you know we have to like try to implement it in or in time right and constant space so let's first try to uh go into this example uh here in the detail so we have been given an input array it is uh just like a not sorted so what we will do is first we are going to sort the array so let's just take this example and let's just uh write here the sorted array so our solid array will be minus 1 3 and 4 right so 3 and 4 is our sorted array here for this corresponding array right so this is sorted now and we are going to take one variable called stem so we will just assign this temp as a 0 in the beginning and what we will do is we will uh go through this uh sorted array and whenever we see any number which is like a less than zero you know we will just ignore that number for example if we are seeing minus 1 we will just continue you know we will not do anything so we are now at the second element 1 so we will always calculate the difference between this current element and our temp element so the difference now between one and zero which is uh one right so whenever the difference is greater than one we will uh at that time we are going to first find the first missing positive right so we are at this point where we have one and our temp is zero so difference is one so we will not do anything because we want a difference which is greater than one because that is where we will be finding our first missing positive uh at this time we will update our temp to this number right one that we are seeing actually and we will now go to the next number which is three so three minus temp is 1 which is equal to 2 so our difference is now greater than 1 right so that is where we find the first missing positive so now our first missing positive will be 10 plus 1 right so 1 plus 1 so 1 is our 10 and 1 plus 1 is our missing positive so which is equal to 2 right so 2 is our answer that we are going to return so that's why it does output is equal to 2 so this is the logic we are going to implement so we will take one more example you know just to uh make sure you understand uh the logic correctly so we will just have let's say we have another array here right so another array is minus 2 then minus 1 minus 2 then let's say 2 then minus 1 then 1 and then four right so this is our array that is we have been given right so what we will do is first we will be sorting this array right so let's just write a sorted array here so the sorted array will be minus 2 then minus 1 then 2 and then 4 right so this is our sorted array so we have a method called as arrays dot salt so we will use that method the time complexity for rs.sort method the time complexity for rs.sort method the time complexity for rs.sort is n log n for sorting so we have sorted this array and we have taken one variable called as temp right so temp is our variable it is initially temp variable is equal to zero right so temp is zero and a difference we will calculate in and let's just say this is the difference we will keep calculating when we are traversing the array so after the um sorting is done on the array we will take one by one element and we will first check if that element is less than zero we are here at minus two so the element is less than zero right minus two is less than 0 so we will just continue we will not do anything now minus 1 again it is less than 0 we will continue we will not do anything now we are at 1 right so we will calculate the difference between 1 and 10 so difference is one right so difference is not less than like greater than one right we are looking for a difference which is greater than one so right now difference is one so we will update the temp here and temp is now one right because 10 will be this number now we are here at 2 again we will calculate the difference between 2 and 10 means 2 and 1 the difference is still 1 so we will just continue right we are looking for a difference greater than one basically so now we are at four so now difference between uh and we have to update time to two right temp two we have to update now we are at four right now when we are at 4 the temp value is 2 so we will get 4 minus 2 the difference becomes 2 which is greater than 1 right which is what we are looking for so at that time what we will do is we will take the time value and we will just add a 1 into this right so 2 plus 1 and that is what our missing number is right so 3 is our missing number as you can see in the array so that is the first missing positive number because we have 1 we have 2 and 3 is missing here right 4 is there so 3 we will have to return so let's look at the implementation now so let me just make it little bigger so you can easily read this yeah so first we will check you know if the array is null or its length is 0 then we will just say 1 is the first missing positive number right in that case uh and then we have defined this temp which is initially it is 0 then here we are using arrays.sort method we will just using arrays.sort method we will just using arrays.sort method we will just pass add array and it will get sorted this time complexity is o this time complexity is n log n right this is the time complexity for resolve and after that uh we are going to iterate through the array right one by one so whenever we are seeing any number which is less than or equal to zero we will just continue basically because uh we want first missing positive right so it's if it is 0 or less then we don't want to do anything in that case if otherwise we are getting a number which is bigger than 0 right then in that case we will calculate the difference between temp and that number and if it is greater than 1 then we will just return 10 plus 1 right in this case how like we got difference 4 minus 2 is 2 so we will just add 10 plus 1 means 2 plus 1 is our answer so that's what we are doing here returning 10 plus 1 and if that is not the case means if the difference is 1 we will just update the temp right with the current number that's what we will do in this for loop and at the end we are just going to return 10 plus 1 here right here mostly when we get like the missing positive we will get 10 plus 1 otherwise at the end we will just return ten plus one right so that is the logic for solving the first missing positive number uh so let's just take some example and run the example so this is or we can take our example this one minus 2 to minus 1 4 right so let me just write down here minus 2 minus 1 4 right minus 2 to minus 1 4. so let's take this example and make sure our code works so we are getting correct output here right 3 so we'll just submit our solution so our solution got accepted it is almost 88 percent faster so which is pretty good and let me just show you like so we are not like using any kind of a heavy data structures or anything like any map or any set nothing just we are just uh using just a team variable so it is you can say space conflict complexity is just order of one because we are not using any different data structures uh and the time complexity means uh the array sort time will take more uh prominently right it is n log n actually because sorting takes n log n uh and this is just order of n so the more time uh consuming like a prominent will be n log n so that is the time complexity for this algorithm and the space complexity is good because it's like a constant right we are not using any space like any data structure so just like variable so it is order of one the space complexity so this is how you can solve first missing positive uh number so if you uh you know on my channel i already created uh like a playlist dedicated to lead code and linked link crowd solutions i have discussed a lot of problems in that playlist so please take a look they have been explained with examples and also it has playlist con helpful for like telephony crowns as well as screening interviews like for example like it has a playlist for you know like um dynamic programming uh data structures like hash map priority queue as well as bfs dfs graph solutions and matrix solutions so please check it out and subscribe to the channel subscription to the channel will be really helpful for the channel to reach to more people so please do so thanks for watching the video
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
899 |
all right guys welcome to our channel code with sunny and in this video i will be talking about the problem orderly queue its index is eight double line and uh it is the hard type problem for you okay so we have been given a string s and an integer k and we can choose one of the first k letters of the string s that is given to us and append it at the end of the string okay so there is a possible move that is being given to us that is every time we are going to choose any of the first k letters of the string of the given string and we are going to append it and that is the character that we have chosen it right now we are going to push back that character to the back of the current string and we are going to do this operation any number of times that we want okay and return the lexico graphically smallest thing that we can obtain after applying the mentioned step at any number of nodes that is we are going to do a infinite amount of moves that is whatever we want and the answer that we have to write on is the lexicographically smallest string that we can have after applying a certain set of moves okay so in this question the concept that is being related to this one is like maths you can have you should have to have a good knowledge of maths that is what is being happening over here how we can rotate the strings and what are the best efficient solutions also you should have to have the knowledge of sorting algorithms like selections or bubbles or algorithms and many more i will discuss all those like all those necessary algorithms that we are going to focus over this problem and then we will together build up the best solution for this problem so let's move further to understand this problem with the help of examples okay so let's first understand what this problem is going to say suppose we have the string containing let's say five characters so s 0 s 1 s 2 s 3 and s 4 okay and suppose that k is given as let's say 3 ok so if k is given as 3 what does it mean that this is our actual given string and we have to consider only the first three characters of this string right and we are going to choose any character note that the term any character we are going to choose any character of these three like the first three characters of this string and we are going to choose that character and discard over here lets say i have chosen this s1 and append this s1 to the back of the current district so it means that our new string would become s0 s2 s3 s4 and now s1 okay and now what will be our next step of move again we are going to choose this first three characters and like any of the characters let's say now again i have chosen s 0 then f 0 will be discarded from here and s 0 will be appended to over here so my new string would become this one and we have to do this operation like any types that we want and what should we return in this case that our returned answer would be a smallish lexicographical string that we can build by doing these series of operations okay so let's take an example and analyze how we can do that okay so let's say i'm taking cba and k is one let me erase this one so our like uh this is the given string and k is one so if k is one what does it mean that is we are going to choose only the first string we have the only option to choose the first string okay now let's say i've chosen this string so in one move our new string would become b a and c will be appended to the back okay and in another move i can't you i have the only option to choose b note that still this string is not the lexicographically smallest string because we have the character a which is the smallest character so our string should begin with the character a that's what we are trying to build up so in one operation again i will have the a as the first c then appended by the b okay so this is acb can we build like can we have much more better than this one no we cannot have because after again one operation you can see a will go to the back side of this string okay so c will come up to the first uh so the character cba is not going to be lexicographically smaller than a c b so this is not going to be possible acb is the smallest one right so i think acb will be our answer you can see yes acb will be our answer and this is for k equal to 1 so let's analyze the problem with k equal to 2 so for k equal to 2 let's take another sample string as let us say a b and c okay now suppose this is the given original string and we need to build up the lexicographically smallest string by doing any number of moves such that we are going to choose first k letters from the given string okay now you can see i have this a b d c and what is the lexico graphically smallest string note that i am asking for the smallest string in terms of lexicographical manner for this string you can see the it is the sorted form that is a and b c and d okay so this is the smallest string that we would be having if we sort the given string like the original string so can we build this string that is the sorted string from this one if we are able to do that then this will be our answer because this is the smallest lexicographical string of the given string okay so let's check it out if k is equal to 2 it means that we are going to choose first two strings and analyze whether we can build up the smallest lexicographical string or not okay so this is double a b d c okay so uh let's say uh i will choose i'm just popping out the first one since k is equal to two i can choose any two characters any one of the characters from the first two characters okay so let's say i'm choosing the very first one so the string would become a b c a okay now again i'm being able to choose the first two characters like any of the characters from the first two characters let's say i'm again choosing the very first character b like you can choose any one but we need to have to like understand that we need to build up the lexicographically smaller string i am explaining these all the steps because the uh the very important thing is for you to understand how the sequence of steps are working upon and suddenly i will give up the best idea why these solutions have been working on and what could be the best solution to implement that and how the idea came from okay so the next step would be like uh popping this out so b d c a again you can see we have the choice from the first two again i'm saying that i will discard this b so it would become now you can see that uh there is i have the choice from like uh first two characters in spite of picking uh the character d like the very first character i will now pick up the character c and append it to the back of the string so it would become like d a b and c now again i have the choice for the first two then again i will discard this d right now so my character would be a b c d and here the bingo happens over here you can see that this is the sorted form like sorted form of this string here we have got that okay so it means that if you are able to build up the smallest lexicographical string or k equal to 2 from this string it means that this is our answer so let me just introduce one another thing that the general answer for this question so whenever k is equal to 1 let's say we have the certain string as 0 s1 s2 s3 and s4 so whenever k is equal to 1 you have the only one choice you can pick up the very first character from the given string and append it to the back and again if again suppose this is the new string so you have the choice to pick up the very first character and append it to the back okay so you can see that every time when you are forming a new string it is of this type like suppose this is the original string suppose that you have done two steps like this one h then you have the string of this type like starting from this s2 and uh going up to the end of the string like a concatenation of this substring plus this substring like this is this will be appended first and this will be appended second you can see that the uh string is h2 s4 and then s0 to s1 so whenever k is equal to one you have the rotation of the strings okay so you can see that this is the very original string and in one of the steps you are going to rotate this string in anti-clockwise manner anti-clockwise manner anti-clockwise manner anti-clockwise anti-clockwise anti-clockwise so when you are going to do that you can see s0 will be discarded and f0 will be appended to the back okay so overall whenever you will be given k equal to 1 as the input and you have been asked to find out the answers you are going to perform the rotation of all the strings okay rotate every time the strings and find out the minimum answer okay so this is for k equal to 1 what happens when k is equal to 2 so let's try to understand that okay so now i'm talking about k equal to 2 what will happen when k is equal to 2 or let's say in more general case k greater than or equal to 2 okay now before understanding this thing you need to understand the swapping thing or you can say that you need to understand the concept of bubble sort in short what is this bubble sword bubble sort is a like sorting algorithm which runs in o of n square time and the main idea for this algorithm is like swap every two elements which are not incorrectly suppose we have the like we have the array let's call the array as one two five four three now you can see that this array is not in the sorted form like not sorted in non-decreasing order okay so what is the non-decreasing order okay so what is the non-decreasing order okay so what is the sorted form of this array you can see the sorted form of this array is one two three four five okay now you can see that bubble sort algorithm works on the case like uh whenever uh check out the adjacent two elements if the two elements are not in the correct place swap them right you can see that five and four are not in the correct fit let's swap them so it becomes four five and three now uh my target element is five right now again five and three are the not in the correct place let's have them one two four three five now five occurs like the place of the five is exactly matching within sorted one okay so again let's check it out which adjacent elements is not in the correct place you can see the four and three are not in the correct place so it could become one two three four five now it becomes the exactly matching with the sorted one okay so it means that the main idea to explain this algorithm is like whenever certain adjacent elements are not in the correct place we can sort the entire array you can say entire substring you can say entire string you can say we can sort the entire string only and only then we are able to sort the adjacent elements of the given string or the given array again i am speaking if we are being able to sort the adjacent elements of the given string or the given array then we can sort the entire array or the entire string okay now let's talk about the k greater than equal to okay again i am speaking when we are able to sort the given string or the given array or the given sequence of elements by swapping the adjacent elements and placing the elements into its correct place then we can sort the entire array or the string as we have seen now in case of bubble sort okay now let's say we have k greater than or equal to 2 and we have a sequence of strings like a bc and uh let's say i'm saying e then d then f and then i think yeah a b c d e f g now you can see that i have taken this as the sample string now we need to find out the smallest lexicographical string of this string okay so like the lexicographically smaller one after some certain sequence of moves okay what is the lexicographically smallest one for this using you can see it's the sorted form so a b c d e f g right this is the sorted form so uh let's claim that whenever k is greater than or equal to 2 we can always form the smallest lexicographically string from the actual string note that the smallest one i'm talking about is the sorted form okay so whenever we have k greater than equal to 2 we are going to sort the given string and return that as our answer why we are going to able to do that the concept is the same as bubble sort that is we can swap the two elements in our actual string which are not in the correct place and moving it to the correct place we are always being able to do that and how it is going to be done let's try to analyze now you can see that the abc is in the correct place according to the sorted form now you can see that these two elements are not in the correct place you can see here these two elements are not in the correct place and the remaining elements are in the correct place okay so let's try to analyze can we swap this element like can we have the condition that if we are able to swap the like if you are able to swap the adjacent elements of our current string which are not in the correct place then similar to the case we can swap any adjacent elements and move the particular element target element to the exact place that they are being supposed to have like you can see the character e is supposed to have two at this position but it is not at there so we need to do some swapping operations right so let's try to understand can we swap e and d then if we are able to do that then we can similarly cancel any of them okay so you can see that let's try to do that so what we are going to do k is greater than equal to 2 let's say k is minimum as like 2 okay so we are able to choose the first two characters so let's say i'm going to pop out this a then pop out this b then pop out this c okay so though after doing this my characters are like e d f and g then a b c now we have the choice to do the first two characters but we are not going to choose e right now because so what we want is like d before e okay so that's why i'm going to choose d right now so the next step would be like e f g then a b c d okay now again choose e then f then g so these all will be discarded then e f g now here comes the another thing that is being interesting yes we are able to swap them you can see a b c d e f g so it means that whenever k is going to be like greater than or equal to 2 like suppose k is equal to 3 then that's or that's a good thing for us okay because we are have we have a wider range of choosing the elements okay so even for the minimum k like as of now for s2 like we are always talking about k greater than or equal to 2 and for k exactly equal to 1 we are always doing the rotation of the strings in anticlockwise manner and when k is greater than equal to 2 like for the minimum k that is k is equal to 2 we are able to swap any these two elements like in the bubble sort whenever the target element is not in the correct place we are going to do the swapping operation with the adjacent element okay now you can see that here also e and dr is not at the correct place we are going to do the swap operation and yes we can do that okay like first taking out first i minus 1 characters and popping out to the back now again what we are going to since e and d are not at the correct place first pop out the like the first character if i am going to use the zero based indexing then pop out the 0 0th character that is s 0 to the back and then the remaining characters as it is you can see f and g as it is this will make us the swapping of e and d as possible okay so this is the case like let me generalize this one whenever k is equal to one perform the rotation of the strings and find out the minimum answer in anti-clockwise manner node that we in anti-clockwise manner node that we in anti-clockwise manner node that we have to do and for k greater than or equal to 2 the only thing that you have to do is like sort the add and return the answer because we are always being able to convert the given string to the sorted form with the help of bubble sort technique that is weak we are able to swap the adjacent two elements it means that we can sort the entire array or the entire string you can say okay so let's move on to the coding part to analyze the code so the code is like very much simple so let me just look out this summation so okay whenever k is one you have to do the rotation of the strings in anti-clockwise manner so answered with a anti-clockwise manner so answered with a anti-clockwise manner so answered with a minimum of all those answers so first to the like if you perform the rotation of the string at this position i that is you have this new string as s dot sub shear of i that is ah that is the substring after the ith characters and the first like eye length string okay eye length substring and you need to concatenate them and find out the minimum answer otherwise if k is not one sort the string and return the answer as it is always possible to sort this so this will give you all test cases watched so if you have any doubts do let me know in the comment section of the video and i will ask you to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
|
Orderly Queue
|
binary-gap
|
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters.
| null |
Math,Bit Manipulation
|
Easy
| null |
1,015 |
hey what's up guys this is chung here so let's take quickly look at today's daily challenge problem number 1015 smallest integer divisible by k so here's a description you're given like a positive integer k and you need to find the length of the smallest the length of the small is the positive integer n such that n is divisible by k and here's the constraints so on and only contains the digits one and return the length of n if there's no such end return minus one so no keep notice that m may not fit in the 64-bit the 64-bit the 64-bit sine integer so which means that you know we have integer k here and the cave has been is in the range of 10 to the power of 5 and it asks us to find if there exists an n such which only consists of one that can be can is divisible by k so basically 1 right so on continue until it reaches the length of until it can be increasing forever right so and how to solve it right so i think here we need to make some observations you know the first observations is like this you know let's say we uh we just we're just starting from one assuming we start from one and then we go from one the brutal fourth way right one and how many times we need to repeat these things i mean it we should at least i mean i'd most repeat this k times to find to either find this n here or return -1 and why is that this n here or return -1 and why is that this n here or return -1 and why is that because you know so divisible by k means that when we do if we do a modular if we have n here right if we do n modular by k if this thing is zero then we know okay the n is our answer right and but it's k how many modulus how many possible modulus we have for k of course it's from zero to k minus one right so that's the total possible modular after doing the mod by mod k right that's why within this range as i mean if we see a if we haven't seen that the zeros then it means that okay it will not we'll definitely we'll never find any here because you know as long as we see a duplicated modular here you know it means that you know if we continue doing this kind of module the mod cave and then we increase the end we increase one database by end it the modular will suppose i mean we'll end up in the while i mean in the loop so that it will just continue in that loop for forever and ever and will never find the zero so the first thing is that the for loop we only need to do a for loop from for this many of times basically k times and then the second one is the what and the second one is this constraints here so i mean keep in mind that node the k could be pretty huge right and if we're doing this kind of brutal force way by increasing the this n by increase times this n by 10 every time random plus one this number this n number will definitely overflow because the uh the biggest number is going to be 10 to the power of k right so and if the case is like this big you know this number will definitely overflow so we have we need to find a way to solve it right so how can we solve it so the way we solve it we should use the remainder not the uh not the n itself so why the remainder can represent n right so let's say for example we have let's say the k is three and then we start from one right start from one then the uh one divided by 3 equals 2 equals 1 right and then we do a what we do uh one now it's 11 divided by 3 equals to 2. actually not let's not use three let's use four i think four is better so let's say we do a four here it's one and 11 divided by uh not do a mod modulated by four is what is by is three yeah and then one modular by four is what it's also three yeah because this is and that's why you know so why is one can represent it by three so we're saying that you know we're going to use this three to repre to represent this one because this here let's say we have one two multiplied by four is this is also three so why this thing works right because the uh if we do uh you know this one is equal to what is equal to 27 times 3 plus 3 right and then this thing will do a plus 10 times 10 and then plot and then plus one okay so as you guys can see so this part you know since this one the previous one is always like times the k and then plus the remainder so whatever before this plus sign can be divided it's divisible by k right so it means that after times 10 the total the i mean the total result is also divisible by k so which means that we can ignore this part and we only consider the remainder part and times 10 plus one that's why every time we can instead of using this big number right that keeps increasing we can always use the remainder and then to represent the last number okay cool so if we have figured out those two things now the code the rest part is pretty straightforward you know basically we have a remainder and equal to zero and we have a scene dot remainder i'm going to keep all the same remainder in the set right and like i said we just need to loop through the uh the k to k times right and then the remainder right so the remainder is like this the remainder is the remainder times 10 plus one right and then we do it divided by k since we use the remainder to represent the n here that's why every time when we are updating the remainder by uh by doing multiply 10 and then plus one and divide by k right so few things if the remainder is equal to zero okay of course we know we simply return i think i should i need to return i plus one because i zero based and we need to return the length right the length is one base or we can do a one two k plus one but since i already used i here i'm going to stick with it so that's that right i mean the second one is what so second one is if the remainder is in the scene right then we simply return minus one and in the end we add this remainder to the same set right and then that's it we don't even need to return anything here because we know we'll definitely find a result either this one or the minus one within this k for loop here and let's try to run the code here or accept it submit all right cool so that's that right i mean the time complexity of course is the length of it's k so o of k and the space is o of k as well and yeah i think that's that i think that's it for this problem okay i'm going to give it my own upvote since this one already got too many downloads all right cool guys thank you so much for watching this video and stay tuned see you guys soon bye
|
Smallest Integer Divisible by K
|
smallest-integer-divisible-by-k
|
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105`
| null | null |
Medium
| null |
161 |
give given two strings s and t return true if they are both one edit distance apart otherwise return false so what does it mean what edit distance it means if we make only one change in s we get it equal to t so and what is that one change it can be an insert or delete or replace let's go through some examples so you can better understand the case so here is an example of s and t that we just need to insert c here between a and b to make s and t equal in the second example we just need to remove r here to make s and t equal and for this case we need to delete a here to make s and t equal how about this one in this one we need to replace g with b to make them equal so let's say if it is something like this it's capsule we need to replace g with b to make them equal and for this one as you see s is very shorter than uh t so it's not gonna be one change to make them equal we need to insert three characters to make them equal so that's not the right case we are going to return false for this one for the other one as you see s is way short or longer than t and we cannot make them equal just with one uh change so they are not one edit distance apart and for this case you see they are equal and no change is needed to be made and that's why we are going to return false because they are not one edit distance apart let's see how we can solve this problem first thing we are going to deal with these three cases that they are going to be false and it's easy to deal with so if the length uh if you get the length of s and t that s and land t and if the length of either s is bigger than t or length of t is bigger than s if we're going to return false and for getting that you're going to get the absolute difference between ls and lt and if it is bigger than 1 we know we should return false can we deal with this case here too yes we are going to say or if t and s if they are equal we are going to return false so we have dealt with these three cases so let's see how we can and decide on delete and insert and replace for doing that we are going to have a for loop to iterate over the shorter string why shorter string because if we go iterate over the longer string we are going to get an error so we are going to iterate over the shorter one branch how do we get the shorter one we are going to use mean function between ls and lt and then we are going to see if s at index i is not equal with t at index i we are going to do something while we are just checking if they are different because if they are equal we don't need to do anything we need to make changes when they are not equal so what i'm going to do i'm going to say if uh they are not equal we are going to deal with the replace case for replace case is very easy i'm going to say if i plus 1 after that index that they are not equal i plus 1 is equal to t i plus 1 so it has been a replace needed right so we can just say if they are equal then it's going to be true otherwise we are going to return false or this was replaced right we need to deal with uh insert as well so if we are saying about insert what you need to think is that's uh the point that we need to insert something to i right at that point because they are not equal so if we move one step forward here right so we are getting the shorter one so if we move one step forward here are we going to get um not this one if we move one step forward for t here are we going to have it equal to s at point i and if yes this means we needed to insert something to s i plus 1 to the n or for deletion what we need to do we need if we move one step forward is s equal to t at that point as you see for here if we uh move let's say we have uh for the delete here so if we have difference at r and e if we move one step forward like we get it from e f to the end is it going to be equal with e f and if it is we are going to return true and if like we will go through these cases and you will decide on that there is a special case here that is a deletion but because the shorter one has no length so what we are going to do we are going to return true because this is going to be the case and if this is the case if we delete one character here we are going to get the right result let's get rid of this and run the code and see what do we get here so it says invalid because i forgot to put one equal here let's see it seems all good and as you see here i ran this and uh it has been accepted so the time complexity for this one is linear because we have to iterate over the string and the space complexity is linear as well because we are using these um substring to compare them indices to compare them thank you
|
One Edit Distance
|
one-edit-distance
|
Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`.
A string `s` is said to be one distance apart from a string `t` if you can:
* Insert **exactly one** character into `s` to get `t`.
* Delete **exactly one** character from `s` to get `t`.
* Replace **exactly one** character of `s` with **a different character** to get `t`.
**Example 1:**
**Input:** s = "ab ", t = "acb "
**Output:** true
**Explanation:** We can insert 'c' into s to get t.
**Example 2:**
**Input:** s = " ", t = " "
**Output:** false
**Explanation:** We cannot get t from s by only one step.
**Constraints:**
* `0 <= s.length, t.length <= 104`
* `s` and `t` consist of lowercase letters, uppercase letters, and digits.
| null |
Two Pointers,String
|
Medium
|
72
|
234 |
palindrome linked list keep the height of a single linked list return true if it is palindrome or false otherwise we have example one two one so it's the same if we read uh from this direction and this one is not palindrome because this direction is 1 2 this direction is 2. so for this question I'm gonna use separate step to solve this problem first I'm gonna use a slow fast pointer message to located the middle of the link list and then I will reverse the second half of the linked list and then I'm gonna iterates through the post linked list from the start and then compare the value of each node if the value is not same then I return first if I reach the end I will return true so as I start coding first I'm gonna have a slow and a fast pointer both put into the head and the next I will have a while look so if fast is that to now and uh that's the knife not equal to now then I will move slow one another time and they're fast to another time and then I will after that let's see this example we have slow move this here fast here slow here fast in the now and then now the store is at the second the head of the second half so we have the cell so we want to reverse the link is so using the slow pointer so now I will have a list node called the previous will initially be now and uh the other one I will say curve in it will be slow node position so well current is not equal to now then I first record where the next node position is so I will say 10 equal per the next and then I change the printer for the current next so current the next will be the previous note and then previous to update to the current position current will update to 10 position after this I will I reverse the second half of the link list and then now the previous third will be the head of reverse the link is so I'm going to declare two variables so I would say first half well the head of the first half will be the original head and uh the second the head of the second half will be the previous note now I can do the while loop again so well um so if we didn't reach the end of the second half not equal to now then active iteration so I will say if first half that Bell not equal to second half dot well that means they have different value then I will return first otherwise I will move both the first half and second half one note forward so I would say first half equal first half the next second half equals second half doesn't it and then if we successfully uh entries over the while loop that means we didn't find any node with different value in that case we can return true and then we can lastly handle some edge cases so if hat you go to now or had the next go to now then it will be empty or just be one node so in both cases you can return true and then that's it the time complexity will be open even though we have one two three we have three water we drop the constant so we eventually end up with n and the space complexity will be of one because we just create a few nodes we didn't create any other data structure so if we're using constant space next Let's test the code out before let me go through one last time to check and submit just looks like we passed the tests
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
833 |
hello friends and now let's do a simple question funny replaced industry to some strands will perform some replacements operation catcher plays rook of letters with new ones not necessary until it's M stars actually this is the tricky part of this product each row represents operation has three parameters are starting in exile a sauce word ex and Italian word black the rule is that if X starts at the dish I in the original string s then we will replace that occurrence of X with y if not we do nothing for example if we have s equal to ABCD and we have some replacement operation I equal to 2 X equal to C D Y Q versus them because city starts at position 2 in original's string as we were placed with SSS so how to think about this problem as you can see because it's the size of their so see a subtree not equal to null targets a substring so we cannot directly change in the string in the original string and also as if we change one string then their index not valid anymore because this indicates a position in the original string so a simple solution that we will use an extra array to not sure if the us so C is a matches the original string is in a match we break holders their index in these three erase what does that mean say this is true and this so C is the city as Matt Scherzer CD in original string so in our extra array the true will equal to the one indicated the play C in this is rearranged and finally we use these the array to generator our final result so let's solve it first we will capture the length of this string and we will use extra array and the name will equal to the match and the we personally get all the value in this match in connective oh the reason is that so by default the value of this array is equal to 0 but an index can be 0 so it's confusing so we just initialize to negative 1 and then we iterate I equal to 0 I less standard index now less I trust us we checked every sausage to see if it's a mesh in the original string so it's substring the start index will be index I and the end index will be the index i + the end index will be the index i + the end index will be the index i + the sauces i sauces I tell this ok if they really if they matches about it's a substrate right and then if the eCos chooser sources I push it means that match so match this index i will equal to die because we want to finally capture the targets already and then we will use a string builder to generate our results extreme builder yes I coach with your I left and the Israel to know to write the condition as updater how to update this I your true case it if the match I not equal to text mulch basis they are match so we just appender third target and the places in this target is equal to the match I because we say then as the value upended these targets and somehow updated I choose our closest match I done this if not equal to next one we just let s be appended this original character Exodus I and do not forget to update this I finally just returned SB shoestring okay it worse see you next time thank you for watching
|
Find And Replace in String
|
bus-routes
|
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`.
To complete the `ith` replacement operation:
1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`.
2. If it does not occur, **do nothing**.
3. Otherwise if it does occur, **replace** that substring with `targets[i]`.
For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`.
All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**.
* For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap.
Return _the **resulting string** after performing all replacement operations on_ `s`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\]
**Output:** "eeebffff "
**Explanation:**
"a " occurs at index 0 in s, so we replace it with "eee ".
"cd " occurs at index 2 in s, so we replace it with "ffff ".
**Example 2:**
**Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\]
**Output:** "eeecd "
**Explanation:**
"ab " occurs at index 0 in s, so we replace it with "eee ".
"ec " does not occur at index 2 in s, so we do nothing.
**Constraints:**
* `1 <= s.length <= 1000`
* `k == indices.length == sources.length == targets.length`
* `1 <= k <= 100`
* `0 <= indexes[i] < s.length`
* `1 <= sources[i].length, targets[i].length <= 50`
* `s` consists of only lowercase English letters.
* `sources[i]` and `targets[i]` consist of only lowercase English letters.
| null |
Array,Hash Table,Breadth-First Search
|
Hard
| null |
813 |
hey everybody this is Larry this is me going to do an extra question for today I actually need to go out and get food so I'm going to just pick a medium for today I have a lot of medium problems anyway so yeah uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's medium bomb that was an SQL problem so I'm trying to obviously not dress QR problems but I mean I need to do that do them so that I don't I stop uh getting these things but we'll uh we'll think about it later okay so today's bonus bottom is actually not a premium question so I guess eventually we'll get through them 813 largest sum of averages okay so what am I what we're partitioning the way at most K non-adjacent non-mt adjacent Subway ways non-adjacent non-mt adjacent Subway ways non-adjacent non-mt adjacent Subway ways so we're trying to just do this three times this kind of reminds me of the contest problem that we had recently but uh maybe the score of the petition is the sum of the averages of each Subway so 9 okay this is equal to 20 we could have also partitioned this for example but then that would be 13 which is worse okay so we're going to maximize the score you can chief of all petitions okay think the hundreds are really awkward in that I was I'm not gonna lie so initially I was thinking about maybe just because I was thinking about the other one I was thinking about some greedy type problems um the idea is that in theory it you know like I mean I don't know how to put this together to be honest or like you know I'm still in the conception or uh yeah conception stage abstractions now and whatever right just thinking stages but I'm trying to say but with a bigger word but um but the idea is that okay for example if you have a really big number you want that number to um you know you want that number to stand by itself because then it has a bigger impact at the sum but maybe not I don't know but I was hoping to kind of maybe explore and feed on that idea uh maybe there still could be a thing but given that n is 100 then we probably can do something more brute force is what we're going to do um can we and the first question is can we do something of n Square um can we do something with n cube right um so the first thing to notice is that we can definitely do a suffix type thing right um suffix DP meaning that um the sub the answer of a suffix we are able to build the optimal sub problem for the suffix then we can kind of merge it with the existing thing right and then the other thing is that um okay if we do that's going to be N squared but we don't take account K so well the easy part is just take account K and taking account K will make it n times K times n so N squared times K and this is just in my head um we'll go over it you know if you didn't follow along that uh it's fine we'll go over in more detail in a sec but that's basically my DOT I just want to um illustrate my DOT process into why I'm committing into it before you know like I don't want you to be like oh like let me Implement something you know it's too slow right what how does he know right um but basically I just thought about it and this is and like I said if I if that part went too fast it's um a lot of it's just due to experience so definitely um what will we actually explained upon don't worry uh and he says you know uh tab but yeah but yes that if and you know this would depend on um foreign knowledge of dynamic programming right um so basically the current thing is having the suffix index or a suffix of this Plus or another dimension is just how many K's we have left because we have to kind of petition them into you know uh um into K different uh supper ways or whatever right so yeah so then if index is equal to n then what happens if K left is equal to zero then we return zero it else then that means that we still have arrays left over so we want the score to be something like negative Infinity right because we don't want this to be a it's not a we didn't use up all the numbers so that so we have to kind of consider that okay and then okay right so then now we because we still like and some of this is a little bit cheating in the sense that it is working backwards from knowing that um we only have 100 elements because then now um just as a backup the envelope indexes goes from zero to n uh K left goes from zero to K which is also 100 right so this is a hundred um and if that means that we can do a for loop from you know uh an O of n for Loop which we'll show in a second and then there'll be 100 Cube which is fast enough right because that's just a million Okay so up to here now we can go okay um yeah let's just say current sum is equal to using just this one number for this in the thing right um and then now for I in range of index plus one n maybe then oh and here maybe you know we will have something like best is equal to zero um maybe 0.0 um maybe 0.0 um maybe 0.0 um and then passes you got a Max of current sum uh pass uh no that's not going some well current sum plus um largest suffix index plus 1 K left minus one right because we used 1K um actually we should make sure that if K level is equal to zero then we also return negative Infinity because that means that we ran out of num uh we ran our partitions but we still have numbers left so we don't want that to be a possible answer which is why we're using negative Infinity to be like okay so you need to uh step back from your recursion stack okay so yeah um okay so then now that's for one number maybe we're gonna win that I guess we I don't know why I wrote it this way maybe it's fine because we could just do also current sum as you go to zero right um we can do something like current some plus and this is actually wrong I did it well my fault friends uh largest suffix of um I plus one and we actually want to start at the index here then uh I plus one k left minus one this assumes that K level is greater than zero because otherwise we will already returned early um in this case starts at zero then we no it's okay um so then we add that to the current sum and then of course we actually we're going to do this thing but this formula is one because it's not the current sum it's the current sum um divided by the count right so maybe we add count equals zero and then can we increment uh what is this going on I think this should be what am I doing okay right so basically the current sum is just basically the prefix summer oh not the prefix sum but just like the subway sum of the numbers that we're doing and then now we have to you know uh divide it for the average right and also it's not a division uh thing so yeah and then after we consume this number we go to the next number K minus one and then I think that's it really so then now we've got a larger suffix from 0 to K and this should be good except for the time limit exceeded um yeah uh it doesn't really time to exceeded here but it's got time number exceeded because that's just how these things are right this is exponential and exponentials are pretty sad so basically we just add our general uh dynamic programming techniques so we have has cash is you go to um force times K plus one for so then now we have an N by K uh array a matrix if you will right and then here now we can just go has cache of index K left C sharp notation by accident is to go to true and then um yeah Cache of index okay left is your the best and voila I mean of course we should still check for it that would be nice you know actually you use the cache ha and that's pretty much it hopefully yeah this has been actually a little bit slower but uh as you can see when you submit everything is friendly so yeah um as we said you know we have um the total time as I always do is just um number of inputs time or well yeah times time per input so number of inputs is going to be n times K or all of it a little bit uh okay and then each input does all of n work here possibly so in total it's going to be o of N squared times K and space is the same logic except for each input only takes over one space so this is going to be all of n times k um cool can I always submit it okay I think so right yeah um that's pretty much it let me know what you think uh can you see all of it um yeah you can see all the before I type all this stuff so maybe go back a little bit and make it slightly smaller so you can see all of it in one page for a second uh okay close enough I think um that's all I have with this one let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Largest Sum of Averages
|
all-paths-from-source-to-target
|
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer.
Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted.
**Example 1:**
**Input:** nums = \[9,1,2,3,9\], k = 3
**Output:** 20.00000
**Explanation:**
The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
**Example 2:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 4
**Output:** 20.50000
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 104`
* `1 <= k <= nums.length`
| null |
Backtracking,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
2090
|
56 |
one so today we are looking at leap code number 56 it is a question called merge intervals and this is like i think this is probably one of the most popular questions on leap code you can see it's got 7 000 likes but if we jump down here you know i mean it's just asked all the time everywhere um last six months to a year so recently it's been very popular so definitely a good one to be familiar with and uh we'll kind of jump into it now there's a couple different ways to solve this you can use a brute force approach or you can use a little bit more of an optimized approach so we'll look at both okay so we're given an array of intervals where intervals at i is equal to start of i and end of i merge all overlapping integrals and return an array of non-overlapping and return an array of non-overlapping and return an array of non-overlapping intervals that cover all the intervals in the input so okay we have example one here we have one and three two and six eight and ten fifteen and eighteen and we can see one there is an overlap between three and two so we can get one and six we're going to merge these two and then we have eight and ten there is no overlap between six and so eight and ten just goes into the result and then there's no overlap between 10 and 15 so 15 and 18 also just goes in into the result and if we have equality uh then we just go ahead and merge that so this will just be one and five and we just have this one and five okay so we could do a brute force approach where we do two for loops and we find the intervals and go about it that way um it's fairly intuitive and it's just not very efficient so let's take a look at the more efficient way of approaching this okay so first thing we want to do is this example the array is sorted but if it's not we don't have a guarantee that the input array is going to be sorted so what we want to first do is just go ahead and sort the input array okay and that sort operation is going to cost us n log n time okay so sorting that input we're going to have to pay a cost of n log n on time but then we'll have everything sorted and now what we want to do is we want to create a result array and we want to go ahead and put in that first interval into the result array so we're going to go ahead and just put in that 1 and 3. okay and now what we want to do is whatever is the last element in the result array we want to go ahead and get the end of our first one so i'll call it e1 it's going to represent this value right there okay and now we're going to have another let me use a different color here so just it's a little more clear this is going to be e1 okay and now we're going to also compare this to we're going to create a variable as we iterate through our input array and we'll call this start one or start two sorry and end two okay and so now what do we want to check if e1 is greater than or equal to start two okay so let me just go ahead and write this out here if e1 is greater than or equal to start two okay if it is greater than equal then we know we need to merge uh we need to merge these two arrays together okay but we don't want to we have to be careful we don't want to just go ahead and merge e2 we also want to check we want to make sure we get the max okay and then what we want to do is we want to just update the e1 on result and move on okay so what we want to do now is we want to go ahead and take the result this uh index right there so we can say result at result dot length 0 at one so let's see here we can write this out like result at minus one that's going to get us the very last element and then we want the first index okay and then what we're going to do is we're going to set this to the max okay the max of e1 and e2 because we don't know this could be a 10 right here right and so then we don't want to go and fill in this with 6 because it's going to be incorrect so what we're going to do here is we're going to just get the max we're going to set this to the max of e1 and e2 so in our case here what we're going to do is we're going to go ahead and remove this three okay and we're going to update it with a 6. and now we're going to go ahead and move forward with our iteration okay i'm going to remove this here and now our start 2 is going to be here and our n2 is going to be here and now we just run the same uh the same conditional here does e1 is it greater than or equal to s2 it's not okay so these two do not have a merge and so then what do we want to do we just want to have an else here and we want to just push this into our result okay so we can just say result.push interval so now we're going to have this 8 and 10 in here and we'll move forward so i'm going to go ahead and remove this here and then this is going to iterate forward so now we're going to have start 2 here and n2 here and we'll just do run the same conditional is e1 this is going to be our e1 let me update that because we're good the e1 will always be the last element in the result at index one okay so that's our end one and we're gonna check is it greater than or equal to start two it's not okay so then what are we gonna do we're just gonna push in this interval and then that is going to give us our correct result okay so it's not too bad it's just a matter of using the result array the end of that array and keeping a running tally that's really all this question is getting at and so what is our time and space complexity well we do run these linear operations so we do have o of n time for that but because we're sorting here okay because we have this sort here it's our time is going to be n log n and then what about space well we have to create this result array so we're going to have o of n space okay which isn't terrible so let's go ahead and jump into the code so what we want to do here is we want to go ahead and create our result array and then we're just going to go ahead and push in the very first interval we'll actually first we want to sort the intervals and we want to set sort them by the zeroth index okay and now we just want to put in that first interval as an initial value into our result all right so now we have our initial setup and now all we have to do is just iterate over this array and update the result so we can just do a four let interval of intervals and we get our variables so let e1 equal that's going to be end one and that's going to be our result.length our result.length our result.length on the first index then we're going to have our s1 that's going to be our i'm sorry our s2 that's going to be a start 2 and that is going to be interval at index 0. and then we're going to have our n2 which is going to be interval at index one and this interval is not intervals it's the individual duple that we're iterating through and then we're getting this the value of the zeroth index and the value at the first index okay and now we just run our conditional if uh e1 is greater than or equal to s2 start 2 then what do we want to update whatever's in our end one in our result array so we can just say result.length minus 1 is going to equal the maximum of e1 and e2 and why are we doing this math.max e1 and why are we doing this math.max e1 and why are we doing this math.max e1 and e2 so let's just jump over here and make sure that's clear if that result if this right here is let's say 10 or i'm sorry let's say this right here is 10. so we don't have a 3 we have a 10. this is going to initially set to 10. we don't want to go and then put a 6 here that's going to be wrong so we want to make sure we keep the maximum here in case it's over if this interval is actually below whatever this interval is right there and that's why we want to get the maximum of the two variables okay and if that's not the case then all we want to do is just push in our interval into our result all right and then all we have to do is just return our result i'm going to run this let's see here result.length this should be result.length this should be result.length this should be result.length minus 1. result.length minus 1. result.length minus 1. let's see here result line 10 here we go uh let's see here this right here should be the first index and we're good okay and you can see we get excellent performance using this strategy we get beat out 95 of online submissions and then on space we're beating out 65.86 65.86 65.86 so this is a really fun problem i really enjoyed this problem um you can see that it is just asked all the time like all the time so it's one of the most frequently asked questions and so i highly recommend being very familiar with this because it's very likely that you're going to run into this exact problem or something very similar that's dealing with merging intervals and if you have a good idea of using this pattern sorting it and then just checking the last index with the first index and updating accordingly you know you can apply that and solve it okay so that is lead code number 56 merge intervals i hope you guys enjoyed it and i will see everyone on the next one
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
118 |
given a nun active integer k how do you design an algorithm to return the first K rows of a Pascal's triangle that's about today's video last time this is where my dream started hi everyone this is Steve here and today we are going through another very classic interview question which is leave : interview question which is leave : interview question which is leave : 118 Pascal's triangle as recently we have gone through it's follow-up and have gone through it's follow-up and have gone through it's follow-up and Pascal's triangle to you so we're now revisiting its predecessor which is an easier one let's take a look at this question first given an active integer number of rows generate the first num rows of Pascal's triangle again we're looking on this interactive diagram very illustrative we can see in Pascal's triangle each number is the sum of the two numbers directly above it you see all of these and all of the ones that's on the right edge here all of these all of the ones on the left edge they are the column which is called M and Edmonds and all of the elements on the right edge they are the and gentleman on the right side they don't change they're always 1 right but however for the ones that are in the middle saying this - it comes from the sum of saying this - it comes from the sum of saying this - it comes from the sum of the two elements right above it one plus one equals two - and this one comes from one equals two - and this one comes from one equals two - and this one comes from one plus two becomes three and this one is also coming from two plus one equals two three this is Pascal's triangle and the problem is asking us to return given and we can take a look at the API signature here we're giving a number or just call it K to simplify our code writing give a none active integer K were just it's asking us to return all of the first K rows so you see it's a list of lists a list of Lists here so this list of leicester is the first K rows well same as an announced problem let's quickly draw some diagrams first one okay it actually starts from zero one two three four how many do they have five okay which starts from zero that's good so let's see the diagram is going to look like this is one so Pascal's triangle is always standing from one so this one is second one is one this one is one and then starting from here what we'll have is one but this one is a two why because this one is coming from the two elements right above it so continue with this row it's going to have one here this one is a 3 because 3 is coming from 1 plus 2 and then this one is a 3 as well and the one on the right edge is always a 1 right now let's take a look at here 1 here and this fall comes from this 1 plus 3 equals to 4 and then here we have 3 plus 3 becomes 6 and then here at 3 plus 1 becomes a 4 here and then the one on the very right is always a 1 that's the first five rows of Pascal's triangle then we'll think about how we can put that into actual code very intuitive solution is that we can just impute the every single roll on top of its previous rows so we always stand with a 1 that's what we have here for the first row and the second row we can go either ways we can go stand from the very left hand we can go from the left hand towards the right like say we add a so this is the very first row then we can add a 1 and the that is right which means we are going to shift every admin in the current position towards the right this is the this is going to be the second row so after we boot the current rule we're going to add that row into the final result so that we don't need to keep track of actually the final result is helping us to keep track of every single Rose result so and here after this is the second row as I said we can continue to build all of the rows all of the following rows on top of its previous rows so here we'll just continue to add one more one at the top at the very left end of this row but here is starting from the third row and row two index starting from zero and this row will have to you reset the value why because all of the values as I said all of the values that's in between the only to be reset right because this is right now we just add one on top of the previous row which is here but since it has more than two elements in this row so which means it must have an M and in between which means the an in between must derive from the one that's directly above it so this one needs to be reset how do we reset it we can just reuse the rows that we just added one at the very left end of it we're just did some of these two up and then reset this value to this value that's it that's how we get to you row two if you are a little bit confused don't worry about it we'll go through that into more details and even we'll find out internally and go through that step by step you'll have a better understanding this is wrote to you let's just do one more row which is we'll go to Row 3 and Row 3 as I said we'll start from adding 1 at the very left end of the previous row so now this row becomes 1 2 1 right but apparently we know this row is not correct the correct value should be 1 3 1 so how do we reach here from here we'll just go through all of the elements that's I'm in between right which is these two values so we'll start from the elements at index 1 we don't need to start from zero because all of the edge elements as I said all of these admin they don't need to be reset because they are always one so we start from this one we get the value how do we reset this value to what to these two values add up so 1 plus 2 is 3 so we have these two you reset this one to be 3 this is also a middle element which means when it reset researching one value to these two values Edda this is going to become 3 that's how we get this number 1 3 1 this is one approach to reset it and actually we call this left to right approach we always add one and the very left end of the previous row that's what we did right actually there is we can also do it by just EEP append 1 at the very end at the very right of the previous row we can quickly go through with that as well that route will allow us not shifting all of the animals that's current in this position towards the right which is going to save us some time let's start writing some code if you are still confused and don't worry about it as I said well fire up IntelliJ and go through with that set a breakpoint step through that so then you have better understanding of why we're doing that so first we'll go from left to right let's initialize this copy this have another road-holding every single have another road-holding every single have another road-holding every single row number and we'll have a for loop here I small I'm smaller than K I passed plan and so here we so now we'll start from the left towards the right first so what does to add we always add one at the very left and at the very left hand so this is this call and then we'll have another phone inside and the inside phone will start from one J is smaller than Rho Rose size and minus 1 J plus Perelman saying why is J is smaller than real size minus 1 okay let's take a look here suppose we start from the left hand at here row size 3 minus 1 is 2 so we only need to go up to where less than 2 right so here is one that's why we only need to go up to you J is smaller than real size minus 1 we don't need to go any further if that's not descriptive enough let's fire up the intelligent later we'll do that and then here what we'll do is we'll reset as we just said well reset all of the values that's in between right this is we standing from the second element wait and then we go up to the last second element second last element we reset this one too so here we're going from left to right so it's and we append one we were prefix in this previous row with one at the left end already so everything here is shifting to the right hand that's why we'll do this plus one yeah so after this one so the purpose of this in the follow-up is to reset all of the in the follow-up is to reset all of the in the follow-up is to reset all of the values that are in between right reset this value reset these two values reset these three values that's the purpose of this in the for loop so after this in the for loop this the current row the next row is being reset to all the correct values and this moment we can just add this current row into the result which means we have all of the correct values for this row already so we can simply assign this undiscussed for there is some confusion as after why we need to initialize a new ArrayList and assign the current reel into there into the new ArrayList and that's because if we don't create a new object and copy the current row into the new object this row is always going to be constantly to be updated in the next generation which is not what we want we can quickly see that in once in intention we can and two men you have a better understanding this is I guess this is very specific to the Java language implementation I'm not exactly sure about other languages okay back to this problem this is the entire algorithm that we implement if we go from the left towards the right let's hit submit and see all right accept it and not see pretty impressed has actually pretty slow let's hit submit again and see oh this is really running the same algorithm I didn't change anything again let's see all right zero millisecond 100% okay millisecond 100% okay millisecond 100% okay this is the one that we went through from here from left to right we can do the same we can implement the same algorithm from right to left let's just quickly do that very similar but instead of appending and instead of inserting a one on the left end of the current row or just append a one on the very right end of the current real let's do that reset it to default code then here starting from zero this is still the same so let me just change this one's okay I pass instead of inserting a one at the very left end of the current room what do that after we reset all of the values which will do J standing from J will stand from the very right end which is going to be row size minus one J is greater than or equal to 1 and J minus - greater than or equal to 1 and J minus - greater than or equal to 1 and J minus - this is what we're going to do and then row set this value to be row cat J plus row get J minus 1 and then in the end we'll add row and just add one in the very right because the API implementation of this in list interface for an API is to add one towards the just a pen one to the very end of the current ArrayList that's it and then well result will make a new copy of this coming row and add it to the result that's it let's hit submit and see you alright it's also accepted 100% yeah alright it's also accepted 100% yeah alright it's also accepted 100% yeah that's me ambulams from going from the right hand towards the right towards the left and also we implement the algorithm to implement to compute the values from the left hand towards the right and if you want to have a more detailed walkthrough let's fire up in Tanjung and walk through that all right now I'm in my IntelliJ we can take a quick look of how actually every single line of code is being executed well take a look at this one set up a few breakpoints here we'll start from this in the for loop well it's not a breakpoint here and I have a task here which is going to what just quickly go through the second algorithm which is to reset all of the values from the right end with the left let's debug this and it's going to stop pause and the breakpoint okay number of rows is 5 so here 5 we start from 5 so but at this moment in row is just empty then we can go at this moment is not going to enter the in the for loop why because it really is empty there is no middle elements so we're just a and 1 into Despero so row becomes 1 so initialize a new object and put the current row copy into it and now result becomes a what it has the first row and then it goes to the second intuition at the outer for loop so still it's not going to enter the in the for loop why because we're just about to compute the second rule of the Pascal's triangle in the second row in Pascal's triangle is just a 1 and 1 it doesn't have any middle elements so it's not going to go into the in the for loop and we can take a look at the code as well so row size right now is just a 1 right so 1 minus 1 is 0 J standing from 0 J 0 is not greater than or equal to 1 so we're not going to come into the in the for loop so it doesn't go in then we add 1 to the covering row is going to add 1 so here Rowe has one more element here then we in create a new copy to hold the current row and add that into the result so resume has so now result has two rows now one is the first row which contains only one element 1 the second row is containing two elements 1 and 1 so here now we are coming into the third iteration of the outer for loop let's see so now I becomes 1 and so and the rows sighs let's see the size of the row is 2 at this moment let's see so now it comes in why because say here J is starting from 2 minus 1 is 1 and 1 is greater than or equal to 1 is recording 1 right so we need to reset this value here reset this funny reset this value to what do to that's it so you see here this value is being reset - - and that's this value is being reset - - and that's this value is being reset - - and that's it that's all we are going to break out of the in the for loop here we break out and then we append a 1 into the end that's it and then we add the result in backing and then we'll go through that a two more times to finish the entire innovation because we are given a number of rows which is equal to 5 ok that's it we can just go through this set it choice because there are two middle elements we add one here so now this one because 1 3 1 which is the crack value for the 4th world and then it's going to execute it one more time and just quickly go through that one more time so and then and 1 4 6 4 1 which is the correct value for the 5th row here now which is going to break out all right test passed my test is not comparing action and we're just printing it out so just print it out so then we can see all of the values all of the rows of every single value I just would like to quickly recap why we need to initialize a new realist object what if we don't do that what's going to happen so let me just it there is this so let's run this program run this test and see so remember this is the curl out of the correct row values which is what we expected right but if we don't initialize a new array list what's going to happen let's run this right so this is the result that we get it's all the same and it's actually all of the last row which is wrong right why is that because if we don't remember I just removed the best let me just undo everything if we don't initialize a new array list and just to put the copy of the covering row into the neo-realist this objective is kept the neo-realist this objective is kept the neo-realist this objective is kept being modified right we are constantly modifying in the neuro and we are always adding the same object reference into this final result which is mutable it's always being changed that's why we need to add this yeah that's it for this solution Pascal's triangle I hope you guys could have a better understanding of it if you do please don't hesitate to leave me like but it just a tenth and gently tap that like I'd really appreciate your help and don't forget to subscribe to my channel as we continue to go through a lot of the code problems yeah that's it for today's video see you guys in the next one
|
Pascal's Triangle
|
pascals-triangle
|
Given an integer `numRows`, return the first numRows of **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** numRows = 5
**Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\]
**Example 2:**
**Input:** numRows = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= numRows <= 30`
| null |
Array,Dynamic Programming
|
Easy
|
119
|
524 |
hello everyone so today we are going to cover longest word in dictionary brutality so we are given an input of a string yes and a list of strings d and we have to return the maximum size of a word that can be formed from the string yes that is present in the list dictionary t so how do we do it let's understand this problem with an example first here in our given example the first word is a l e you can actually form a l e from the given string yes by deleting the other characters and the it is of size 3. so moving on to a next word apple also can be formed from the given string yes moving on to the next word monkey cannot be formed because the characters doesn't match in string yes so that we cannot form monkey and finally p l e you can form p e l e from the given string by deleting the characters from a to c and it is of size four and other word we found this apple that is size five so now from our dictionary we can form three words from the given string yes and which is the maximum size or which is the longest apple is the longest so we have to written apple as our output so this is the problem statement says so when i first saw this problem the idea or the intuitive approach that up hit my head was longest common subsequence so i plan to find longest common subsequence between every word and the given string and if the longest common subsequence found is the word itself then i added to added it to my result finally return the longest word that has formed for example from my string early and comparing my string s the longest common subsequence that can form is ali itself that means you can form the word ali from the given string s so i added a lead to my result first so once that is done moving to apple is again the longest common subsequence between the word s and apple so again i'm updating my result to apple because this is her longest than ali so moving on to monkey the longest common subsequent you can form monkey from the given word is e because no other characters are matching and yes e is the only uh character that matches so since e is less than apple we are not updating our result moving on to pl ea again plea is the longest common subsequence but we are not updating our result because it is of size 4 but apple is of size 5 so finally we are going to return the result here i faced two complications uh the one is the time limit x exceeded as i submitted the solution it runs fine it works fine but i couldn't run it within time the second thing is consider this case so here in this case if we are applying the same logic the first word a can be formed from the string by deleting the three other characters so we are updating our result to ta first and then moving on to ba is again can be formed by deleting a b from the string so i am updating my result to uh ba so again a b we are checking a b can be formed from the string yes but it is of same size ba so i'm just ignoring this a b and moving on to c here c also can c cannot be formed so i'm returning the result ba but the output of the this example is going to be a b why because out of b a and a b both are of same length but a b is lexico sorted or lexicographic graphically lesser than compared to b so this is going to be our output this is the second complicated thing i've faced in while doing that solution so to reduce the time complexity i sorted the list from longest to smaller string so here i sorted my given list d from longest to smallest because we need to return the longest string that can be formed from the given string yes so the first word from the list that matches or satisfies our criteria that is that can be formed from the string is our output we don't have to check the other strings at all because we need to rotate the longest so by using that first checking monkey can be formed no monkey cannot be formed the second string is apple but the apple can be formed from string yes it can be formed so this is going to be our output we don't have to check the rest of the strings so instead of checking longest common subsequence because finding longest common success subsequence is another extra work we are doing we don't actually need that to this problem so what i actually did i started iterating the strings with two pointers so now a b c p l e a and apple so i'm keeping a pointer i at my string yes and j at my string from the list d so every time i iterate i is going to be our scanning element it i moves every time we i trade and j moves only if the character matches so let's start moving our i and j so a and a matches so in this case both i moves and j moves to the next character here b and b doesn't match so we are just moving to the next character to i but not j is going to stick to here because we are checking whether we can form this string from d from this string yes so here p and p matches so we are moving our inj so i move to c and j moves to p again so here c and p doesn't match so we are moving our i to p and j still here at v in this case p and p matches so both of the pointers move so here i moves to l and j moves to here j and j again matches so we move to l e so e and e again matched so in this point we are checking every time whether j meets length of the given string that is the length of the given string is five j starts at the first index and moves till fifth index and it again meets five so in this case it means we formed the word we already found the word from d in the string yes so if the j matches the length of the word then we found our maximum word that can be formed by deleting characters from the string yes so we simply return the return this word so this is going to be our second approach this code can still be optimized but before that let's see how are we going to code this and then move on to our optimal solution so here is the longest common subsequence solution that didn't work because of the time limit exceeding thing so here i'm sorting my list based on the length so if the length of both any two strings in the dictionary itself is equal then i'm checking which is lexicographically goes first so i'm sorting the list in descending order if the length is equal then i'm comparing both the strings and assign align them based on its lexicographical order so once that is done i'm going to have two pointers i and j so i'm gonna loop them i goes till the length of the given string and i'm checking if i'm migrating every word from the list i'm checking whether the character at index i of string of given string is matches with the string in the dictionary if it matches then i'm going to iterate both the pointers that is in for loop i will be i traded automatically for every scan or every iteration j i tricks only if the character matches finally i'm checking if j reaches the word dot length then we found a word that can be formed by deleting the characters from yes so we are just simply returning the word if not finally we are returning an empty string so let's run yes so our solution runs in 21 milliseconds we can further make it even more optimal so let's see our approach three so far we have found whether we can form the string from d from string yes by keeping the pointers i and j and i goes or iterates the complete word yes every time it encounters a word in d to check whether we can form the word this word from this word but there is a technique if the word doesn't exist or we cannot form that word from yes but still i trades from the index 0 to till the length of the string s to avoid that we are going to use another technique if we know that we cannot form this word from the string we simply skip and move to the next word so how do we do that to do that i'm going to check whether yum exist in the given string or not simply it just checks whether m exist no m doesn't exist in this case you cannot form this word at all so simply you can skip this word and move to the next word apple so here to check apple we are just checking whether a exist or not yes a exists so next we are moving to check b exist or not but what if the word is v b e c b then still it satisfies p exist a exist but we cannot form the word because these characters are rearranged so to check that we are going to use a predefined function from java that is index off this method is going to help us to find the index of every character so first we gonna start with a we are going to find the index of a in the given string it is present in the zeroth index so now we are going to consider the string only from the first index fill the last index and find p in this range and once we found p we are going to split this and consider searching the next characters one leaf after the index of last found p so now next is another p we found one more p here so we're going to split the string and further search the rest of the elements only after the range from last form character so by doing that if all the characters returns an index which means this word can be formed from this word if any character search gives us minus 1 which means the character is not existing in that range so we cannot form the word so we can simply skip the word and move to the next word so what is the advantage of this from the previous method in the previous method both pointers i and j i trade completely to the string even though it doesn't have the character for example in our monkey though we cannot form monkey it still i trade through the string completely but here if it found yum doesn't return any index it returns minus 1 which means in the first character itself it skips the loop and move to the next word apple so by this it reduce a lot of time so let's see how are we going to code it so here i'm still gonna keep this sorting as of now inside every word i'm gonna call or check a helper method is the word sequence of that word this sequence if it is yes then i'm gonna return that word because we have sorted the words from longest to shortest so the first word satisfies this sequence is going to be the word the same technique we used in the previous algorithm so public it is going to return a boolean value whether true or false so i'm gonna initialize my j pointer to minus one so in a for loop it is gonna check so this function is going to check whether the character at i is returning any index from the string b a is the word from dictionary and b is the actual word or string yes given so it is going to check whether in this character has an index from the string b and why we are specifying this integer value here it is one j is found that is the last index of the character is found it is going to check the remaining character from the next index so this indicates search that characters index starting from this index by using that we are going to get j if any character returns minus 1 that is if j is equal to minus 1 then written false straight away we cannot form the word or if it completes the iteration which means we can form the word so written true let's run this yes so again it runs fine but it takes 13 milliseconds which is actually a better solution than the previous one we have submitted but still we can make it some more optimal by removing the sorting process this is taking uh n log d time where to sort all the strings from the given list so let's remove the sorting completely and i'm gonna iterate and check for every word in the d but i'm gonna have a result variable i'm gonna check the sequence only if the length of the result is less than the word currently we are going to iterate it if the word's length is gonna be higher than the previous result we stored in result variable then we gonna call the sequence and check if not if it is not greater if it is lesser we can simply have a result and move forward to the next solution or if it is equal if the result dot length is equal to word dot length then we are going to check whether it is lexicographically less if not if it is lexicographically higher then we do not have to do this we do not have to check whether it is a sequence and update it if it is lexicographically lesser then we are going to do the sequence so we are checking if it is equal and word is less than 0 then which it means it is lexicographically lesser so if this is the case and our the new word satisfies the sequence then assign result is equal to word and finally return the result so overall what we did instead of sorting we removed the sorting code and we are checking if the new word is greater than the result then we can check whether it is a sequence and update if not if it is lesser than the word it is obviously not going to be an output or if there are there is another case that if the words are equal length then we have to do only if one word is lexicographically lesser than the other word if not again it cannot be a solution we can move so we are checking if the word is equal and lexicographically uh lesser than the actual result then we gonna check if it is our sequence then finally update the word okay we are assigning the word result to yes our solution is running in eight milliseconds which is far better than the first one we have submitted so thanks for watching if you like the video hit like and subscribe thank you
|
Longest Word in Dictionary through Deleting
|
longest-word-in-dictionary-through-deleting
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Array,Two Pointers,String,Sorting
|
Medium
|
720
|
1,935 |
Hello Hi Friends Welcome Back Together Into Solitude Problem 1935 Maximum Number Of But You Can Type So You Common Adopting No Data Open Create Videos Related To Javra To Interview Aa Material Edit Solution Singh Jawak So Iodine Is Point Ko Dissolution School 6065 Problems Old And Explain To Please take a look on this channel will be really helpful for you if you are preparing for the interview and according to the interview subscribe to the Channel Keyboard Well Some Letter Kiss Do Not Work And If 30 Keyboard Work Properly Youth Spintex Talk WhatsApp Deleted By Single Space No Leading or Trailing Space End String Broken Letters After All Distinct Letter Alarm Set Up Broken Return The Number Off But SIM Text You Can Fully Type Using this keyboard physical you can imagine that you have you know you have a like computer and you have broken keywords show sea of 1000 not working and now you have to find out what you want keywords show sea of 1000 not working and now you have to find out what you want keywords show sea of 1000 not working and now you have to find out what you want you can completely tight with scan keyboard show this is the example Day everyone has so let's take this example in you how they can solve this problem so we swadeshi states hui want to type and way to take you know what are the words on twitter and tagged with and broken keyboard show the broken Letter For Working Harder And E Saw Two Letters Sir Broken What We Will Do Is First Will Take This String And Will Just Know If We Get Area Of The Thing From This String Using Question Use Pet Right Clear Is True 500 And 1000 Doing A Split After spring and will get the area of world and will it and will get the area of world and will it and will get the area of world and will it rain through each word for example first world they are getting is this world rate hello so will related through the first world hello so receiver for this world and what we will do it is well treated through thought provoking latest one by one and the same time and win use string dot in string ghr index of method so will convert this letter head into a string and will check in this hello tasting actually fried so i don't have a share in a string In this hello day will grow and will reduce another letter of do that word e will check gift during his present in hello so both are not present som will say that hello world vision type with power that he hello from portrait features they can type in our Broken Key Mein Aa Vikas Gift Hai Saaf Not Have Any Broken Key Sites And 30 Will Contest Way Din Hello Sun Will Take Another World Is Our Another Word And Will Again Tanche Gift Share String Is Darindagi Awal This Video Not Yaar Do You Will Take You First Time Disappearing Discussed In Word Sorry For India Is Yes So Index Of Evil Returns Raw One To Three Four 100 Index Of The President Of Atom Stream Character Ride Point Will Return Index 100 Will Know That Hui Channel Type This World Basically So Will Return One Aisa And Output Head Solve That Time In Villages With The Amazing Strings And It Will Udayveer Vishwa First Village Hello And Will Take The Same Time To You Will Check Vipin Yadav Broken World Is Present Weather In This Rafting Guide It's The Thing Will Just Increase And counter and will return to contract to here in this way are using back streams index of mithila flat world implementation of this software quality of amazon of word servi and inner visions and account called as iska insaaf plan * * * * * share and insaaf plan * * * * * share and insaaf plan * * * * * share and result Is The Counter Actually It's Exactly By Starting Increment Ride World Is Hero Saw What We Will Do It Is A Will Read The Third Reich We Are Processing This W World First And Will Check That Tweet Rover Broken Latest One By One Are Eyes And Here Know Evil Check Your Forward Busy Had Broken World Clear Rates String Value Of And Were Going To That You Convert Director Came From Broken Letter To The Best Results Basically Have Converted As Letter Interesting Here Right And They Are Taking Bete Letter Which Consists Of Contents In Disturb You Will Drive To It Is The Hardened Will Be More Than - One Who Will Get Hardened Will Be More Than - One Who Will Get Hardened Will Be More Than - One Who Will Get In That Case How Will He Broke All World Is Equal To One And Will Break Out Fits Oh Man You Man Checking Out After This Point To You Will Check Gift World Is Find any of the broken characters in this letter during This World And You Will Just Say Pro Convert One Hand Break Powder Actually Software Index Of Method Will Give As Minus One Is The Meaning Of The Term The Fasting Is Not Present In That Otherwise It Will Give The Index Of The Present Character West To Dashrath Solution Work Show Latest Vinod Hum 10 Solution In Working Fine With The 10,000 More Test Cases Working Fine With The 10,000 More Test Cases Working Fine With The 10,000 More Test Cases Have Not Clear So Let's Message Wikileaks The Way You Can See The Code Working Fine And Where Getting Correct Results Year Research Solution Is Like Much More Cleaner Quality Lean Doing Like Lot Of character and all the like looping so ujjain ghazal index of methoded after the string and you can check your vision convert between character of the broken letters which can convert into a string and will change its present in the award suresh very clean and moisturized third T20 Now Flash Lights Off Power Solutions Getting Almost You Too Per Cent To MS And 4310 Memory Switch Pretty Good Night Salim Solution Turn Off Scanner Problem Article Getting Into The Initial Round Of Interviews And Coding Interviews And Even Coffee Line Coding Interview In White Building Devi Lal's Beach Center Questions 10000 910 Index of Metal Works in Gunas This is very important method it is like you very handy method to solve this kind of problems and it is like lord cleaner code vitamin radha and you will redirect a bike character of which of the character From The World You Know It Is Fish Coconut Adi Solution Adharmic You Like This Solution Please Subscribe My Channel And Click On The Like Button Also Click On The Bell Icon So You Will Not To Miss Any Future Videos Of Fun Create Videos To Help People You Know Aam Aap Repairing Home Java Interview Solid 50m Ya Indrajal Interviews Coding Interview Is Well As Will Discuss Laika Water Frequently Today's Data Structures Algorithm Question Singh Jhala Show This Please subscribe The Channel It Will Be Really Helpful For The Channel thanks for watching this Video a
|
Maximum Number of Words You Can Type
|
minimum-number-of-operations-to-reinitialize-a-permutation
|
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_.
**Example 1:**
**Input:** text = "hello world ", brokenLetters = "ad "
**Output:** 1
**Explanation:** We cannot type "world " because the 'd' key is broken.
**Example 2:**
**Input:** text = "leet code ", brokenLetters = "lt "
**Output:** 1
**Explanation:** We cannot type "leet " because the 'l' and 't' keys are broken.
**Example 3:**
**Input:** text = "leet code ", brokenLetters = "e "
**Output:** 0
**Explanation:** We cannot type either word because the 'e' key is broken.
**Constraints:**
* `1 <= text.length <= 104`
* `0 <= brokenLetters.length <= 26`
* `text` consists of words separated by a single space without any leading or trailing spaces.
* Each word only consists of lowercase English letters.
* `brokenLetters` consists of **distinct** lowercase English letters.
|
It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution.
|
Array,Math,Simulation
|
Medium
| null |
1,416 |
hey everybody this is Larry this is day 23 of the uh what month this is April legal daily challenge hit the like button hit the Subscribe button join my Discord uh let me know what you think about this Farm uh for those of you celebrating uh do you say happy while I'm done I don't know I feel like I'm always like messing up what to say but uh anyway is it happy Ramadan Mubarak hopefully maybe I don't know I'm saying that right okay ah yeah uh in any case yeah I hope everyone's doing all right um but usually actually I'm not gonna lie um uh usually I actually do a fast uh on this time but uh but this year I'm my energy is just really down so um allergies is just kicking my butt so I'm trying to maybe I'll eat it a little bit I don't know if that's a real thing but in any case so we'll see what happens as you kind of saw in yesterday's video I was just especially on the premium one I was sneezing like crazy so hopefully this one will be a little bit better anyway let's take a look at today's vlog uh 1416 returned over uh restored away oh excuse me you're doing some morning all right a program is supposed to put in a way of integers the program forgot to print white spaces and the arrays printed as a string of digits s and all we know is that all integers in a way we're in the range one to K and then no leading zeros and no way giving the string as an integer K we turn the number of possible arrays that can be printed as s using the mentioned program since the answer is maybe very large we turn it uh it's much uh we turn it modular some numbers so first of all remember the mod okay let's see what are we doing what does K mean again all images are weighing okay is it just means that okay yeah that means that the substring is um less than k okay I mean this is a way it's standard e dynamic programming problem um the key even to notice is you know if you kind of Drew the implicit graph it is very tempting to just be like okay well it's gonna be N squared because you know you're looking at sub arrays but of course given that K is only up to 10 to the nine that means that K will only take up at most nine or ten digits I guess right and if it only takes 10 digits then that means that for each index for each prefix you only care about 10 digits so therefore we should be okay um okay so then that with that said then we could get oops get started pretty quickly right so let me just do something like cam uh we have index and hopefully I don't have to explain this by now because we've had a week of dynamic programming but index just um shows you basically what it represent is the suffix of the string s right this that is the suffix of that counting right so that means that another way of saying it is given the suffix of s starting at index uh what is the number of ways that uh satisfy this criteria we saw the array or whatever right so okay and of course index can go from zero to n is going to express uh yeah so if index is equal to n then we return zero maybe or maybe one is fine yeah one then wait otherwise then total is equal to zero um and then this is where we just use index uh you know we do something one at a time and you can kind of write this in a number of ways but uh I'm gonna see how I'm gonna write so it's current is you go to SF index uh into this right um and maybe what we want is um say current index is equal to index so maybe that's slightly better right or maybe yeah okay fine uh let's just rewrite this chronic zero current index is really while current index is less than n uh and current is less than K or less than and equal to I guess right then current we added to current index of course we increment current index and of course this should be a shift and add right so currently shift and then we add and then here now that oh now that we have this then we want to count in um current index is the last thing we consume so we want the suffix of that so it's plus one right so then we have total we add that to um yeah the number of count of this uh yeah right maybe well this is of course assuming that current is less than or equal to K right which is the constraint that we have for this problem um otherwise if we break I mean I think it just gets checked anyway but I don't know just of course as well and this is not answers total whoops um and then just return column zero and there we should be good right maybe not um I don't I want to see whether prefix zeros matter oh there's no leading zeros okay so that's why um yeah okay so if there's no leading zeros that means that if s of index is equal to zero well I guess in this case 10 degrees of counter zero then we return zero right down can it be why would this be our pair of what is this such status because it can only be index indexing real n right what is going on here hmm it's actually surprising current index will be oh I see because I incremented by one here so this is actually off yeah okay it's very awkward though I think I'd like to write it this way instead to be more clear okay and then of course you can add more things oh I was gonna hit submit but yeah of course the next thing to do is recognizing that you have to remember the memorize so of course uh indexing up from zero to n and so we're just gonna memorize it right back and keeping in mind that as we said um okay we'll do the analysis afterwards actually hang on okay yeah so basically the analysis is that okay um what is the total time complexity right total time complexity is of course you go to um time per input times uh number of input right or total number of input so here the total number of inputs is equal to O of N and each input takes o of log um K right for upper Battle of K or maybe Max K or something like this and of course technically this is a log base 10 but of course Big O takes it that way because log base 10 is just over uh divided by log 10 which or bigger takes away anyway so that means that total time is going to be all of n log k um which means it's going to be 10 to the fifth times uh 10 or something like this in Practical so that's going to be fast enough I say that and hopefully it's true well I did forget to uh do one thing so that would have been video kind of sad but uh okay now we can maybe hopefully this works uh yeah okay one last time hmm this is the only contest I guess so oh I didn't do the leading zero huh which is fine but then I don't know why I don't know maybe there's some weird leading zero things but uh but yeah uh that's all I have for this one let me know what you think and yeah this is kind of proof for us I don't know that I explained this one very well to be honest let me try a little bit but basically the idea is that okay so let's say you have I think I just kind of skipped ahead but I say you have some string right uh and you have some K as you go to some other string and basically all the first way is just okay let's see one digit okay is this one digit let's say we take this one digit that means that we do recursion on the suffix and then now we take two digits and then now we do a recursion on that suffix and then we do three digits and then so forth and then now until you this number is bigger than K and then go okay well this is no buenos and let's break because everything to the right of that is going to be bigger and then we just kind of sum up the number of counts and that's pretty much the way that I did it um yeah okay now I think that's all I have for today uh the contest is in like two hours or something so if you're doing that good luck uh and yeah that's what I have hope y'all have a great rest of the weekend and to whatever you use yourself wearing uh that's all I have for today let me know what you think stay good stay healthy to convin mental health I'll see you later and take care bye
|
Restore The Array
|
check-if-an-array-is-consecutive
|
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.
Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "1000 ", k = 10000
**Output:** 1
**Explanation:** The only possible array is \[1000\]
**Example 2:**
**Input:** s = "1000 ", k = 10
**Output:** 0
**Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
**Example 3:**
**Input:** s = "1317 ", k = 2000
**Output:** 8
**Explanation:** Possible arrays are \[1317\],\[131,7\],\[13,17\],\[1,317\],\[13,1,7\],\[1,31,7\],\[1,3,17\],\[1,3,1,7\]
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only digits and does not contain leading zeros.
* `1 <= k <= 109`
|
Try sorting nums. If nums is consecutive and sorted in ascending order, then nums[i] + 1 = nums[i + 1] for every i in the range 0 ≤ i < nums.length - 1.
|
Array
|
Easy
|
298,549,1542
|
207 |
hey everyone welcome back today we are going to solve problem number 207 course schedule first we will see the explanation of the problem statement then the logic on the core now let's dive into the solution so in this problem we have number of courses so in this input we have four courses and we have a prerequisite 2D array right this 2D array is nothing but a graph so in this case we need to finish course 0 to take course one right similarly I need to finish course 1 to take course 2 and I need to finish course 2 to take course 3. so we need to check whether we can finish all the courses so if this is valid we need to return true and if we can't finish all the courses we need to return false also if we deduct a cycle in this graph we need to return false right so here the graph represents the given input so we need to finish the course 0 then only we can take course one we need to finish course one then only we can take course 2. and so on right so now we will see how we are going to do this so initially we are going to create an adjacency list of the graph so here to take course 0 we don't have any prerequisite and to take course 1 we have a prerequisite to finish course 0 right we can see that here to take course 1 we need to finish course 0. so we have created a adjacency list here then we are going to create a visited list of zeros based on the number of courses so here we have four courses so we have four zeros in this case so here we are going to keep track of whether we have visited all the prerequisite of the particular course or not right so initially I'm going to perform DFS on course 0. so in the DFS function we are going to check whether is there any cycle in the graph format right the reason why we are checking for Cycles is that if there is a loop in the graph it is obvious that we cannot complete all the courses right that is the reason we check for cycle in the graph so initially we need to check so whether we have visited the course 0 or not so in this case if we have one in the visited set for the course 0 which means we have detected a cycle right so in this case we have 0 so we can just proceed further then we need to check whether we have finished all the prerequisites of zero or not that will be indicated with 2. so here 2 in the visited set represents that we have finished all the prerequisites of zero so in this case 2 is also not present in the visited set right for the course 0 2 is not present since this is 0 we haven't seen 0 in the past right so we are seeing 0 for the first time so since we are seeing this for the first time we need to mark this course as 1 that is we are in the process of visiting all the prerequisites right so now we are going to visit all the prerequisites of 0 while we're visiting prerequisites of 0 if we deduct 0 itself we are going to deduct a cycle that is the reason why we are initializing one here so we need to check is there any prerequisites of zero or not so here we don't have any prerequisites for zero so we can just mark this one as finished course right we don't require any prerequisites for this course zero so here two indicates we have finished the course successfully right so now we need to take the course one so we need to check whether we have one or two in the visited set for the course one we don't have one or two so we have to initialize one for the course one which means we are in the process of visiting the prerequisites of one right then we need to take the prerequisites of 1 so in this case 0. so now we need to perform DFS on 0 itself so now I need to check whether I have finished course 0 or not in order to take course one right so in this case that I have finished the course 0 successfully so I will return back and I will tell here that I have finished course 0 so I can take course 1 and also there is no cycle and I have finished all the prerequisites of one so I will Mark 1 as 2. so now we need to take the next course that is course two so we need to check whether we have one or two in the course 2 since 1 and 2 is not present we have to initialize one in the course two that is we are processing on the course two right so now I need to check the prerequisites of course 2 that is 1. so I will do DFS on 1 and I will check in the visited set whether I have completed one or not so here in the course one it is 2 so 2 indicate that we have finished the course so we will return back to 2 and we say that I have completed course 1 so we can take course 2 right and we have finished all the prerequisites of two so we have to mark that I have finished course 2 as well that is by 2 right so now we need to take the next course that is three so we need to check whether one or zero is there in my course three there is no one or two so we can visit Three so we will initialize one in my third course and then we need to check the prerequisites of three that is 2. then I will do DFS on course 2 and I will check whether I have completed course 2 or not so here we have 2 in the course 2 which means we have completed so I can take course three so I will return back and we have finished all the prerequisites of course 3 and we need to mark 2 in my course three right which means we have completed the course so in this example we can finish all the course successfully so we can return true so whenever we performing and checking the prerequisites if we deduct one in the visited set which means there is a cycle or we are still haven't finished the course yet right so when we deduct that we can just directly written faults as my final answer we don't have to do anything further right that's all the logicals now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we need to build the adjacent sale list where we will be having the course and the prerequisites to complete the course right then we will create the visited list based on the number of courses so then we are going to check each and every courses to deduct cycle if we deduct cycle we need to return false else we need to return true right so now we will see the hash cycle function so in the hash cycle function we need to check whether we have visited the current node or not if it is 1 which means we have deducted a cycle so we need to return true else we need to check whether we have already completed the course or not if we have already completed the course we have to return false indicating that there is no cycle right then if we are visiting for the first time we need to initialize the current course as 1 and then we need to check all the prerequisites of the current course after finishing all the prerequisites of the current course we need to initialize current course as 2 and we need to return false if we haven't detected cycle right that's all the code is now we will run the code as you guys it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos and keep supporting us
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,222 |
all right so hello again here we are let's keep going doing more problems let's take a moment to make sure the audio is working pop out the chat in a second work on next question is going to be queens that can more problems let's take a moment to make sure means I can attack the king uh number 1222 okay have to forgive me sometimes I get kind of uh just get really down and it's hard sometimes to keep it together can be hard sometimes for me to keep it together I think I'll be right though think I'll be all right it's kind of like a chess game you know you have to really be careful with your moves game of attrition the game of attrition can be very difficult at times um okay I keep stay focused queens that can attack the King on a zero indexed 8 by8 chest board there can be multiple black queens and one white king you are given a 2d integer array Queens where Queens of I is X Queens ofi y Queens ofi represents the position of the ey black queen on the chest board you also given into Jay King I wonder if this is row column into Jay king of length two or King is X King y King represents the position of the white king turn the coordinates of the black queens that can directly attack the king you may return the answer in any order okay um many queens are there it's only 64 Queen's length King length Mo 64 given positions are unique pretty low submission rate but very high acceptance rate for the ones that did I don't think this is that hard quite frankly um oh maybe it's a little harder than I realized okay well the queen are on the board oh I see okay oh all right these three can directly attack the king and these ones can I mean basically just it's at most nine queens and it's just the nearest Queen on each of these lines if it exists um turn the answer in any order turn the coordinates of the Queens like a direct okay I want to say this is not such a hard question um yeah I mean the easiest thing to do is just go in each direction from the starting point the king down up left right uh right diagonal right into the left diagonal or excuse me right and up diagonal right and down diagonal left and up diagonal right I mean these are um dropping frames oh no um these things would be uh it's probably the easiest way to do this just dump all the Queens into a hash set to check um could just use an unordered map or just a regular set guess these are vectors actually easier would be to convert to use a hash set even easier than a hash set would be a um a Boolean array and just convert each of these to the keys in the Boolean array um yeah interesting um okay all right um yeah all right I think I have an idea how to do this okay ready this how we're going to do it how I do it on time uh five minutes okay so Boolean array has Queen um it's going to be 64 yeah 64 constant uh n or just say board size false right um and then for each Queen z b V1 key is going to be um length yeah I mean this is like M rows and columns something like this and then just say has Queen of key is true right that's encoded and then I'm going to say um for each Direction so two loops and so excuse me um yeah there's at most eight positions for the result so we're going to say in R is King zero C is King one also making sure that's correct um so the king is 0 yeah okay that's good so this King should be 0 1 2 3 0 one 2 3 three would be better if they had a king that was like well okay let's do this queen 0 1 2 3 4 I'm pretty sure it's row column I'm just going to go with row column um I'm trying to identify like one of the Queens four five 0 1 2 3 4 0 1 two 3 4 five yeah I think it's row column um anyway so uh D is going to be um Zero D column is going to be one and the way this is going to work have four directions I is less than four standard swap drdc DC * = 1 okay um constant new row is going to be row plus TR new column is going to be column plus DC uh going in these four different directions starting from the position of the king so if inbounds of so new row is greater equal to zero and new row is less than number of M rows new columns great to zero and new columns less than n columns and has Queen of new row new column then no so there's another loop okay for really while actually um well this and not has Queen um let's do starting row starting column let's do it this way of a for Loop row is starting row um column is starting column and the row and the column we got rows great than equal to zero and rows less than M rows and columns great equal to Z and column is less than number of columns and um this position doesn't have a queen then I'm going to keep incrementing by drdc okay and then we say if has Queen if we're inbounds we have a queen then sal. push back um or in place back uh well um I'm not really sure actually I think I want to do it this way let's do push back for now um row column okay it's something like this and the big difference here is going to be this starts off at uh the bottom right down one row over one column and goes each four all four directions and this one will go in the other four directions um yeah I think it's that simple oh and has Queen it's going to be not RC um but R time M rows plus C and here same thing R * m Rose plus C and here same thing R * m Rose plus C and here same thing R * m Rose plus c um slight difference here maybe I should actually have the um maybe I should make this a Boolean like double array instead of like this may not be as efficient as it could be I'm actually not sure about that um let me run this and see what I get I do on time 13 minutes um oh it's right okay maybe I just go for it I don't know see if I have any mistakes up got it nice that's what I like to see all right I'll submit this four more times and then we'll go into the next question one two three four five six one two three maybe I should actually switch the Boolean array one two three four five six I think I'm going to do that one two three four oh no 100% got one two three four oh no 100% got one two three four oh no 100% got there one two yeah so it's kind of unfortunate that my thumbnail doesn't show when I take a thumbnail it doesn't show me the uh this amount 100% it's too hard to see quite frankly 100% it's too hard to see quite frankly 100% it's too hard to see quite frankly that's pretty good okay I like that um all right very good so thank you for watching and I'm going to go ahead and um I'm going to stop the stream and restart our new question if you like the video give it a like And subscribe for more all right take care
|
Queens That Can Attack the King
|
remove-covered-intervals
|
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king.
You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing, yKing]` represents the position of the white king.
Return _the coordinates of the black queens that can directly attack the king_. You may return the answer in **any order**.
**Example 1:**
**Input:** queens = \[\[0,1\],\[1,0\],\[4,0\],\[0,4\],\[3,3\],\[2,4\]\], king = \[0,0\]
**Output:** \[\[0,1\],\[1,0\],\[3,3\]\]
**Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
**Example 2:**
**Input:** queens = \[\[0,0\],\[1,1\],\[2,2\],\[3,4\],\[3,5\],\[4,4\],\[4,5\]\], king = \[3,3\]
**Output:** \[\[2,2\],\[3,4\],\[4,4\]\]
**Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
**Constraints:**
* `1 <= queens.length < 64`
* `queens[i].length == king.length == 2`
* `0 <= xQueeni, yQueeni, xKing, yKing < 8`
* All the given positions are **unique**.
|
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
|
Array,Sorting
|
Medium
| null |
392 |
all right this league code question is called is subsequence I'm not sure if it's pronounced subsequence or a subsequent so I apologize in advance if I go back and forth between those two all right it says given a string s and a string T check if s is a subsequence of T you may assume that there is only lowercase English letters in both s and T is potentially a very long string and s is a short string a subsequence of a string is a new string which is formed from the original string by deleting some but it can be none of the characters without disturbing the relative positions of the remaining characters so for example AC E is a subsequence of ABCDE because ABCDE has the letters AC and E in it in that order but AEC is not so for example one s is ABC and t is a hbg DC so we'll return true because a hbg DC has the letters a B and C in it in that order and for example two will return false because a hbg DC does not have the letter X all right so the key to solving this problem is to use two different pointers will have the first pointer starting at the first character in the first string and will have the second pointer starting at the first character in the second string and what we'll do is we'll move the second pointer until it matches the pointer from the first string and only at that point will we move up the first pointer I'll show you what I mean so right now are the two pointers pointing at the same character yes they are so we can move them both up now we check again are the pointers pointing to the same character no they're not so we won't move the first pointer will only move the second pointer and we'll move it until it matches the character at the first pointer so we'll move it now are they pointing to the same character no they're not so we move pointer to again are they pointing to the same character yes they are so at this point we can move up both pointers move a pointer one move up pointer - now are they pointing move up pointer - now are they pointing move up pointer - now are they pointing to the same character yes they are so again we can move them both up by one now as we can see the first pointer has moved past all the letters in the first string because of this we know in this example the first string is a subsequent of the second string but let's look at an example where isn't all right so let's do what we did before we'll move up both pointers if they're pointing to the same character but if not we'll just move up the second pointer all right so are they pointing to the same character yes they are so we can move them up one are they pointing to the same character yes they are so we'll move them up one again at this point the second pointer has now moved past the last character in the second string and at the same time the first pointer has not moved past the final character in the first string so we know that one of our rules needs to be that if either pointer moves past the final character in its string then at the end we need to check whether the first pointer has also moved past the last character in the first string in this case it hasn't it's at the last character so we know that the first isn't a subsequent of the second-string isn't a subsequent of the second-string isn't a subsequent of the second-string now let's look at one final edge case alright here we have two new strengths let's do what we've been doing we'll move up both characters if they're pointing to the same string but we'll only move the second pointer if they don't match all right so do they match now yes they do so we move up the second pointer and the first pointer do they match now no they don't so we'll move up the second pointer do they match now no so we move it up do they match now no move it up but now we have a problem if we keep moving it up we just end up in an infinite loop because we'll never find a letter that matches so what we have to do is every time we move up the second pointer we have to check whether it has gone past the last letter of the second string and if it has we know we can return false because the first string wouldn't be a subsequent of the second one so let's try that again do they match no move it up no and when we get to here we've now gone past the last letter in the second string so now we can return false all right let's get to the code what leak code has given us is a function called is subsequence which accepts two parameters s and T are just two words and our job is to check whether s is a subsequence of T so the first thing we can do is we can check if s is an empty string if it is we'll return true immediately because an empty string is a subsequence of any other string so we'll say if s length is 0 then we'll just return trip all right so if that's not the case then we're going to need two pointers we'll say let pointer one equals zero and let pointer two equals zero that would look like this all right so now we'll have to move the pointers and we'll stop if either pointer goes past the last letter of the string so we'll say while pointer 1 is less than s dot length and pointer 2 is less than T dot length okay so what do we have to do now we have to check whether the pointers are pointing at the same character if they're not we have to move up pointer two so we'll say while T character at pointer - doesn't equal s character at pointer - doesn't equal s character at pointer - doesn't equal s character at pointer one so while they're not the same what do we have to move up pointer too so pointer to plus but we also have to account for the scenario where pointer to will never equal the character of pointer one so for that will say if pointer 2 equals t dot length meaning if we've checked every character in pointer - that means that character in pointer - that means that character in pointer - that means that the first string is not a subsequence of the second string so we can return false but if that's not the case meaning we're still in the bounds of both strings and the characters are the same we'll just increment both pointer 1 and pointer two so pointer 1 + + and pointer two so pointer 1 + + and pointer two so pointer 1 + + and pointer 2 + + in the example to the left that is 2 + + in the example to the left that is 2 + + in the example to the left that is the case so we can increment each of these by 1 alright let's just finish up the example are they pointing to the same character no so we increment the second pointer by one they're still not pointing to the same character so we'll increment it again right now they are pointing to the same character so we'll move them both up by 1 again pointing to the same character so we can move them both up by 1 alright so now we've gotten to the end of at least one of the strings so all there's left to do is to return whether pointer 1 is equal to the length of the first string because remember the only way the first word could be a subsequence of the second one is if we've checked every letter in the first string all right so let's run the code see how it did looks good let's submit all right so our code was faster than about 86% of other JavaScript about 86% of other JavaScript about 86% of other JavaScript submissions as usual the code and written explanation are linked down below if you liked the video please give it a like and subscribe to the channel it helps out a lot see you next time
|
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
|
1,759 |
let's solve the today's lead code challenge which is Count number of homogeneous substrings so in this problem we are given a string s and we have to find the number of homogeneous substring of s so what is the homogeneous substring uh any string is called homogeneous if all the characters of the string are same for example a is homogeneous let's say a is homogeneous this XY is not homogeneous BB is also homogeneous a b c is not homogeneous okay you got the idea so here uh what we have to return is let's say we are given a string XY and we have to return the number of homogeneous subst so XY is having a substring of X or Y and XY now analyze uh if x is a homogeneous yeah all the characters in The String are same Y is also homogeneous but XY is not homogeneous so its answer would be two so in this example a b c a what are the substring so let's say start with a A is also a substring which is homogeneous if we take uh BB together b this is also a subst and it is homogeneous but apart from that all the substring of this substring will also be homogeneous let's say uh take further substring which is having same number of characters c yeah this is homogeneous and apart from that all the substring that is that it uh it is going to have will also be homogeneous and after that a is also homogeneous so I just broke down the given string to this form so a is not having um any substring so we will count one from this side so BB how many substring does BB have you can calculate by uh checking the length of the string so BB is having two length so we can first uh find all the substring of two length and then all the substring of one length and for zero it is nothing in this case CCC substring is having length three so firstly uh to break down this string into substring we can find out all the substring with length three C CC and after length two which is CC the first CC then the second one and then uh for the length one it is C comma c 1 2 3 4 5 6 so if the length is three then we are getting six substring if the length is two we are getting three substring B and B okay so if the length is two so let's write down the all the substring homogeneous substring of a first a and then second a which is three so here you can an analyze for any uh substring let's say x to write down the substring we can uh all the characters in The String are same so firstly we will uh find the substring of n length which is the length of given substring and then n minus one which is two then n minus 2 which is 1 until n until uh this nus 1 becomes 1 which is n equal to 1 from n = to 1 to which is n equal to 1 from n = to 1 to which is n equal to 1 from n = to 1 to given number uh let's say let call it this variable I from I = to 1 to n we going variable I from I = to 1 to n we going variable I from I = to 1 to n we going to take the sum okay so in this case what would be the sum would be 1 plus all the substring of this BB which is three 1 + 3 + is three 1 + 3 + is three 1 + 3 + 6 + 6 + 6 + 3 which is 13 so 13 would be our answer so instead uh so how do we check that like uh firstly we will break down this string into the homogeneous substrings it means like all the substring with same character will be a separate part so let's say uh we calculated a we calculated BB and while we are doing the iteration of this string we are iterating from I equal to 0 to n and while doing the iteration we can capture the length of the current homogeneous substring So currently let's say we are at the first element so length equal to 1 and the current character equal to a which is the case of for case for the first element so if we move to the further which is B in that case we will compare it with the previous element so we will compare B with a so B is not equal to a so it will it means we will reset our value of length and character so character will now point to B and length will be again reset to one and then in the next iteration so it is again the equal to the previous element so length will become two and the character will remain the same in the further case now let me move that down so now in the further case which is the case for C so when our Loop will come to this first C the length will again become one and the character become C so in the second iteration length will become two and the third iteration length will become three okay and then for the these a Here length will become one character is equal to a and the last index length will become two so in the previous uh example of for the BB like what was the answer uh for all the substrings homogeneous substring which was uh number of uh integer sum from 1 to n so in this case in the iteration also the number is from 1 to 3 so if the length of homogeneous substring is three so in this case we will just have to calculate the sum of 1 2 3 so it means that a will be form one substring and BB will Form 1 + 2 which is three substring and Form 1 + 2 which is three substring and Form 1 + 2 which is three substring and Triple C will Form 1 + 2 + 3 which is Triple C will Form 1 + 2 + 3 which is Triple C will Form 1 + 2 + 3 which is six substring and a will also form three substring okay so this will be our answer let's try to code it you will understand better so here we will just have to move an iteration from first index to last index or maybe we can initialize for the first index because the constraint is from the given string length is from 1 to 10^ 5 so it will definitely be 1 to 10^ 5 so it will definitely be 1 to 10^ 5 so it will definitely be having one character so first character we can directly say that length is one and the current character is a and for the further runs we can just uh match the character value from previously stored character okay let's say int length which is our current length of uh which is current characters uh length for the first character it is one and the first character is s do character at zero okay apart from that we will also track our answer variable which will store for the value of length at every index which is 1 2 3 and 1 two we'll just have to calculate the sum of these length variable for every iteration so we will start our iteration from One S do length i++ Okay for the first character we have i++ Okay for the first character we have i++ Okay for the first character we have already calculated our length so for the first character the answer will also be one now we are starting from second character so for the second character we will check the character value from the previous character so if s do character at I is equal to previously sto previously stored character so in this case what we will do is we will just increase our length else if the current character is not equal to previous one in that case we will reset our character s do character at I so now we have got this length at the first index which was one so we will keep on adding the length in our answer variable so answer plus equal to length and just in the last we will return answer let's try to check it on the sample test cases yeah apart from that okay for this variable it is giving 22 for one to length s. character is equal to previous character length equal to 1 otherwise character is equal to this and we will also reset our length to one apart from that we are also given that we have to take the modulo 10^ 9 + that we have to take the modulo 10^ 9 + that we have to take the modulo 10^ 9 + 7 so for that I'm just taking another variable 10^ 9 + 7 no okay so after storing our answer we will just keep on doing the modulo okay it goes submitted so what we did is we just initialize with the first character because first character is definitely going to be our uh homogeneous substring so answer is one so for the first for the substring we just calculated it uh compared the current character with the previous one if current character is equal to the previous one then we will increase the length otherwise we will set the length to one and update our character and for the case where it was CCC which for the CCC number of subring that it has is sum of element from 1 to and which is 1 2 3 so which is already in our length variable so that's why we just added the value of length for every iteration and we found our answer okay guys thank you so much bye-bye
|
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
|
127 |
foreign word letter welcome to my video let us begin in this problem we are given a starting word from which we are to reach an ending word in a series of Single Character switches using words from a given list all words must be of equal length in this method we will set up a graph of all the words in the given list that differ by one letter then we will use this graph to solve the problem by employing the BFS approach we will transform hit to Cog using these six given words each word has same length equal to 3. the result is 0 if length of words is zero or if N word is not in the list let us set up the required graph we Define a dictionary and process the words in the given list one by one first word is hot it has three characters one by one we replace these characters with Dash in the first iteration we get Dash OT we save hot against this generic word in the dictionary next iteration gives H dash t which is also added to the dictionary in the next iteration h o dash is added next word is dot which gives three generic words as shown dashot is already in the dictionary we add a new entry in the list against it and add the other two keys in the dictionary dog is added to do Dash and we add two new entries in the dictionary next three words complete the dictionary as shown graphical representation of first line of dictionary is that hot Dot and lot are connected with each other by a single switch next three entries in the dictionary are single terms Dot and dog are linked with each other dog has two more links namely with log and COG finally lot and log are also connected Cycles are present in this graph so it is not a tree to avoid repetitions we Define a list named visited with begin word as its first entry Cog is the end word in the graph we use a queue to manage BFS the begin word at level 1 becomes the first Tuple in the queue we use while Q to start BFS in every iteration we pop out one entry from left of the queue to follow the first and first of basis and they become current world and level if we start a loop to obtain three generic words of hit first generic word is Dash it is not present in the dictionary so next for Loop is skipped next generic word is H dash t for which list has only one word hot is not the end word we added to visited list and also added to the queue for level 2. they look terminates we clear the list for H dash t this helps in preventing futile repetition in future cases third generic word is h i Dash This is not present in the dictionary so the iteration is skipped we move the queue further hot is extracted from the queue and it becomes the new current word its first generic word is Dash OT it is present in the dictionary which has three words in its list in the first iteration word is hot it is not the end word but it is present in the visited list so we move to the next word is Dot it is added to visited and also to the Queue at level three next word is lot which is also added to visited as well as to the queue after processing all the words of dashot its list is cleared next generic word is H dash D but its list in dictionary is empty third generic word is Echo Dash it has only one word hot in the list which is already in the visited list so we clear this list without any processing all the words at level 2 are processed and now we will process the word dot at level 3 by extracting it from the queue first generic word of dot is Dash OT for which the list is empty next generic word is D Dash D it has only one word dot which is already visited so we clear this list do Dash has two words dot is already visited we now add dog in its visited list and in the queue we clear the list for do Dash now we extract lot from the queue which becomes the new current world its first generic word is dashot for which list is empty next is L Dash T its word lot is already visited we clear its list next is hello Dash lot is already visited we add log in visited list and queue and clear the list we know extract dog from the queue dog becomes current word its first generic word is Dash OG which has three entries out of which dog and log are already visited the third word Cog is the n word so process is terminated and 5 is returned as the result note that we have been adding and removing words in the queue we break out of the loop only when the N word is encountered in case all the words in the queue are processed without coming across the end word the return value is 0. in BFS approach all nodes of a particular level are processed before shifting to the next level this ensures that the length of the path is the shortest for n-words of length M each time for n-words of length M each time for n-words of length M each time complexity is of the order of M squared n because of each word in the list there are M generic words there are M times n iterations to create the dictionary further formation of each generic word takes time of the order of M in the worst case we may have two Traverse all the words of the list each of the n words has M generic words so in the dictionary there are M times n entries each of the size M so space complexity is of the order of M squared times n this is an improvement over the previous method we start cues from both beginning and end and move the queue which has lesser entries this way we cross over to next level in lesser number of Trials process stops where the two sides arrive at a common node in this solution we Define class level variables length and generic dictionary length is 3 in this example we Define a function visit node which we will discussed in a bit we will now write function ladder length based on bi-directional BFS bi-directional BFS bi-directional BFS we check that length of the word is not 0 and end word is present in word list we set up the generic dictionary as before we Define two lists Q begin list has begin word and Q and has n word we also Define two dictionaries in visit begin word has value 1 and visit and has N word with value 1. we Define ons equal to none and we start a loop that runs while neither of the queues are empty in order to get new value for and we call the function visit node for the queue which has lesser entries three variables will acquire new names in the function as shown in the present case Q begin becomes a q in the function inside the function we Define variable queue size which gets value equal to the length of the queue which is 1. presently Q has only one entry so the for Loop will run once only in this iteration the word hit is popped out of the queue and it becomes current word in the nested for Loop we generate its generic words first is Dash ID it is not in the genetic dictionary so the next for Loop is skipped next generic word is H dash T only word present in its list in the genetic dictionary is hot had it been present in other visited the problem was solved as the two paths join however it is not present in other visited it is also not invisited so it is added there with value equal to 2 and is also added to the queue third generic word is h i Dash but it is not in the general dictionary all Loops terminate without any solution so we return none to the calling function all local variables are cleared and the function parameters acquire their original names The Returned value is stored in answer which remains none both the queues are not empty so the loop continues we notice that all changes are similar to the previous method in the next cycle hot is extracted from Q begin while Dot and lot are added to it and also to visit it begin note that Q end is now shorter than Q begin so in the next cycle Cog is extracted from Q end in this call visited end will become visited and visited begin will become other visited dog is added to both q and visited end once again Q end is processed its neighbor dot is present in other path so the process is terminated and 5 is returned arms becomes 5 this time which is not none so it is returned as the final answer this takes lesser time as we do not have to process lot at any stage time complexity is same as before however the number of iterations can be lesser because we separate the queue into two parts we know that number of entries in a BFS queue it increases certainly if its number of levels become very large therefore in this case the execution time can be much less memory used in forming the genetic dictionary is the same so space complexity remains unchanged thank you all for watching the videos please stay tuned for more such videos and please subscribe to my channel
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
1,423 |
Hello guys welcome to another video desi of wedding ude abir volume ko maximum points are given from quartz use subscribe thank you solve 123 subscribe 428 voter card maximum maximize your first look a beneficial planets account from the end again in special fruit also Din Tune Pic Whose Twitter The Channel Possible Solution In This Is For OnePlus One Plus Two Plus Subscribe Definitely Interview Maximum Select Me To The First 100 Subscribe OnePlus 6 Idi Maximum And Do n't Forget To Subscribe My Channel Pim's 12th Maximum Possible to dedicate and decree producer oy give examples for I want to make the model of the time subscribe video to like and subscribe 12345 reason use tollywood 10 back to three four 5 to alive case when you in the last 60 1234 six pieces IMPORTANT TO YOU TO THE ELEMENT WHICH IS THE MAXIMUM SOLUTION FROM MANDI WA KULLU * SUBSCRIBE 123 LIKES SUBSCRIBE AND SUBSCRIBE TO A PLUS FORM VISITAM AAT PARTICULAR EUROPE KE SUICIDE MARG 1012 324 506 EXEMPLARY TARF WANT TO FIND THE SUM OF THE FIRST LOOK OF Elements subscribe The Channel subscribe Video subscribe - 9000 subscribe and subscribe this One That The Sum of Particular Servers Down I Know What is the Score of Living for the The Total of the Total Sunday December 02 - 09 2018 2019 A Ride in a Flat Example Again 12345 6 OK Select Govardhan Example From The Beginning Water Proof Smudge Clips 1234 5 To 6 Minutes Subscribe And Morning From The First Subscribe And Share Subscribe To Hai So Let's Tried To Find Out The Sum Of The Year Gone To Restore Initially This is my start hokar is equal to zero is my start end Jassy VC Safar reader will type this bell website for what is the sum of decide what is the name of the simply tempo key right now let me answer Eden total arm hole subscribe - 10 total arm hole subscribe - 10 total arm hole subscribe - 10 Upalsari Plus Point Is Equal To Take Android Sudhanshu Restant And Account Certificate 600 800 This System And Let's Go For Example Awal Example 12423 45 To 60 The Number Three 500 Answers For The Hello Some Vector Plus Viewers Nav Samvatsar Just 100000 Don't forget to subscribe and subscribe -0.182096 0 4 6 2 Mein subscribe -0.182096 0 4 6 2 Mein subscribe -0.182096 0 4 6 2 Mein Peeth Is Side Aur Batte Cigarette Adi Indore Ladies First Sermon On Forest Wealth Who Want To Maximize The Course Will Not Change The School Will Determine Which Should Not Just For Example A The Cinemax Particular example will have equal to and equal to 500 will have equal to two android app that this apps that i get total 250 this particular inductive businessman december if and to into fiction with one sweeping this particular rich this and midfielder carles 121 0.46 find the The Mystery For - Release 09456680640 One Mystery For - Release 09456680640 One Mystery For - Release 09456680640 One Plus One Is It Not Becoming A More Question Is Like Dot It Features Mom Mar 10 Avatars And How To Find The Maximum Beach Certificate So Let's Go Slaughter Elastic Example In The Last Example Is Equal 302 60 Plastic Example You Noticed That You Have This Particular Early In The Morning How To Find The Subscribe To Adjust 1622 - 6 - 6610760 Subscribe Now To Receive 1622 - 6 Is Equal To Six Particular 1622 - 6 Is Equal To Six Particular 1622 - 6 Is Equal To Six Particular 's Notice To The Maximum School Finally 's Notice To The Maximum School Finally 's Notice To The Maximum School Finally Returns The Video then subscribe to the Page if you liked The Video then subscribe to the Page Tomorrow morning hydrating over and let me declare variables it means college donate system in committee sheds the phone hai to remedies 10 time dip hundred point and once yadav edible sum you can just you know it Say It Means Change The Capital Of The Are All The Best All The Name Of Subscribe Now To Receive New Updates Drop By Side With You For You Can Even Look For This Point To Point Dots Plus Setting Show 288 From Zero What Is In The Last example I ranges from 023 only will not go to the end of the year in this way I just need to go up to elements in this will give us all a very happy for the start and end sliding window into what is the land sliding Window Switch Just See The Example Of Sliding Window - Just See The Example Of Sliding Window - Just See The Example Of Sliding Window - 300 Points 138 Who Is Equal To The Length Of Units Sliding Window 10 I Plus Point That Now Dot Side That And Whom 180 I Will Be For Example 0 First K And Points Size 207 And What WILL B AND KK WILL BE 300 IT WILL RAIN FROM THE ROAD TO SO PRESIDENT VIKRAM EQUAL 245 E WANT TO RANGEED FROM BLUETOOTH TO WIDE AND - BUN HERE DIGEST BILL FOR OK AND - BUN HERE DIGEST BILL FOR OK AND - BUN HERE DIGEST BILL FOR OK SUBSCRIBE AND CAN JUST HAVE THE SUM OF THE YEAR TO RETAIL DECLARATE INTER School Quiz Available only to find the total Subscribe School Subscribe Answer The answer is the problem is some of married but they are going to remove ho the walking and they all should declare intoxicated What is the answer go into this is it is pet saaf - finished - 1st into this is it is pet saaf - finished - 1st into this is it is pet saaf - finished - 1st law from the we with whip will poison we will give equal to zero simply give answer will be minus one total subscribe button to the student particular's share and finally vijendra returns to suji logic and know in it what happens When you know when you have this particular subscribe to the Page if you liked The Video then that card point dot size will shrink by shrinking this you can simply available on the cause of Protestantism Sundha Sangathan C1 VS working on that citric acid thank you for watching painter
|
Maximum Points You Can Obtain from Cards
|
maximum-number-of-occurrences-of-a-substring
|
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain.
**Example 1:**
**Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3
**Output:** 12
**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
**Example 2:**
**Input:** cardPoints = \[2,2,2\], k = 2
**Output:** 4
**Explanation:** Regardless of which two cards you take, your score will always be 4.
**Example 3:**
**Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7
**Output:** 55
**Explanation:** You have to take all the cards. Your score is the sum of points of all cards.
**Constraints:**
* `1 <= cardPoints.length <= 105`
* `1 <= cardPoints[i] <= 104`
* `1 <= k <= cardPoints.length`
1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.
|
Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce.
|
Hash Table,String,Sliding Window
|
Medium
| null |
1,690 |
So hello friends welcome back and in this video are going to see in the amazing problem express train china 768 toll free contact no in toilet saaf baje gym witch direction places baba play list subscribe button subscribe like and subscribe mean that subscribe assigned sleep Open play store that triad to some thing positive person toot answer is need to answer this kar aa light bill ko difference daba subscribe difference bihar stones specific what is the difference between the 109 subscribe my channel short that you MS Word Tiffin Samagra 5314 Do A Souvenir Way To Options First Understand What Is The Latest Subscribe To Subscribe Kintu Na Teri Meri R S Way Know What Will Be Difficult Maximum To Second Latest Posts By Subscribing Shooting 50 Efficient To The Meaning Of Nothing But The Number Subscribe 9.66 Subscribe 3505 Subscribe - 500 Number Subscribe Now To - 500 Number Subscribe Now To - 500 Number Subscribe Now To Receive New Updates Reviews Question What Was Actually December Satire It Is The Meaning Of Subscribe This Video Subscribe - 36 Cigarettes The Video Subscribe - 36 Cigarettes The Video Subscribe - 36 Cigarettes The Subscribe Now To Receive Thursday Subscribe Now To Do Subscribe My Song Do The REMAINING PART WITH NOTHING BUT FOR IN THEM GUILTY BUT 512 SUBSCRIBE NOW HE GUYS TEMPERED GLASS TO IS USED FOR ITSELF AND THE AWARD 400 HE GET NOTIFICATION Vikas Notice MP Addictive Video Shooting And Everything Is Who Nothing Is The Meaning Of You Will Choose Not To Appearance Gets It's Just Malik Subscribe Button Wash Id Subscribe And Subscribe The Ko Subscribe And Subscribe Quote Pack Speed Five Suhaagses This Because She Is Pack Speed Five Suhaagses This Because She Is Pack Speed Five Suhaagses This Because She Is Attracting Ko Rumor Ko Fried Eggs 19 Hours Ago At Every Possible Effort To Maximize Your Limits Chus Thee That It Is Slide 5314 280 531 Middle Age Subscribe Button More Subscribe 512 Maximum First Hai Next 9 News Room Se Hua Tha For Every State Both Actor Will Also Conducted And Subtracting Love You Dies Amazing Minor And subscribe The Amazing subscribe Video plz subscribe Channel Please subscribe and subscribe the Channel subscribe and subscirbe Subscribe to Mausam Loss Reduction Activists Were Also Need to Pass My Clear Which Nothing But - The My Clear Which Nothing But - The My Clear Which Nothing But - The Spirit Will Be Id Am I My Chus-Chus The Spirit Will Be Id Am I My Chus-Chus The Spirit Will Be Id Am I My Chus-Chus The Element Next to Do - - - 1929 Task Complete in Chanod Force Wanted Significator Maximum Will Just Maximum B2 Options Simple Deep Web Subscribe 601 Simpler To Aa Enjoy Simply Acid Simpler To Aa Enjoy Simply Acid Simpler To Aa Enjoy Simply Acid Simple Subscribe Me To 9 10 Amazon Found In This Is The Sum Of My Life My Standard Procedure Of Mid Size In Presentation P Audio Dpr Having Otherwise Mist img20 Aa simply this function call which is a festival function more people liquid and one option aa blind with account or answer status the question side should you need anything but nothing but - side should you need anything but nothing but - side should you need anything but nothing but - 1 - subscribe to the Page if you liked 1 - subscribe to the Page if you liked 1 - subscribe to the Page if you liked The Video then
|
Stone Game VII
|
maximum-length-of-subarray-with-positive-product
|
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score.
Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._
**Example 1:**
**Input:** stones = \[5,3,1,4,2\]
**Output:** 6
**Explanation:**
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\].
The score difference is 18 - 12 = 6.
**Example 2:**
**Input:** stones = \[7,90,5,1,100,10,10,2\]
**Output:** 122
**Constraints:**
* `n == stones.length`
* `2 <= n <= 1000`
* `1 <= stones[i] <= 1000`
|
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
743 |
hello everyone welcome to day 14 of lead code my challenge today we have question number 743 network delay time so in this question they have given us a network of n node labeled from 1 to n and we are also given times a list of travel times as directed edges u v and w where u is the source node v is the target node and w is the time taken for a signal to reach from source to target and we will be say we will send a signal from a given node k and we have to return the time it takes for all the endnote to receive the signal if it is impossible for all the endnotes to receive the signal then the answer then it will return the answer minus 1 neither wise it will return the total time taken so in this example this is the directed graph where the total node is 6 and the source node is 3. so from 3 we will give the signal and we have to find the total time it takes for all the end nodes to get that signal so first thing is here we will create a variable total time which is initialized with value 0 and we will create a visited array which will keep like which all the nodes are visited and which are left so this will be of same size as of the node four five and six so first thing is first we will create a mapping of the node and to its connected nodes like three is connected three it's directed with four like from three we can go to node four we can go to node five we can go to node two so that is what we will create a map like from three we can go to node 4 with a distance of 1 or the cost we can say or the time we can say of reaching the signal from 3 a signal can reach to node 5 with like and the time it will take is 2 and from 3 we can the signal will reach to node 2 and the time it will take is 1. similarly for note 4 the signal can reach to node 5 and the time it will take is one and there is no other node to which signal is to from like which 4 is directed to so yeah now we will take the note 5 note from note 5 we can send signal to node 1 with a distance 1 and then we have node one from node one we can give signal to node six and the time it will take is one and from six we cannot there is it's doesn't have any node to give signal and neither 2 is also not having so this is what we got the mapping and now we will create a priority queue and the priority queue will be based on the minimum distance or the minimum time here i am using the distance so first thing is we will add our this is our source node we will add a source node and if the so if the source is also three and the destination also is also three so the signal will take zero time to reach over there so that's why its distance is zero and we are using the bfs tri vessels we are traversing in the level by level like first three then two and four and so on so that's why first we will pop this three and then we will check the minimum sorry maximum distance or the or we can say time or distance so i am using the word time so this is also 0 no need to update so the maximum will become zero and once the three is visited now we will add all the nodes that three are connected to like two four and five and we will as we are using minimum priority queue so we will give the highest priority to the node which have the minimum distance from node 3. so now here i am going with 2 comma 1 and then 4 comma 1 you can first you can write 4 comma 1 and then 2 comma 1 it same thing because both have the distance one and then we have this five comma two now three is done we have added its connected nodes also so we will mark visited to 3 and then we will move to our next leak we will pop the next node from the priority queue that is 2 and then we will see 2 is not connected with any node like 2 it doesn't have any directed signal to any of the nodes so it's not going to provide signal to any node so the we will find the minimum distance from one and zero that is one so we will update this y one and mark two as visited and then we will pop the next node in the priority queue that is 4 comma 1 for 4 comma 1 it is directed to 5 but the distance it will take is its distance that is 1 plus the reaching from 4 to 5 distance that is one so we will add that is five comma two so it is no it cannot provide signal to any other node it was just connected to five that we were we added in the queue so we will mark four also has visited and now we will move to 5 comma 2 we will pop this out 5 can send signal to node 1 and with a distance 1 from this and 2 it is like coming from 3 and four and then it's reaching five so two and two plus one is three so one comma three this is one comma three so now the total maximum distance is two or one is 2 so we will update this total time mark 5 as visited and then again we got we will pop out this element this is 5 and then we will see it's already visited so we will move to 1 we will pop out one we will see the maximum distance three and two we found that three is the maximum distance we will write three and then we will add the children i mean in the sense children is like one can send signal to six so we will add the node six and the time it will take is like one of this is two from reaching from one to six and the other is three so total is five so we will mark one as visited and this is six comma five so five is the so for one we are done then we will next we will pop out five for five it's not it cannot provide signal to any node so we will just see the total distance that is five and the three which one of which like three or five which one is maximum five so we will update this by five and mark 6 has visited now we have visited all the nodes and the total time which we got is 5 that is what we have to written it as the answer so now let's code it up first thing what we will do is we need to create a class why we need to create a class for this mapping this is like the target node and the distance or the time it is taking and this is the integer basically for that like we will build a graph so what we will do is we will create a private class let's name it as node which will have the two variable one is the target because in this question it is mentioned like v is the target node and w is the time taken so target and the other is the distance or the time taken we can say and then we will create a constructor the first thing is i have written a spelling wrong it's t a r and then target and this dot distance is equal to this distance first thing what we will do is we have to create a minimum heap or the minimum priority queue so priority of type node we will name it as pq priority queue is of which type we want that it should consider it should give the highest priority to minimum distance a dot distance minus p dot this so this we have created a priority queue next thing what we will do is we will create a map of integer comma set of node which will have graph or the builder since and we will provide here the times array and the other thing is we need to create a set of integer which we will name it as visited we will add the element those who are visited in it hash set this we are done for graph what we will do is we will create a method of type map and we will name it as build graph our input is the array times area and then we will check for integer area time times zero we will initialize with new hash set always map dot get of zero and we will add what we will let time of one that is the target and the distance but here we have not created any map so first we will create a map so our build graph is ready after this what we will do is um first thing is in the priority queue we will add which will have this source node and from source that is the this and the like target node and the distance is zero and then we will create a variable total time that is what we have written and if we didn't get then if there is one node left also and we couldn't then the signal couldn't reach there then we will written minus one for example if like for now one is directed to six if in any case if this direction would be this from 6 to 1 we can never reach 2 6 then we cannot from 3 we cannot give signal to each and every node and that case it will written minus 1 okay so that what i have mentioned over here so we will written minus -1 but before so we will written minus -1 but before so we will written minus -1 but before this what we will do we will create as we are doing the bfs travel cell the basic one if this is not empty what we will do we will take out its size that is pq dot size and then we will create a loop while size is greater than zero then what we will do is we will create a node head and we will pull from it and then what we will see is this visited contains head dot target if it's already have the its target note present we'll just continue neither wise we will add head dot target and the total time we will update the total time that is mad dot max off total time compare it with the head dot distance now we will check if our visited dot size is equals to n that means we have visited all the node then we will just return total time if map dot contains dot target then we will add its children so for node let's say children or the other node which is which it is connected to like two can send signal to three and one so in this case i am calling this three and one its children so we will get this from map dot get head dot target and we will create integer that is children time so this is equals to what this is equals to the children distance plus what the head distance and then we will add this in the queue pq dot offer new node children type and we are done let's run it thing is we have to use here contains key and the other thing is we have to add this it's in the node in the constructor so it's of type node and we are missing this over here let's run it now it's working let's submit it we are done thank you
|
Network Delay Time
|
closest-leaf-in-a-binary-tree
|
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
|
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
1 |
so in this video I want to do a coding interview problem I usually code to do problem solving because I feel like it's a really great website and has a lot of great problems that are given in interviews so that's why I usually code I also use Packer rank and others so I wanted to show you guys a problem and how I solve these type of problems so the first problem that I want to do is a twosome it's called su some difficulty is easy and even though the difficulty can be easy hard medium definitely when you're getting interviewed with the pressure from the other end other interviewer I still believe some type x easy problems can be quite difficult especially when you're at in that zone when you're really pressured so it's really good to practice over and over our practice you know trying to sell these problems in a certain amount of time and just putting yourself in the situation where things can be more comfortable to you I also like to start my problems in C++ because I feel like it has a really C++ because I feel like it has a really C++ because I feel like it has a really great library that STL library and I just feel more comfortable doing a lot of these interview questions in C++ so of these interview questions in C++ so of these interview questions in C++ so let's get to the problem and the first thing I want to also say or something else I want to say is the first solution I'm gonna give you guys is a N squared solution but there is a faster solution and I will go through both solutions and the reason I want to do that is because the first one is pretty obvious and the second one might not be so obvious obviously when you do a lot of these problems a lot of these companies want to see you do a problem and can you optimize that problem can you make it faster so I want to show you add that as well so the first question is give me an array of integers so I'm gonna be given this array so technically I can see from my parameters that array is nums so this nums is an array with house 2 7 11:50 11:50 11:50 returns and indices of two numbers such that they add up to a specific target that pretty much states that two numbers in here add up to nine so as you can see because numsy row plus 9 1 2 plus 7 equals 9 I'm gonna return 0 & 1 equals 9 I'm gonna return 0 & 1 equals 9 I'm gonna return 0 & 1 so in any array given to me there could or it cannot be an answer but here says you may assume that each input would have exactly one solution so right there I know that no matter what really gave me there's always going to be a solution so I don't have to write code for that test case and also says and you may not use the same element twice so that's something I have to think about and make sure I implement in my code so the first thing that I'm thinking about is that N squared solution I could do two and compare 7 do to compare 11 do 2 and compare 15 the reason I didn't do to then check 2 again it's because you know I don't want to use the same element twice so then I loop again I use 7 compared with 11 7 compared with 15 then do 11 and compare with 15 so that's a pretty good solution doing comparisons to comparing 2 with everything 7 with everything 11 with everything 15 with everything and on and Bruce bigger rate and the way I can like that is you know do a for loop so I'm gonna do from 0 so from 0 to the size or a lesson to the size of the array and it's actually for two for loops because I'm not only going once I'm doing - going not only going once I'm doing - going not only going once I'm doing - going looping through these 7 looping through these 11 looping through these so I'm gonna have two of these and they both are gonna loop the size of the array so here I have this is gonna loop to then it's going to go to the seven so this is gonna go to the two to the first one then this one is gonna do seven eleven fifteen but I don't want to do two twice so I only wanted to do the next one so if I write one that's actually not gonna help me because that's always gonna do one so that means is if I'm in fifteen it's not going to do the next one it's just gonna do this one I wanted to do the next one after where I'm at and that's I where I'm at and the next one so that means if I'm in seven so let's say this look the first time two then it does seven the next one I 1 is 11 this is gonna go to the third element and all I want to do is right here is check if nums I and next to it equals to target then I'm good then I have answer so the way I can write that is if nums I plus nums J equals to the target then I'm good and I have the answer actually I'm going to put brackets there so once I'm at this point I have to think of exactly how am I going to write this so if I have two and seven so I have 2 plus 7 because that case is eventually gonna happen equals 9 what am i exactly gonna save I have to save this index and this index so where am I going to save it obviously I need to return an array so that means I had to save my answers in a tray so what I could do in C++ a vector tray so what I could do in C++ a vector tray so what I could do in C++ a vector pretty much an array I could do an array of size 2 and what I would do is do you know my array of 0 is gonna hold you know the index of I and then it's gonna save the index of J so it's gonna save the index 0 and the index 1 if I did numbers one is gonna save that too and that 7 but I wanted to see less to in the 7 I wanted to save just an index so that's why I'm doing here one saving index not number and same as above save index so looking at my code everything looks fine this is running N squared see here this is running and squared and the last thing I need is to return my value or return my array so I'm gonna return my array so to go over everything again this is gonna do it N squared loop so it's gonna do - for the first loop so it's gonna do - for the first loop so it's gonna do - for the first loop and then for this one is gonna do 7 11 15 and do comparisons then for the next one is gonna do 7 and then for all these is gonna do 11 and 15 then let's go I'm gonna go here again to 11 and then check at 15 so once that's done and once you find the target of Ni plus NJ is gonna equal the target I'm gonna save those indexes to this array and reach in my array so I can run this code and this is pretty much a test case solution and I'm gonna step in my solution and see if that's correct and as you can see the answer has been accepted so my n square solution works however I don't want it n square solution because there's a faster I can actually do this similar every time so there is a way that I can run through this array only once and so instead of having to do 2 7 11 15 I can literally go through this array 2 7 11 15 once and I'm done and there is a solution obviously that solution you have to think a little bit more think about it a little bit more and a little analytically so I'm going to show you guys how I came up with that solution and what I actually thought of so I'm gonna erase all this so to run the linear solution I have you have to think of a different approach so there is a way actually to solve this where you can actually just go through this array one time you don't you do to 7-eleven 15 7 11 15 you don't you do to 7-eleven 15 7 11 15 you don't you do to 7-eleven 15 7 11 15 you can actually just run to 7 1 15 and the way to solve these problems is that think of algorithm data structures that I think about a heap think about binary tree and map stacks and queues which of those can I apply to this problem so it can give me a linear solution I know aha and you can just the more you start working with these data structures the more comfortable you can get with them for me using a map is very simple and I feel like I can use the map to solve this problem in linear time so what I'm gonna do actually is what I want to do is I want to do 9 minus 2 and if in my map 7-eleven or 15 exist then I map 7-eleven or 15 exist then I map 7-eleven or 15 exist then I have an answer the same thing with second I could do 9 minus 7 which is 2 if to exist in my answer and in the array in my map then I have the answer then I could do the same thing 9-11 if then I could do the same thing 9-11 if then I could do the same thing 9-11 if negative 2 exists in my array then I have my answer so I'm not looping over and over I'm literally looping through this one time so what I'm gonna do in my array is save to as a value 0 7 as the value of 1 11 as the value 2 and 15 as about a 3 and the reason I'm saving these as the value 1 0 2 & 3 these as the value 1 0 2 & 3 these as the value 1 0 2 & 3 Tory's only reason that would matter right now is because it says you may not use the same element twice so for example let's say I have a 3 and I want you know the target at 6 and I have this 3 and my algorithm says do you have a 3 then it can be yes but I have to make sure that is not itself so I can have 2 3 4 I just have to say if 3 exists or yeah you let's say I have this 3 & 6 minus 3 you let's say I have this 3 & 6 minus 3 you let's say I have this 3 & 6 minus 3 is 3 so if 6 minus 3 equals 3 so if 3 exists and we're is not three so itself is not three then I found the answer so the first thing I need to do is put these values right here in line five in a map so the way I can do that is to just do a regular for loop this is actually gonna run one time and it's just gonna do the size of the array so I'm gonna do that even need these brackets I can just say I'm actually gonna write everything here some say map of type a map is a key value pair for yes I don't know do my map so my map of 2 equals 0 of 7 equals 1 of 11 equals 2 and then here this is also going to run in linear time is also a for loop and I'm gonna do what I'm talking about I want to do this nine minus two so I'm gonna write I'm gonna make a variable I'm just gonna call it Kampf do target - I'm just gonna call it Kampf do target - I'm just gonna call it Kampf do target - my num 0 which is 2 so 9 minus 2 is 7 so if 7 exists and the value 7 is not itself so I'll answer and the C++ to do itself so I'll answer and the C++ to do itself so I'll answer and the C++ to do that's pretty easy you can say if my map comp so 9 minus 2 is 7 so if that's true that is in my map and my map 7 which is 1 is not equal to my mind variable so it's not so if 7 which is actually 1 is I'm not in this place so it's different then it's not itself then I found the answer and all I need to do is save that information and I can see that information in an array or a vector so I'm actually saving so I have to save the indices so the sort of the index which is 0 because that's around that index and actually the not the my map comp is 7 but that's actually 1 so that's the index so technically these values are here are the indexes so I can even write right here sorry I can write here saving index to value and so my map is technically a value index pair innovative one equals my map and all I need to do is we turn my array but I never declared this array so what I can do right here is do my vector and array the size two and let me see if it runs with the test code right now so your answer expecting a certificate so we for said ma'am I said let me submit my solution see if I got this correct my answer was actually accepted and this ran in linear time so to go back to what I did is I did a map of actually value and index pairs so this is an X 0 and X 1 and X 2 and X 3 a value 2 7 11 15 and I put that in my map pretty much what I said here I'm gonna run this one time I'm gonna do 9 minus 2 which is 7 so here 9 minus 2 equals 7 if my comp 7 if that exists if my comp 7 exists which it does even though it gives you 1 it exists because if I if this actually would have been an 8 this would have been false this would have given me a false and never gone in there so if 7 if it's in there and my seven witches in that this is my index 1 is not the same index because if this would have been index 1 that means I'm reading that 7 value twice so this is actually for the first time is 0 so if it is there and it's not the same value then we're good save the indices to my array and return my array and that's how I solve this to some problem linear time thank you
|
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
|
983 |
hello everyone welcome to another one of my lead code videos and this one we'll do lead code 983 minimum cost for tickets this is today's daily challenge so we're basically given two arrays one is the number of days we want to travel or the days we want to travel and the other one is the cost which is basically the cost of a one day pass a seven day pass and a 30-day pass respectively pass and a 30-day pass respectively pass and a 30-day pass respectively right so we need to determine the optimal you know passes that we should purchase if these are the days we want to travel so basically in this example we're given let's say these are the dates we want to travel and this is the costs for a pass so one thing you could do is on each day you get a one day pass right so you'll be two dollars here up all the way up to here so in total you paid 12 dollars right the other option is on this day you can get 30-day pass right for 15 and for fifteen 30-day pass right for 15 and for fifteen 30-day pass right for 15 and for fifteen dollars you'll be covered up to the end right and then the other option is you get let's say a seven day pass at day one and then that sets you good to day seven and then you buy two one day passes right so that'll be seven plus two which is 11 and that is actually the optimal one but you could also just buy a one day pass here and then do the seven days in between in either case 11 is the smallest amount so what will be your approach to solve this problem if you think about this one this is basically going to be a dynamic programming question right like because you have to explore different possibilities and you have to optimize for the minimum so what we'll try to come up with is you know what are the different parameters what is a recurrence relation right like what is our sub problems and then we'll try to see what we can do from there so basically if you look at this what are our variables right so for example given this input you need to know at each point like you know up to when is your last pass good until right because it might be that when we visit this day we already purchased a seven day pass let's say here and turns out that you know we don't need to do anything here right that's always Optimum if the last thing we purchased covers us so let me just move on right so we need to know when The Last of Us is good until right and if the last pass doesn't cover and we have three decisions to make right so either we take a one day pass a seven day pass or a 30 days pass right and we have to take basically the men of these three decisions and whatever is the most optimal that will be our the number of costs the minimum cost it takes to go from that day to the end if we don't already have a pass that's good for that day right and so if we do this there can be still repeating sub problems right because let's say you pay for a one day pass on each time at eight you still have a problem okay if I don't have a pass at eight what's the best I can do to get from 8 to 20 and then if you do the other option here which is to pay for a seven day pass the seven day pass will be good from one to seven but you'll still have another sub problem here which is the same one as last time right so we'll basically memorize whatever we decide here in a DP array and that will represent basically the time it takes for this index if we start here to get to the last day right which will be the main of these three decisions and one other thing I wanted to highlight here is note that the array is going to be sorted right so we're given here that this is an increasing order so we don't have to worry about you know sorting it ourselves or days being out of order so with that let's just go ahead and code the solution and then we will see hopefully how um things unfold so basically we'll do a recursive function right so let's write our recursive function which will basically be in Min cost tickets and we'll take in obviously the inputs which is the days and the costs if we'll take in what an index we're at right now right um what index we're starting at we'll take in this variable which we will need which tells us when is the last pass good up to right and we'll also taken our DPA array which will tell us what is the minimum way to travel from this index to the last day so that we avoid you know having to solve the same problem twice so first let's handle our base case right so the base case again is if our index is greater than equal to days uh length that means you know we've already been through everything and we're trying to go to the next one that means you know we're done so then we'll just return zero because it's you don't have to spend anything uh because you're already at the end so you don't have to spend anything to reach to the end right and so the next thing we will check is if our current if our day set index is less than or equal to our last password until that means if the last pass still covers the current day then we just skip it because it's always optimal to just use that and move on to the next day right so in this case we'll just recurse for the next Index right because our last pass is still good so we'll just go ahead and recurse and then next case is if we so now our last pass is not good right because we've already checked that here so now if we've already computed the minimum way to travel to the last day right if we start at this day that means DP at index would not be equal to zero right because initially we'll initialize everything into zero and you know we were guaranteed that the cost is at least going to be one right so there can't be a zero cost option so therefore DP at index P0 means we haven't computed it yet the cost and so if it's not zero we'll just return DP index means we've already computed it right and otherwise what we do is now we'll make the decision right so we'll take the minimum of these three decisions so we'll compute our main cost and then what we will do is we'll set our DP at index equal to this main cost and return the main cost right so the main cost now will be the minimum of these three decisions right so we'll say math dot min and then all three decisions right so let's just copy this one over here three times and change the variables right so all of them will try to go to the next day right but so the first option is if you pick the one day pass right so you'll have to pay the cost of taking a one-day pass which is cost at taking a one-day pass which is cost at taking a one-day pass which is cost at zero right that's the cause of picking that one day pass and then your last pass good until will just be days at Index right because we can only use this pass for today we can't use it for tomorrow so whatever the current day is the pass is only good for that day the next option is if you pick a seven day pass right so we'll say cost at one which is the price of a seven day pass and this time the last pass is good until days at index plus six right because it includes the current day so the current day will become the first day you use it and then you can use it for current date plus six and the same logic over here where we'll say it costs two for the 30 day pass and this time is good until days at index Plus 29 right because it's a 30 day pass including the current day it's current day plus 29. so whatever the minimum of these three options will be the minimum cost and that will store on our DP array so now you just have to go ahead and call this function so we say men posts days costs start at index zero our last pass is good until zero if you don't have one and then DP would just be new and of days dot length so whatever this today's array is we'll have a DP for your each position right and finally whatever we return will be our solution so this should do it let's go ahead and run it to see how this does all right let me just remove this scratch pad all right we can't take a man of three things at once so we will take them into the first one and do another Min over here all right accepted let's submit perfect 100 solution thanks so much for watching I'll see you in the next video cheers
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
472 |
hello guys welcome to deep codes in today's video we will discuss lead code question four to seven that says concatenated words so here we are given one idea of string words without duplicates and we need to detect all concrete or concatenated words so the definition of this concatenated word is any string that is comprised entirely of at least two shorter words in the given atom okay so uh if let's say this string gets uh gets dog catch so this string of is made up of three different words as you can see here cats dog and again catch so we can say that this is one concatenated word now if we talk about this word only cats then there is no sort of two words like cat and S or CA and TS in this input of words if there would be two words like ca and TS then we can say cats is also a concentrated word it must because it must have at least two shorter walls and uh and it should be compressed entirely you'll get a two or more shorter ones you got it so as you will take a look at here that cats and dogs is one example then dog get the dot gets dog is another example because this time this input has dog as well as gets as well as dog okay and another is uh yeah red cat dog cat see we also have a right and dog and cat is we also have so that's how we've found three concatenated word from this input got it now take a look at this test case we have cat dog so it is comprised of cat and dog so that is our answer okay so I hope you guys understood the question now uh following an intuition for this is the given example now for any given word let's say you are trying for what to get what we will do we will check either we have possibilities like uh C comma a comma team are these three different words or CA and T are if these two are defined words or C comma 80 is a defined word so these are different possibilities and if let's say we have any of the possibility match means H C A and T that would be another word in these like ca and T then we can also say that this cat is a concatenated one got it so that's how we will check by taking a substring of each word and we will check if that substring is present in this given words or not if it is present then we would uh check for another substring not the remaining part of this word so I hope you guys are deriving the intuition of how we will do this that by checking uh for each substring of different length of a given word got it let's say for this let's say if C is not a present here then we will try for CA there is CA is present in this no then we would try to see it if C8 is present in this see we won't check for this I mean so we would by checking we would remove the original word got it from uh the words we will remove that okay acid is present no so that's why we would rate it false the no or it is not possible to make this word by concatenation of two words so that's how we will do let me take one another example to let you show you better let me take dog catch and dog so let's say I tried uh by checking let's say initially D is present no then I took do is do present in this uh added node then I try dog is doj present yeah Doc is present okay I got one answer then here I tried four C is C present as a word no CA no c a t yes okay see it is present okay now I type for this s is present no D present no o s do you present no so here it is false okay then I again tried for dog let's say for dog then I tried four cats so it gets present here dog present here and the remaining dog present yes okay so that's how I will try to solve this question got it by taking different possible substrings at different uh indexes okay so uh So based on this you will have data that what we will do we would try to do a recursive function yeah similarly to a DFS uh call that we make so we will try to do a recursive function and also we would store all this in a unordered map for better tank complexity another map is publicity so our approach would be to use unordered map to store all this possible string it would be of string end and then we would Traverse we would make a DFS call uh for our each word starting from zero handle and we would try to form different possible substring if a substring is possible then I will check for next substring and then for the end and if you reach 10 and all the above substring are possible then we would return true else we would return false if we would return true then if at any point we got our answer is true then yeah we will stop and we would return we would add this to our answer simple so is now do you feel this question as a hard question I think you must not feel this is a hard question this is a simple question like if you would know DFS or recursion then it's easy for you to solve this because we are just doing that making trying to make different possible substring this is like a charge diagram very choice to include these as a substring or like this as a substrate so yeah that's all for the approach part uh now let's move on the recording part where we will see how we will code this function so guys now let us try to code our approach so let me first initialize my unordered map of string an inch let me name it as m format now let us Traverse 4 with all the string in this words item and we would simply add the frequency of those words in our map now again what we will do we would Traverse for these words again okay now before that let me also initialize answer variable Vector string of on sum foreign so that we won't count it as a substring yeah and now if the DFS call where we would pass the current word and the unordered map M and the index 0. and if this returns true then of people to answer Dot pushback and we will push the string s and I remember again to increment the frequency of the word and here we would return answer now let us try to code this function the Boolean function Bool DFS string as unordered map off string tint and let me name it as m and one index to store the index now if index equal to s dot size then we would return true see I would uh I would explain you why we I am directly returning true here but before that let me take one uh stamp string where we will store all the soft string from Andrew Travis from index up till as dot size what we would check if U of 10 so but before that we would push some of the correct the character the current character and so fine this time and if U of M is greater than zero that means we have that substring and it we will and we will call this DFS function again on the remaining string that is from uh I Plus 1. okay and for the I plus one that is remaining string we will again call this function and this returns true and this is also greater than zero then here only we would return true right so that means if we have reached the end of the header that means that uh this also the fs call would be also written true so if we Encore any of this condition then we will simply return true right because all the substring uh before this end of the item are the value substring yeah and in the end you return false if none of the condition is satisfied then we will return false now let me try to run this okay you sorry it's not you it's m and for unordered map okay what's the errors still unexpected okay that would be on comma here so yeah the test cases are passed now let me try to submit this okay yes so our code got accepted so I hope you guys understood the question the approach as well as the code for it not talking about the time complexity see here we are running this look for and times that n is the size of this words a vector that is the total number of words here and for each uh word in these words we are calling a DFS function so here let's see here uh the size of the total number of words is let's end and size of word is let's say m then to find all the possible substring of this values okay now uh so we if this word offers is the first size n then to pause hundred all the possible substring would what would be the time complexity there could be a time complexity of n Cube if you know the how we can if we know the complexity of generating a substring then that is NQ offers a word of a size of M so over our total time complexity would be n into n Cube correct and Total Space complexity would be n into m I guess yeah this is only the this only would be the same space complexity yes because uh for all the m n number of words we are showing it into our unordered map and then we are storing uh some substring in the temp of size M so this would be our space complexity so I hope you guys understood the intuition behind this question and also the approach so that's all for this video make sure you like this video subscribe to our Channel and also note one thing that I am sharing the job opportunities in the community section do check that out uh on a regular basis and also hit the notification Bell to get the notification whenever I share something so that you won't miss the miss something so that's all for this video uh make sure you subscribe the channel if you haven't and like this video thank
|
Concatenated Words
|
concatenated-words
|
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`.
A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.
**Example 1:**
**Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\]
**Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\]
**Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats ";
"dogcatsdog " can be concatenated by "dog ", "cats " and "dog ";
"ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ".
**Example 2:**
**Input:** words = \[ "cat ", "dog ", "catdog "\]
**Output:** \[ "catdog "\]
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 30`
* `words[i]` consists of only lowercase English letters.
* All the strings of `words` are **unique**.
* `1 <= sum(words[i].length) <= 105`
| null |
Array,String,Dynamic Programming,Depth-First Search,Trie
|
Hard
|
140
|
131 |
hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be solving the problem palindrome partitioning from the sd sheet but before we move on to the problem if you guys are new to our channel please do consider subscribing to our channel so the problem states that you'll be given a string s and your task is to partition s such that every substring of that partition is a palindrome so you need to return all the possible palindrome partitioning of any given string s now you know what is a palindrome string right a palindrome string is a string that reads the same backward as well as forward so if you take this example where s is given as a b so you can say that you can have two kind of partitions where you can have one of the partitions as a b while the other partition can be a and b so you'll get this string so you can see that the size of the string can at maximum b16 so that actually gives you an idea that you can write the brute force of generating all the partitions so let's take this uh string so if you take this string the possible answers can be you can decide to have a partition here then another partition here so if you decide to have these kind of partitions you will end up getting the string a b so this can be the first partition and the other partition can be you just decide that you are gonna have a partition over here and then over here and nothing else so this will give you a and b now suddenly you can also think of having the partition over here then another partition over here so this will give you a b and b now all of these sub strings are palindrome so you can have this partition as a comma b comma beats here is that all the substrings that are partitioning are palindrome in themselves other partition that you can try to do is you just put a single partition over here that will give you the string a and b so you can try out all the other partitions and you'll only get these four partitions as your possible answer so this is what the problem states so this is the first list of all the sub strings this is the second list of all the substrings this is the third list where this is the fourth list and your task is to return a list of all of these lists that are possible since an academy has sponsored this video let me tell you something about them now they have brought the subscription plan of enrolling for learning competitive programming now why should someone take the subscription plan first of all when you take up a subscription you get access to all the batches and courses that are running currently and also the ones that it's not a particular batch of course that you're paying for you're actually paying for all the content that is present on their platform also you can learn from your favorite teachers and be part of the courses and batches that are being taken by them they're also providing you with dedicated doubt sessions yes where you can ask your doubts in life classes you also have the option to interact with the teachers directly in the life class through messages emojis whatever you want to and yes there are different types of batches and courses starting and running at all times so if you are at a beginner intermediate or advanced level there are batches and courses running relevant to your need so these are the things that you will get if you take up the subscription as at an academy so there is an interview preparation batch starting on 24th february especially for intermediate level folks which will help you get ready for upcoming placements now this batch is being taken by deeper gore and ria bunsel you can see deeper gold was the icpc world finalist andrea bunsel is currently working at flipkart so yeah do check out the batch by clicking on the link that is given in the description and if you want any discount on the subscription you can use the coupon code take you forward to get that discount so how can you solve this problem obviously we have to write a brute force that does generate all the partitions and some common thing to observe over here is whenever we are doing a partition every substring has to be a palindrome and the partition can be anywhere so it's basically you have to write a function that has the same thing again and you know whenever you write a function that does the same thing again and again of partitioning strings that is when you start thinking of recursion so how will you think of recursion so what is your task what is your primary task the primary task is to partition okay so let's uh do it step by step so what if i ask you which is the first position where you will partition in order to get a sub string that is palindrome your answer to that will be you'll try partitioning over here yes so if you do a partition over here you will still be left out with a sub string a b but since you have partitioned here this string this substring is a palindrome so that's your first thinking where can i have the first partition that's over here now what if i ask you if i don't allow you to have a partition here then where can you have your second partition and the answer to that will be you can have your second partition over here right after a you can do a partition why because this double a is a palindromic substring so if you do that you'll be still left out with the string bb for which you have to do a partition so can you do a partition over here the answer to that will be no because if you do a partition over here this substring in itself is not a palindrome and what you require is whenever you do a partition the sub string should be palindrop so thereby you cannot do a partition here can you do a partition here obviously not why because aabb is not a palindromic substring so we cannot do a partition here so we can see whenever we started we could only do a partition over here and a partition over here so that is what we do we try to do a partition wherever it is possible so when we have done a partition here we are left out with this string so let's call a recursion for this string only that's abb so now if i ask you where can you do a partition in this abb your answer to that will be you probably can do a partition right over here yes right over here and that will give you something like this if you do a partition here this substring in itself is a palindromic substring so you'll be left out with a substring bb now what if i ask you what is the next index where you can do the partition can you do a partition over here can you do no because this substring then will not be a palindromic one can you do a partition over here again no because this entire substring will not be a palindrome so the only partition you can do will be over here and you do that and after that you tend to call the recursion for the remaining substring that is bb now my question to you is where can you do a partition here yes you can do it so if you try to do a partition there what you get is a right after that you do a partition here so this substring in itself is a palindromic substring after that you are left out with the substring b for that you again call a recursion remember now since you did a partition here my question to you is can you do a partition right here yes you can do that partition and if you do that what you will get is a e and since you did the partition at the end you will get b now this is a substring in itself now since you were able to do the partitions in such a way that at the end you put a partition at the end so that is where you stop but let's wait let's do the left part first where's the last partition that you did right over here and you're still left with this sub string so let's call a recursion for this substring now when you call a recursion for this substring it decides where to do the partition so can you do a partition here yes you can do that partition because if you decide to do that partition you will be again doing a partition at the end and that will make sure that this substring is a palindrome and since you are able to do a partition at the end that means this substring and this substring which is nothing but a comma b is a partition where every substring is a palindrome so this whenever you reach the end remember whenever you reach the end your recursion call is over so now it's time to get back so that's backtracking so make sure you get back and whenever you get back you can say that this recursion call is also over so you try to get back now this recursion call was left out because you always call the left recursions at first so this recursion call was left now whenever you call this recursion a partition was done at the end so whenever you do the partition at the end what does that signify that means you were able to partition in such a way that this a was the palindrome this a was a palindrome and this bb in itself was a palindrome so you basically get another list of substrings so another partition where all the substrings are palindrome so you can again store it in your list of sub strings so this recursion i can say is over so it's time to get back so i can say i was successfully able to do the partitions from here so my job is done so the recursion for this is now over so i get back so since i get back and i see that there are no possible other partitions apart from this because you cannot partition here because all these substrings will not be palindrome so this recursion is also over so you try to get back now since this left recursion call of partition is over we come out and check for the right so the right has a partition over here so it calls a recursion for this term so whenever you have this bb where do you want to partition at first the answer to that will be you'll try to partition here can you yes you can because if you do a partition you will have right here b and that's a palindrome and you'll still be left out with the substring b yes for which you'll call a recursion and the other partition that you can do is right here and if you do that you will get a and a b and the partition at the end but this recursion will not be called as of now you'll call this recursion now where can you partition if i ask you i'll try to partition here can you yes you can so let's do a partition there so if you try to partition it over there you will get it as this so again you're able to do a partition right at the end and if you're able to do a partition right at the end that means you're able to generate a partition that has all the substrings as palindrome so i can call these substrings as palindrome so this will be another answer of mine that's a b and b so i can store them in a list of strings so this recursion can be said as being over so once this is over you can try to get back now this cannot have any further partition so this recursion is also over so you get back now it's time to execute the right recursion so when you execute the right recursion you see that the last partition was done right at the end so whenever you do the partition right at the end that means you're able to generate a partition where every substring was a palindrome over here as a palindrome and bb is a palindrome so i can say that this can be a part of my answer so i simply take it down so this recursion is also over so we try to get back so now all recursion calls for this substring vb is over so we get back so ultimately i can see i was able to partition a bb in such a way that i got all the four partitions which could be my answer so this was the recursive tree that i did show you but now it's time to convert this into a pseudo code because if you don't convert that into a pseudo code you cannot write your code so basically what do we see at the first we have a string so we can say our recursive function for sure will have a string what next we are actually trying to partition it right from here and we try to partition here then we try to partition here so it's basically saying that for every string i'm starting at a given index so i can say this is zero this is one this is two this is third index so i'm starting from the zeroth index and what i'm trying to do is if i'm able to partition the zeroth index that was the case i was able to partition if i'm able to partition on the first index that was the case over here i was able to and so on i will see will i be able to partition all the index which means i'm actually looping yes i'm looping and checking if a partition is possible and if i was able to partition here i basically take the substring right from the 0th index till the 0th index that's a substring i take and i call the recursion for the string starting with the first index because now the string starts with the first index similarly if i'm doing a partition on the first index then i'll take the substring 0 to 1 very crucial stage because you're taking a that is meaning you're taking 0 to 1 so you take that substring and where will you call the recursion form you'll call the recursion from the second index because you're left out with the string bb so that's the second index where you call the next recursion from similarly you cannot do a second partition because if you partition here this is not a palindrome so make sure whenever you're trying to partition on the zeroth index please do check if zero to zero can be a palindrome if zero to one can be a palindrome similarly if you're trying to partition from zero to two that means 0 to 2 has to be a palindrome which is not the case so you'll not partition over here 0 to 3 has to be a palindrome again that's not the case so you don't partition so basically i can say that generalized version will be there will be a string there will be an index and there will be looping that will go on from index right till the end so when will you be able to partition assuming that i is 0 1 2 3 i can say if index till i substring is a palindrome then only i'll be able to partition if zero and zero was a pile and drop zero one was a palindrome if zero two was a palindrome then only i can call the next recursion and again try the similar way of looping so this is gonna be your pseudo code i'll show you the code and you'll start understanding it in a much better way but this is the generalized version and what is the base case whenever you reach the end so that means whenever you reach the index as n i can say whenever your index reaches n that means you're able to partition everyone and all these sub strings would have been stored somewhere and you can store them in your ultimate answer so once you see the code you will start getting a better version of this so if you look at the java code you have to return a list of strings which will be answer and you are given a string s so initially let's have a list of strings which will be our answer and let's have a list of strings because you know you are generating a string every time so at the end this is a list which will be generated so for generating this let's consider this path okay and we are going to start the recursion from the index 0 and the string s and we are carrying these two data structures which one of which will store this entire stuff and all the lists generated will be stored in this result one so s and index 0 is where we start so we can see that a function starting from index 0 and s has been called and you know the base case will always be whenever you have done the partition right whenever you have reached here which means you have reached the index n so when you partition it completely you can say that this list which is generated which was the path you can store this in your ultimate data structure that is the rest so we store it and we break out so this is a base case is very clear now what about the partition so you try to partition from index right like over here it was zero so you tried two partitions from zero one two and three like in this case it was two so you'll try to partition here and you'll write a partition here that is what has been done so we try to partition so that's why we start from index right and we go on till the end and what do we check if we can partition 0 we need to check if 0 and 0 is a palindrome so that is what we check if the string from index to i is palindrome or not so if that is a palindrome what do i do is i take the substring so basically i take this substring a and store it in our list which will be this ultimate list and i call the next substring right from index 2 so that is what i'm doing i'm just going to the next i plus one because if you have done the zero to zero so the next one will be from one so that is what i call and i pass on the string path and rest now please make sure you remove when you backtrack because just assume yes just assume that you have done a partition here so that will create this individual string into that list but when you go back this b has to go off from that list otherwise you'll not get a bb so please make sure you take that b out so that is what we have done it over here so this will be the entire for loop and you know how to write this as palindrome function it's a simple palindromic check function i'm not going to explain it simple start from the start and have a pointer at the end and basically keep on checking till they don't cross this is how you check the palin drop so this will be the entire recursive function that generates all the partition substrings as the list and that is gonna work and that is what we are gonna return so that was about the java code so let's talk about the c plus code so you have to return a vector of strings that is a list of strings and they're given a string s so initially what we do is we create a result vector which will be our answer and we also create a path now what is this path will be storing the individual list of substrings when you do the partition for every recursion and what is this rest the rest will be storing all these guys yes all these guys will be stored in a data structure rest so that is what uh res is all about so you know you have to start from the zeroth index that is what you have started and you have the string and you pass both the data structures so initially we all know that the base case will be when you have done the last partition right that will be the base case so we can say whenever our index reaches the s dot size that means you have done the partition so this entire stuff will be actually path right that will be a list of strings that is path so you insert that into your rest that's basically the ultimate list of strings so you insert that once you've done that you return so you've inserted this entire list or this entire list into your rest data structure so if that is not the case if that is not the last partition so what do you basically loop and how do you loop you know how to loop if you are at the zeroth index that means you have a probability of partitioning here and here so that is what you do by your for loop right you start from index and you start to a partition 0 1 2 3. now when can you partition you can only put a partition over here if this guy is a palindrome you can only put a partition here if this a is a parent drop so that is what we check if you're able to partition then the substring from index to i should be a palindrome and i've written a function to check that so we can easily check if that is palindrop if this 1a or if this double a is a palindrome what we do is we take that substring like if 0 means a 0 1 means a if that is palindrome so we're taking a right we are taking a right so we store that in our list which is the path so ultimately a will be there so that is what i'm doing i'm storing it and once you have done the partition at zero that means if you have done the partition here or if you have done the partition here then we start from the next index right that's why i call i plus one and we start the next index that is what we have done here the transition so that is what we do and call the next recursion so that it can start partitioning again but when this function call is over and we decide to come back for an example we had a partition here right and this recursion call is over and now we are coming back so you have to make sure that this b which was there in this path has to be taken out so we take this b out yes we take this b out from the path so that the next time the partition can be done and we can take the new bb if we had not taken this b then this list would have contained b since path is a reference variable so please make sure you do a pop back while you come back so that this b will be taken out so this will be the for loop which will make the partition and this will be the recursion call which will make sure that the next partitions are done ultimately will reach the base case and you'll get all the partition substrings which are palindrome so you know how to write this palindrome so i'm not explaining this so ultimately whenever this function call will be over you will get your answer rest which you can return so guys i hope you have understood the explanation as well as the code so just in case you did please make sure you like this video and if you are new to our channel don't forget to hit that subscribe button so with this i will be wrapping up this video let's meet in some other video where we will be solving the next problem from the sd sheet
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
63 |
Good Salary Channel Talk Etc Poverty Shrink Interview Questions Video Apps Sexual Exploitation Unique And Will Not Get subscribe The Channel Please subscribe this Video plz subscribe Channel Please subscribe and subscribe the Channel subscribe Video Subscribe Ca n't To Subscribe Online Reader Right Corner Notice Subscribe School Download The And subscribe and subscribe the Channel Download Only No and 105 Subscribe to the Channel Set up artist flat Shanti Bhushan and some gold ornaments Approach witch they can take care Record only solution to using difficulty subscribe our YouTube Channel and subscribe the Channel and subscribe And subscribe The Amazing subscribe to subscribe channel ok so what do you want two years disrespect of which is the i to relative pound inch to explain solution absolute to do subscribe my channel subscribe my god 2005 thing but subscribe we So still carrot avoid dispositions there number and five eight one man bill-2012 b1 subscribe my channel bill-2012 b1 subscribe my channel bill-2012 b1 subscribe my channel dynamic programming so initially avoid 05 2012 that your name Dinesh Singh Daku or gold plated this and dynamic programming what is the name of the first and use This come subscribe my channel subscribe like this and hear this yes if you cigarette disposition how many where is the thing but what can reach this position which way they can take to subscribe my channel the total number of - 1000 what is the first Of All They Can Go In WWE Election Results And Total Number Of Parts Are Pretty Much The Position Want To See The - Position Want To See The - Position Want To See The - WWE Subscribe Download Video Channel Subscribe To Those Backwaters And You Subscribe Now Square Minus One Now Scorpio Total Number Of The Robot Tours In the same position from deposits of the pimple - festival and nathuser get rid of cancer and subscribe - first day first show hai to how many they is how many panch karo vatuk pimple - - - select - 151 - 151 - 151 - 1the is only one copy of the first roll Subscribe To 200 But Remove Distinguished End Left From This Zoom Developers Do n't Push It Hard Festival 93405 The Robot Subscribe Now Problem Everything Should Subscribe To This Feed Images Of Physical Verification Option Select Total Number Of Butts Can Take To Reach This Position School 2030 Little Butt It's not the only thing that to from the - - - way - - - - way - - - - way - - - - - subscribe and Share and subscribe the to mixi computers disposition friend na decoration What is the total number of passes robot take oath in the coming from the Robot Don't Forget to Subscribe Hair Tips Reduce Hair Well To Them Classification Not Less From Difficulties Sudhir And Nurses Vikram Thakur No Matter What Is This From His Position To Be Free From All Directions From One Plus One Class 10th Class 12th Exam From Shifting Base in 2009 to That's the Forest Sale of My Technical Grade Is Having Author Say Tomorrow Swift Trailers of Pilgrims Have Enough of Sacred to Know Weather on What Can Start from Difficulties Because You Already Have Enough for Justice Returns at Record Lows Not Viable Five Is Notification What Do You Want To English Alive Service Dynamic Programming Head Office Sexual Dana Seo Ra Dana Subscribe To Hai Na David Vriksha Definition Adhavwali Kind But Every 1000 Position subscribe to the Page if you Tube y51l video0 And subscribe The Road Number from google.co.in and tell a visitor to check that is the first taste Rupadhari 9990 Wale Liquid Liner by pressing the subscribe button subscribe this one UP That And Seeing Things Dear One Two For Plotting The Post Call Amazon President Subscribe Sirvi Seervi A person in this is minus one Earth ko lamba hai to domesticated boat or any post after lot operator rundh program hai to intezaar he guys want to oil fan of worry giridih.nic.in Copied life in the giridih.nic.in Copied life in the giridih.nic.in Copied life in the pointers Pimples Him Questions Want to Z Tak Aap Cigarette Se Z F Ko Z Plus To Difficult To Withdraw All Shades Of Madhya Pradesh Assam Bihar Worry Not So Effin Middle-aged Man Mriga Do Not Have Worry Not So Effin Middle-aged Man Mriga Do Not Have Worry Not So Effin Middle-aged Man Mriga Do Not Have Any Questions Page No. 5 From IT - - - - - 1m Ki And definition of worry by report I was forced Vikram Thakur rise in 1995 but I got mosque position Sudhir and Indian return last subscribe my channel [ my channel [ my channel subscribe 0 from now on cigarette 0 - from now on cigarette 0 - from now on cigarette 0 - and Randhir and I which ones the forest department and Lawyers Submitted for All Hair Tips to Subscribe Stop This a Time of Dissolution of the $200 City Use Order of Fame * ABS $200 City Use Order of Fame * ABS $200 City Use Order of Fame * ABS Complications Also an Order of Payment Subscribe Safed To and Subscribe subscribe and subscribe the Channel Please subscribe thanks for watching this YouTube Channel Subscribe to
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
1,361 |
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number 37 of the playlist of graphs, okay my playlist of graphs and concept and questions you can try if you want to understand the graph from the very basic medium level. The question is lead code number is 1361 but it is a very easy question, we have already prepared it with another approach in the playlist of binary tree. Okay, so the name of the question is Valid Binary Tree. Notes. Today we will solve it using DSU, from disjoint to union to matter. Asked this question, there is no need to explain the question again. I hope you must have already understood the question. Today in the morning I had posted a video from the first approach, in that I explained the question well but in short, if I tell it then left. Child and right child have been given and number of notes has been given. You just have to tell whether you can create a valid binary tree or not. If this is ok, then look at the simple approach. I have created a playlist of the tree using simple binary properties. In video number 30, it has been uploaded today itself, you can watch it. First, now we understand from approach two i.e. from DSU, what is the pre-requisite i.e. from DSU, what is the pre-requisite i.e. from DSU, what is the pre-requisite that you should come to DSU. Okay, so DSU is a very simple topic, my play concept. In the playlist having graph concept, you will find DSU is fine. From there you can read DSU. Basically it has only two functions, find, what we do with it, we can find the parent of any node and union of any two. You can union the nodes, okay, these are the two main things, okay, so let's understand today's question, let's see how it will be solved with DSU, look at this example and let's build into why DSU will help us here, okay do you understand? How will it come to anyone's mind that this can be made from DSU? If you remember the question then it has been said in the question that now you have been given A notes in the beginning, okay that means zero, if n is 4 then 0 1. 2 3 Four notes have been given to you but till now you have not been told who is whose parent and who is whose child, who is whose left child and whose right child, it is okay and you do not even know who is the exact root, it is okay in the beginning, then Gradually, if you keep reading the left child and right child, then you will come to know that the left child of zero is one, the right child is two and so on, okay, 0 is 3, so here like the left child of zero and the right child of zero. Child is two, so now as you read this, you got the idea that zero, one and two should be connected, meaning one which is one, zero should be reported because zero is the parent, it is okay, zero is also there, zero should be reported because T. Zero which is the parent of two and we got to know from here okay and like then look at this also here T which is the parent of th so see which is which means it will report to two and ultimately two which is and report to zero. If we look closely, all of them came in one component. Do you remember how many components were there in the beginning? In the beginning, there were four components, all were different. The components were total, four, all were different, but gradually what happened was that as we Read the left side and right side, we came to know the relation, then in the last we saw that now only one component is left, look, all are connected to the other one is fine and look here, it is reporting 32, it is reporting 20. You can optimize this and ask it to report directly to Zero. Do you remember, we used to do path compression or optimization in DSU, this is the same thing actually, it is fine, it does not matter, but the main important issue. This was exactly the story of DSU. Right, it used to be like this in DSU, all the components were separate in the beginning, then as it became known who was related to whom, like here, left side, right side, left side. On the right side we started getting to know, we will keep on connecting, on the right, why did we hit that this is a question of DSU, it can be solved easily from DSU, so let's see how we will solve it from DS, let's try to solve it from DS, look in the beginning. We know how many components will be there in total, there will be four because there will be the same number of components as there are notes, because at the beginning no one is connected, 0 and 2 3 are fine, and this is an obvious thing, everyone is alone in their own locality right now, so everyone is on their own. The owners are zero's parent zero one's parent one two's parent two three's parent three because right now I don't know who is whose parent okay and I take the parent vector here 01 2 3 Now row's parent zero one's parent one two The parent of two is the parent of three. This is my parent vector. Okay, now let's move on. Now the first thing I did was I came to this, I looked at what is the parent of this. Look, the parent is this index which is zero index, the parent of this is zero. Who is the left child? Left child is one. First let's look at the left child. Okay, after that we will come to the right child. Right child is two. So first of all, what does it mean that the one who is one is the child and the zero who is the parent. So first of all I am one. If I go to a parent, first of all I will ask him who is his parent, that is, I will call Find One. Remember what used to happen in DSU, to find out someone's parent, they used to call Find One, then how will Find One know who the parent of one is? One's parent is One itself, meaning what happened here is that Find LC became equal to LC, what does it mean that no parent has been assigned to it yet. You are seeing that One's parent is One itself, meaning right now it has no parent. If the parent is not assigned, then what will I do, will I assign it to one? Okay, who is your parent now? Is it zero? Okay, if I have assigned it, zero? Is it zero? Okay, if I have assigned it, then what will happen, the parent of one has become zero. It is clear till now and if By the way, if we assume that one is already assigned some other parent, then I am saying that if we do find one, then some other value would have been assigned, one does not come, okay, not equal to two, what does it mean, already one or the other parent is assigned. What does it mean that one is getting one parent right now but zero but before this also some other parent was assigned means there is something wrong here right that each node should have only one parent in binary so I am false there. I will return right. Okay, so what I said here is that first of all, what will I do? The LC is my child, right? I will take out its parent. I will take out the parent of the child. Okay, so here I took out the parent of the LC. I came to know that He has no parent, he is himself, his parent means he has not been assigned yet, so okay, I have assigned him that you will report to Zero is your parent, ok, that's it, now let's come to RC Right Child. If we find out the parent of this also then when I call 'Find 2', will when I call 'Find 2', will when I call 'Find 2', will 2 come? Look, 2 has arrived, meaning 2 has no parent yet, it is not assigned yet, it would have been already assigned, then it would have gone wrong, it would have returned false, but now. There is no one assigned to 2 yet, so 2 is also assigned that your parent is zero, okay, it is clear till here and update is also done here, the parent of 2 has also become zero, okay, this is also done but Pay attention to one thing, remember the first component, when I did not connect it, the value of the component was four, then when one was connected to zero, it was connected, that is, I did the union of zero and one, then the component became three. Look, one, two. And it becomes three components, right, then as soon as two is connected to zero, look, I have subtracted one more component, I have become two components, not just two components, great, now let's move ahead, now coming to this, look at this, its parent is one. If left side is my right side my is -1 then nothing has to be done then leave is -1 then nothing has to be done then leave is -1 then nothing has to be done then leave it ok means there is no child at all. Coming to this parent is two. Left child is three. If right child is -1 then three. If right child is -1 then three. If right child is -1 then leave it if it is -1. We don't have to process it, leave it if it is -1. We don't have to process it, leave it if it is -1. We don't have to process it, we are fine, so the left child is 3, so let's find 3, what will be the value of 3, only 3 will come, see what it means, no parent has been assigned yet, so the current parent is If 3 is assigned to the same then who is the parent of 3 right now 2 is okay so the parent of 3 is assigned to 2 meaning what did I do parent of 3 if I did it then what will happen here look I did 2 okay this father You can also optimize that what is three of the parent, what is the parent of two, if the parent of two is zero, then we will directly make the parent of three zero, this is optimization, it is not necessary, but look, as soon as I did the union of two, it is fine, so my Component, I have subtracted one more. Okay, now let's come to this. Let's come to this. Look here, there are all the minuses and so there is no need to process anything. Parent is Thr. Left child is -1. Right cy is also mine, so there is Thr. Left child is -1. Right cy is also mine, so there is Thr. Left child is -1. Right cy is also mine, so there is no need to process. We have moved ahead, all the edges are out of bounds, we have processed all the notes, so we just have to check that see what is the size of the component is left one, that means there is only one component and Remember, even in a binary tree, there was only one component. Only one component was different and it was not cut. That is, this is our valid binary tree. This one, the input was correct and remember when we are assigning. If you were someone's parent, we were also checking whether you already have any other parent assigned to you. It is important to check that thing because from there we are able to check the cycle. If someone else has already been assigned a parent, then It is also possible to know from this that you do not have multiple parents, but there is no such case somewhere, let us assume that this is a node This is wrong, okay, any note cannot have multiple parents, so we are checking that too, that is why all our things are being checked by DSU, it is okay, now let us look at an invalid case, it is very important from there. More things will be known, now look here, let us see that this is an invalid case, it is not a binary tree, okay, so let's see how we can catch it with the help of DSU, we will do the same thing again, we have two notes in the beginning, zero and one. The parent is itself, its parent is also itself and I have assigned the parent vector which is also 0 and the parent of zero is the parent of zero one is also zero. How many components are there? Right now in the starting we have equal to two components, two different. -There are different components, one is this and one is two different. -There are different components, one is this and one is two different. -There are different components, one is this and one is this, okay, let's start first, let's process it. The first one is given index number, zero is the parent, zero is the left child. Look, one is the right child, if -1 is -1, then leave it. If we zero is the left child. Look, one is the right child, if -1 is -1, then leave it. If we zero is the left child. Look, one is the right child, if -1 is -1, then leave it. If we look at the left child, then the parent is zero, the left child is one, okay, what does it mean? First of all, I ask the left child that if you already have a parent, then what is the left child, mine is one, its parent is sorry here. What will happen if the parent of one is one, then find one, what will come, only one will come, meaning it has not yet been assigned a parent, so let's assign it to the current parent, who is its parent right now, if it is zero, then I have assigned zero as the parent of one. Now this is your boss, as soon as you assign, what is the meaning of assigning? I have unionized both of them in one component, the component will not decrease, it has become one component, now it is ok and here also I edit the parent of one, now it is zero. It is done, okay, now look, pay attention, it has been processed, now look at this, who is the parent here, the left child is zero, the right child is my, so leave it, okay, pay attention here, see, the parent is one, the left side is zero. So what I used to do every time was to ask the left child, do you have any child assigned, what parent, sorry, parent assigned, what then find LC, what will happen, LC is my zero, then find zero, what has come, see, only zero will come, so here. I would feel that okay, it does n't have a parent assigned yet, then I feel that there is something wrong, no, I will not assign a parent to it, otherwise by assigning a parent, I will make zero's parent here to one, this will create a mess. I am fine, it means that only this Right, I told you that if find of LC or RC is any child, if it is not equal to LC, that means the parent is already assigned, then in that case we would return false if it is equal to LC. So it means there is no parent assigned, so the parent could have been assigned, okay, and here we have done it, but we have messed it up, look, the cycle has been created, okay, so what does it mean that we have to see one more thing, pay attention to one thing. Find out who is the parent of this one and see who is the parent of one. Brother, let's see that the parent of one is zero. Here, the parent of one is zero and now my child is also zero, so is my parent the parent of that one? Now I have taken out the parent of the parent, was it this parent or not? So who has it become equal to? Zero and zero is my child. See, it has become equal to the child. Can the parent be equal to the child? No, otherwise it is like this whenever the case. If it comes, I will return false here. A simple eight is fine and even if you assign blind, don't assume that you do not check this. If you did not check its parent, then what would you have done. Blind would have made it its parent and As soon as you do the union, what do you do, the component which is yours here, sorry, this is the component, if you subtract it again, then the component becomes zero, the mistake would have been caught here only, but I am saying that this is the first mistake. You can catch who is the parent and see who is the parent. Once I have seen the parent of the parent, I have seen the child himself, this is my child who is invalid, the parent of the parent may be a child, then at the same time you return false. You can do it, okay, so whenever you are doing union, what are you sending, you are sending one parent and one child, it is C, so first of all what I said, first check that find C means C. Is the parent already assigned or not equal to C? If it is not equal to see, what does it mean? Is it already assigned a parent? Then I will return false. Firstly, this is checked. Secondly, one more thing you should have done is to find the parent. If it turns out to be equal to C, it means that the parent of the parent itself turns out to be a child. It is not possible, it is an invalid case, in this case also you have to return false. If both of these are not true, it is not an invalid case, then what was to be done was simple. That update the parent vector Okay, what is the parent of Union is done ok if t if union is not done then if union is done then y will return true if union is not done then return false from here ok this is my union I have written it is simple and find is very simple find you already Do you know what happens in Find? What happens in Find is that if you find the parent of the node of any component, then you simply find it like this, if the parent of If not found, then remember what they used to do path compression, brother, assign it to the parent of Well, you should have known what is DSU, rest if you can solve it easily, then almost we have also coded it, its ok so it has become quite simple, let's code quickly and finish it, let's code the approach of DSU. Okay, I told you that for DSU we have to take a vector of int parent vector and what I have done this time is that I have also taken a variable named components. Okay and how many components are there in the starting n is the total n components. And let's resize the paint dot. Okay, what is there in the beginning, everyone is the parent of each other. Aa = parent of each other. Aa = parent of each other. Aa = 0 aa lesson a aa ps Okay, so what is int node mine? What is int left child? What is my left child? What is the right child of I in? Okay, now look, first of all, do this that LC which is not equal to minus and should be right and end, if it is not equal to minus then okay, let's call union. Who is brother? Parent is the parent. This node of mine i.e. I node and left This node of mine i.e. I node and left This node of mine i.e. I node and left child is its LC. Okay, if the union could not be done, that means E II returns false, okay then I will return false that something must be invalid, only then. False comes from there similarly on the right side also if not equal to mine then it is okay let's try to do union, whose union is whose, root which is my node is parent and right child is child, if false comes from here also then I will do return false, okay, it is simple till now and lastly what we have to check is the value must be equal to one, right that when we were unioning the components, they were subtracting then the value should be one, only one component. It should be because binary tree is called only one valid binary tree, so till now it is clear, now what we have to do is to write simple union function because I am calling union here, boolean union, what was sending int parent. And I was sending int child right simple so first of all I take out the parent of the child if find is not equal to see then return false what does it mean that it already had a parent assigned to it and if If it is not so, then also check whether the parent of the parent is the child, what does it mean that the cycle will happen for sure, even then I have to return false, I had explained it to you in the test case of invalid, okay these two if not. Then it means we are saved, then what will be the parent of child? I have assigned it to P and the component which is mine, I have made it minus V. Okay and in the last I have returned true because we have successfully done the union. Okay and we have used the find function. If used then find function is very simple, find int of What did you do to do path compression? You also assigned it to the parent of We have done this, parents also have to be informed, in starting right, everyone has a parent and themselves, the parent comes and submits the right, it should be accepted and here we have solved it from DSU also, if there is any doubt. Raise in the comment section I will try to help you out see you in the next video thank you
|
Validate Binary Tree Nodes
|
tiling-a-rectangle-with-the-fewest-squares
|
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1`
|
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
|
Dynamic Programming,Backtracking
|
Hard
| null |
663 |
Ajay Ko That Welcome back friends today they are going to solve liquid problem 864 sequential partition this problem Oscar Amazon India first interview sass you can see this year will also discuss about this problem and solution so if you have already subscribe To My Channel Please subscribe To My Channel Nav My Channel Health People Were Preparing for Code in Java Interview Sophia Preparing for Job Interview and Code Interview Please Subscribe My Channel It's Not Good Videos That Will Help You in Your Job Preparation So Let's Go Through the Description Please Go to Retrieve the Notifications Possible To Partition On The Tree Two Trees Which Have The Equation Of Lemon Juice After Removing Executive 181 The National Game Of The Tree Not Value Is The Range Of - Game Of The Tree Not Value Is The Range Of - Game Of The Tree Not Value Is The Range Of - 1020 Ki A Ki And Drive Visleson Equal To Any Relation Equal To Hot 100 Number Notes Right End You can also get the tree is not channel effective should give one so common morning everyone has one example so they can take the example clearly and which can discuss how to solve this problem solve first Louis understand what the problem solve Fateh Singh is it is Like this three like you can find the total of this tree nod32 800 total also third year the writer five plus 1015 plus0 227 per and where saying that can do equal partition specific divide 32nd request 1580 is there any subject with saffron add till we for you Subscribe 0 Total Luton subscribe and Share and subscribe the Light is Video Total Subscribe Thank You Have Equal to 100 Waste Subscribe Like Share and Subscribe Total Sum of the Difficult Total Sum of the True You will calculate will have function which will give us total 2030 And approved the total days will call function which will give us loot like and right side total for each of the notes of the street light so basically for example if you in every do save call date will be late from right side grandma from home to school Will Reach Here And This Will Give Total To The Note 3 Light Ko Like This Is He Total To And Desh Note 3 Will Give Verdict Has Totally Free Basically Every Month Will Get Left And Right Side And Also Know No Veer Is The Total Data Have Totally Failed To Turn It Will Give Me To The Question Is The Total This Key And Events S What Is My Toe Turn On The Right Side Acid 123 One Will Get Total Ten Plus Two Plus Feminine 115 Risk Hai 300 Get Haq Total Of Three Does It Is Equal To Like Power Total Subdivided Into Which Request 215 Right Clear So In That Case Whenever Hui Greater 1503 Related This Lineage Of The Wind Sub Scalp Later This Point The Time Pilot E Think It Will Return 15th Previous Ten Plus Two Subscribe Where going to return to basically partition a history subscribe to that solitaire kallu's dealer code is vitamin E is to common s you can see hui created for it's like and to variable from and partition flight to variable sardar and hui hai that dishonor is given to the Group Has Given To Has So Far Viewers Checking Fruits Will Not Return File Atharva Veda Calculate The Total Rich Person Total And Will Do You Will Go On To The Left For Example For Every Heart Will Go To The Left Side And They Calculate The Total Difficult To Find Someone Calling You Later This Is The Function Where Passing Out Parade Route Weekly Lottery Subscribe Like And Subscribe Andar Take His Language And Will Call You In Graduate Mishri Moti Saunf Naagin Three Use This Same Ways Sonalika Explains Beautification And Function Will Call In the left side and inside right side students or teachers and parents also train it will call in the left side inside right side outside and power base condition is that when the reached into lagna call on the left side and right side share it Will Get Null It Will Get Nursery School Returns 0867 Like And Share Visit Call On To Left And Right Of Two Cities Null Share It Is Null Carefully Tool Returns 0tweet Will Return 0292 Will Return 20 Gyan Hai Journal Of Child Rights Of Life But Will Return Many Share Twitter Pear To Sharp Return Purchase Channel Totally 3 And Train Will Return 50125 And Distance Will Return 10225 Acidity Or Dash Loot Ko On The Way Don't Like It Generate Solid Can Have Elevated 208 You Can See What Year Subscription So This Is Best Condition For Receipt Function Hai To Left And Right Sum Hui Get And Edited Time Jisko Devgan Adesh Side Vinod 800 Wicket Loop Plus Right Plus Root Value Types Of S You Can See Nifty 0.20 Types Of S You Can See Nifty 0.20 Types Of S You Can See Nifty 0.20 12232 Nifty 0.20 Rural Youth President 12232 Nifty 0.20 Rural Youth President 12232 Nifty 0.20 Rural Youth President Relief Is To Right Stree Through 1210 16 To Written 1580 Ten Plus Two Plus Greece 567 Doing Clear And Wherever E Find And Reason Sea Equal Two And Total Sunday Posted By Two Is Just Partition Flight Is Equal Two Through Hair Tips And You Can See Partition Flag This Outside The Earth And Water And Viewers Return And Partition After Burning In This Form Solid Friends Equal Partition Tree Equal Partition Three Does It Is Equal To Total Form Divided By Two In That Case Partition Flight Visited To Truth And You Are Going To Returns The Partition Flag And Interact And Indra Recursive Function Key Additional You Function Returns The Current Samridhi Cement So This Is Gold Channel Is Prostate Power Solution Is Subscription Doctor Find Some On Receiptly Belt So Latest One Se Example That Will Discuss The Same Day Subscribe Is So Aam S U Can See Hui Quattro Hair Sorry Arise Portion Is That System of Solid State Has No Like What is the Left and Right Some Start Can See Lift Two Entry for This Two Entry No Doubt Welcome Two and Three Do It Richest 30 Two Plus Riot Victims Types of Victims Pain and Very Difficult ₹50 Divide Life But Total Very Difficult ₹50 Divide Life But Total Very Difficult ₹50 Divide Life But Total Time Thirty So Right Side Vikram 15mins You Can Divide 3215 1760 E A Partition David Williams Roos Vitap Drum Website Work So Let's Take Another Example Where Water And Partition In This Way You Can See Plus 2 End Subscribe Shyam You Can Destroy Duty Wali Basically Choice You Can See You Yaar Getting From Share Development Acid War Is Right There And Relax Like This 90210 Reservation Equal District In The This Front Subscribe Now To You Want To Change The History Of The Total Welcomes It's A Rough Latest Converted Into Dubitable Decide What We Can Do Subscribe 606 Is So 2615 Can Actually It Means Look So Tan 06 NSS Two Three Four Say Left Just Special Two Here's An Airplane Mode Will Look Like This Right 3406 Plus Points 3132 Plus 434 Right Butt Still They Can Not Equal Distributors 172nd Can Not Have 0 White Vinegar Stand Plus 116 Plus 2 And Should Not Welcome 17th Nov 512 Equal Industry Ki Dainik Hui Removed This To-Do List Vikram Ki Dainik Hui Removed This To-Do List Vikram Ki Dainik Hui Removed This To-Do List Vikram 3837 Done Yes 210 Vanvas The Original Give Entry Day To You Have been given right to recall its truth table vikas gift s30 divided over enemy victim's pain solve even reply the two three inside right side inserted of left sauce fielder slant cap liquid dutiable typing kar sanao 319 5.1 plus 1025 plus 530 and describe 5.1 plus 1025 plus 530 and describe 5.1 plus 1025 plus 530 and describe school 350 plus two Plus three letters check 192 also written s truth that maybe you can see me yes to love puji this 232 know it is not be reduced to 100 years now you can be reduced to 100 500 109 vitthala ki work phone hai mein aa hai So Let's Go Ahead And Submit Solution A 116 Fashion Gold Accepted By Link Mode Switch Off Baroda System But I Don't Like It Means Remove This Ayush Vibhag And Fennel Flat Se Resubmitted Name Sunavai Performances 98 Per Cent Posters Banners Pretty Good 200 Districts Where You Can solve the quality partition in problem asam amazon so will right for you have written and this recursive function find some where trying to find out if oo can find out some flowers which is video original number to you can find out any subject continues its time For Example Share The Ten Plus To Subscribe And Original Committee 3424 Distributed Sudharti Tha Uzi Cancel Problem If You Have Been Told In The Area Play List Election Speech 198 And Harold Different Variety Of Problems Loot And Arms By Big Tech Companies Like Apple Amazon Google Facebook Microsoft Think Tight Defense Like Dynamic Programming Binary Search Address List First Real Life History Of Meghvar Private Tuition To Us Data Structures Related Problems Sardar Uchch Should Solve And Explain In Details With Example Solid Be To Understand And To You And You Know How To Solve This Kind of Problems Including Interview Sal List Claim Interview Playlist Status of Water for Interview Questions for You Not Explain How to Answer Thm So Common Cricket Fever J2ME Development Preparing for Interview and Learn Java in This Channel Will Have Not Good Material for U So IF U Like this video please hit like and subscribe your subscription is really important for us big boss valley civilization video can restore more people to work preparing for jawan will see the great help and by watching the videos please subscribe The Channel and thanks for watching the video
|
Equal Tree Partition
|
equal-tree-partition
|
Given the `root` of a binary tree, return `true` _if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree_.
**Example 1:**
**Input:** root = \[5,10,10,null,null,2,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,10,null,null,2,20\]
**Output:** false
**Explanation:** You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
520 |
hi guys welcome to algorithms made easy today we will go through the day one problem from the oversleed coding challenge detect capital please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a word you need to judge whether the usage of capitals in it is right or not we define the usage of capitals in a word to be right when one of the following cases hold all the letters are capital like in usa or all the letters in the word lead code are not capitals or only the first letter in the word google is capital in all other cases we define that this word doesn't use the capital in right way for the example 1 and 2 given we can see that usa is all caps and so we return true while the word flag does not satisfy the conditions so we must return false so as the question states there can be following three cases all the characters in the word are uppercase all the characters in the word are lowercase or it's a camel case where only the first character is uppercase and all the others are lowercase we can easily convert these three cases into conditional statements if we know the count of upper case characters and the length of word using this the algorithm will look as follows we initialize a count variable to store the count of all the uppercase characters and look through each character in the word and update the count once we have the count we can apply the three cases if the count of uppercase letter is equal to the length of word or if the count is zero we return true as it confirms that the word contains all uppercase or lowercase characters if it is neither of these two we return if the first letter in the word is uppercase and the count of uppercase letter is also one which would mean only the first letter is uppercase here is the actual code snippet for the method rather than writing the loop we can use the regular expression that will internally check the characters this will reduce the code to a one-liner this will reduce the code to a one-liner this will reduce the code to a one-liner code for all the three cases the regular expression can be written as follows we can combine these three into one single pattern that will look like this now that we know the regex we just need to return if the word matches the regex the time complexity for both the approaches is o n while the space complexity is o of one here's the actual code snippet for this method you can also check out the link to all the codes in the description below thanks for watching the video please like share and subscribe to the channel also let me know in the comments what you think about the video
|
Detect Capital
|
detect-capital
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
String
|
Easy
|
2235
|
448 |
arrays are a fantastic data structure not only are they easy to visualize and understand but they also give you two pieces of information the value and the index of that value sometimes these indices can help you to write an efficient solution to a problem i am talking about the problem find the disappearing numbers in an array on lead code well i have kind of given you a hint now so if you would like to try the problem on your own feel free otherwise stay tuned with me a little longer and i will show you step by step how you can approach this problem hello friends welcome back to my channel a place where we explore the life of technology and make programming fun and easy to learn first i will explain you the problem statement and we will see some sample test cases next we will approach the problem in the most straightforward way and see what problems you may face going forward we will try to optimize this solution and eventually we will also do a dry run of the code so that you understand all of this and it stays in your mind forever so without further ado let's get started first let us try to make sure that we are understanding the problem statement correctly you are given an array of size n where elements are in the range of 1 to n that means that if the size of the array is 10 then that array could have elements from 1 to 10 if your error size is 20 then the elements could be in the range of 1 to 20 and what do you have to find the integers that do not appear so let us understand this with a sample test case in a test case number one we are given with this array and the size of this array is 8. so according to the problem this means that this array could have elements from 1 to 8 right and you need to find the integers that do not appear in this array so you can see that one appears in the array two appears three appears you can find a four you cannot find a five then you cannot find a six you can find a seven and you can find the 8 correct so that means 5 and 6 are the disappearing numbers and hence this will be your answer in the first test case similarly let us look at our test case number 2. what is the size of the array is 2 that means this array should have elements from 1 to 2 right now what are the disappearing numbers you can start checking 1 and 2. you find a 1 but you cannot find a 2 right and hence 2 is the disappearing number so in test case number 2 this will be your answer now if this problem statement is clear to you feel free to try it out on your own otherwise let us see how we can approach this problem step by step okay so let us say this is a sample array in front of you and you have to find the disappearing numbers what is the most straightforward approach that you can think of you can start with finding the size of this array right the size of this array is 8. so this means that this array will have elements from 1 to 8 right so one way you can approach this problem is you can start finding each integer you can start to iterate towards the array and see okay i can find a one next you can start to iterate to the array again and okay you found a two similarly you will iterate and then you will find a three then you will find a four and then you will iterate to the entire array and you do not see a 5 right that means 5 is missing so you can write down 5 in your output set correct similarly you will iterate for each integer up to 8 and you will keep on scanning the array correct and ultimately you will find that 5 and 6 are missing from the array so these are the disappearing elements and this will be your answer now this solution works and it will give you a correct answer every time this is known as the brute force approach because you are just verifying that hey can i even find a solution to the problem yes you can find a solution but there is some problem the problem is that if your array is very huge let's say you have ten thousand elements then you will be iterating through the array ten thousand times just to check hey do i have this integer and hence this is not a time efficient solution let us see what we can do about it okay so you have the sample array in front of you right and you want to find an efficient solution to the problem when trying to find efficient solutions to problem the first rule of thumb should be that you gather all the information that you have you might as well say that okay the only information i have is this array right but wait in this array you have one more information and that is the indices of all of these elements right since you are given a condition that the elements of this array lie in the range of 1 to n right where n is the size of the array so if your array size is 8 then the maximum element present in this array could be 8 right and this gives you a certain advantage since the range of these values is defined you can refer to these integers as the indices of the array also what i mean by that is this value 8 could represent the 8th element in the array or what you can say is this could also represent the index number 7. similarly the value one could represent index number zero right because an array is zero based indexing and you can take help of this extra information to manipulate your array so in this array what you need to do you need to find the missing numbers right so one way to approach this problem could be that you start marking out what positions are occupied so when you look at the first element that is 4 you can also look at the position 4 is the index 3 in the array right because an array is 0 based indexing so when you look at this index 3 you see an element 7 right so what you can do is you can just mark it to mark this element i will make it negative that means that i have visited this element but what is this telling you let us iterate through the array and see what we come up with the next element i see is 3 now 3 means the third position in the array or index number 2 so i land at this position i see the element 2 over here this is still positive right so i can again mark it and to mark it i will just make it negative right go ahead now i see element number 2 so 2 could mean the second position of the array or index 1. i see this element 3 over here again right and this 3 is also positive that means we have not visited it i will just mark it so up till now what you can see is that we have visited these three elements in the array let us keep moving ahead and see what we get i see the next element 7 that is position number 6 in the array and once again i will mark next i see the element 8 that is position number 7 and i will also mark it next i see 2 again so 2 means the second position in the array or index number one right what do you see over here you see that this element is already marked right so don't do anything about it move ahead you see element number three that means position number three or index two this element is also marked right so don't do anything about it move ahead one step more uv element one that means the first position in the array or index zero so now you will mark this 4 so i make it negative so what just happened you iterated through the entire array right and you marked every position that the integer was present in the range 1 to n look at your array now and look at these indices that have not been marked these are 4 and 5 that means you couldn't find these two indices and since an array is zero based index that means that you were unable to find five and six in the array right because if five and six were present you would have landed at these two positions and they would also be marked negative right so this way by iterating through the array and marking every number at the index you can arrive at the solution let us now quickly do a dry run to see how we can implement this solution on the left side of your screen you have the actual code to implement the solution and on the right i have this sample array that is passed in as an input parameter to the function oh and by the way this complete code and the test cases are available on my github profile as well you can find the link in the description below let's start with the dry run first of all i have this reverb set that will contain my answer and will be returned through this function next i run a for loop in which i will iterate through this entire array and treat each integer or each value of this array as an index so a value of 4 means index 3 right so this is where i get the index using this index what i do is if the value is already negative i don't do anything and i move ahead if this value is not negative then i will just change it to negative by multiplying it by minus 1. so once this loop ends what will happen is this array will transform into right that is because you couldn't find one anywhere in the array right and hence the first position of the array remained unmarked once this is done all you need to do is you again iterate through your array and look at the element that is not marked 4 is not marked so you see its index whatever value is not marked just take that index and add it to your result fit currently i will add 1 to my result set so once this loop ends this result set will contain all your disappearing numbers and at the end you return this result so i will return this lift as my answer the time complexity of this solution is order of n that is because you're iterating through the array only once and the space complexity of this solution is also order of n because this result set could have all the numbers that are disappeared you could have an array that only has once up till 10 000 times so all the numbers are disappeared right i hope i was able to simplify the problem and its solution for you as per my final thoughts take a moment to realize the solution that we came up with we took advantage of the indices of the array itself right people often miss out that information when they're dealing with arrays most likely you would just see the elements like 0 1 2 and all the way up to n and then you will try to manipulate them now a array data structure that has a size of n and if you are also given integers or values that are also in that range then always try to use this concept the indices can be really helpful so just as a rule of thumb as soon as you see that okay array of size n and a range of size n then you can use these indices to your advantage what other methods did you come up with what other problems did you see where you could use this advantage tell me everything in the comments section below and i would love to discuss all of them with you would be also glad to know that a text-based explanation to this content text-based explanation to this content text-based explanation to this content is available on the website a pretty handy website for your programming needs i'm including a link in the description below 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 problem do you want me to follow next or rather what do you want to learn next until then see ya
|
Find All Numbers Disappeared in an Array
|
find-all-numbers-disappeared-in-an-array
|
Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[5,6\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[2\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
**Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space.
|
This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?
|
Array,Hash Table
|
Easy
|
41,442,2107,2305
|
207 |
welcome to my channel so in this video i'm going to cover uh the solution to this question and also at the same time i'm going to briefly go through the general steps we should follow in the real quick interview so we are going to solve this problem and do some live coding here and we are also going to cover the procedure in their coding interview so before we start the real content for today i would really appreciate that if you can help subscribe this channel because it can help this channel to grow so thanks a lot so let's uh resolve this problem so remember the first step always try to understand the problem if there's anything unclear don't be shy to ask any question and also at the same time think about some ash cases there are total this number of the courses you have to take and label from zero to unknown courses so you're given an array of prerequisites where prerequisites i is a ibi in the case you must take the course bi first if you want to take the course ai so bi comes before ai so for example the pair zero one indicates that you must take that take care zero you must you have to first take course one okay to return true if you can find all the courses otherwise you will you're going to return false so those are the examples uh and let's see the constraints it says the non-course is never going to be non-course is never going to be non-course is never going to be zero so it's between 1 to 100k so the prerequisites can be can have anywhere between 0 to 5 000 uh and the lens is equal to okay it seems like there's no illegal inputs here so um okay so all the prerequisites are unique okay that's good to know so it seems like there's no uh those such cases was considered based on the constraints so let's see the how to solve this problem so it's a pretty uh obvious solution to use a topology sorting to solve this problem so what how do you use the topology sorting so we need to uh so you know that in the graph in the directed graph we have um the in degree for each of the node so first of all we need to take we need to go through a read of the edge which is the prerequisites and then record down the in degree of each of the node so in degree let's say i have a map from the node index and to its in degree and then we are going to we also need to have a map from the node index to its corresponding neighbors so the neighbor so it's like the neighbor knows so the neighbor is defined as uh so for example let's say we have prerequisite ai to aipi so it must take bi before taking i so the there is an edge from bi2ai so in this case the node index is bi to uh so the value is list at least must contain ai so that's the two things i want to have and the other thing i want to have is a queue so the queue is going to have the node index uh so first of all we are going to push the node index with indegree 0 into the queue and every time we try to uh we try to pop one node from it and based on the map this map the node to its neighbor map you're going to find these neighbors update in degree and then if any of the node has in degree as one sorry it has indegree as zero then we are going to push into the queue so that's pretty much how you're going to solve this problem so essentially what is a runtime for this so the runtime would be i would say this oh let's say there are n nodes and the e address so let's say n plus e because we need to go through every of the so it's like for the first one we failed the in degree and this map it is going to take oe and then um for the q we need to put everything with indegree at zero okay yeah so it i would say and everything every time you just pop it and we go through the neighbor knows uh so it is going to be uh o n plus e here so actually we also need to have another thing which is visited so this set which is called visited to record down which uh of course we have already visited there so that we don't need to add that into the queue again so uh having said that uh let's start to do some coding work so for coding please take care about the correctness of the code the readability of the code and also don't be too slow so uh the first thing i would say is to have the um my appropriately degree thing um so this is integer this is node in degree so let's put everything into it on courses dot uh let's say that just uh i zero smaller than the courses plus i so node in degree the output the course i was uh in the word zero so this is the initialization of this then you're going to have the map which is the graph map so i'll say it is the interior it's a list of the nodes or let's say let's have it's a set so let's say i have a set here this is a graph and initialize it um yeah so this is let's see this is edge uh prerequisites um let's see just call it prerequisite um so i mean from node is equal to prerequisite um one and uh in the two node is from prerequisite zero all right so if um if the graph doesn't contains the key so if the growth doesn't contain the from node then we are going to add it a new hash set okay and then you're going to say okay graph dot get from that adder to so this is uh the initialization about the in-degree map and the in-degree map and the in-degree map and the and also the graph and then how we have queue which has a integer so the q new link lists here all right so and uh it's called uh the visited stuff so let's say interior visited is equal to the new hash set and at the end we expect that the visited is equal to courses the size of the visit is equal to the num courses otherwise uh there is a circle within the graph so we if there is a circle within the graph then we are going to return false um okay so we have the queue here um we have the visited so first of all it's something like uh for everything um no note index in degree dot key set so if um node in degree dot gets the node is equal to a zero then it means in degree zero then you're going to push into q so add it into node.add into the node.add into the node.add into the okay i know the unvisited is you're going to mark it as visited as well so that's the initialization um for the queue and the visited already so then it is the well the queue is not uh empty the queue is not empty so and we are going to uh try to pop that try to pop the node from the queue update under find its neighbors update the indegree if any of the node has integrated zero then we are doing we are going to push that so um let's say uh if um okay so this is like node is equal to q dot pop um or goes through all of this neighbors uh i'll say if the if it has been visited not actually so shouldn't do it here so this neighbor so this is kind of default or if you can do it if the graph that if not graph contains key node then we continue so in this case we don't need to call this one we just need to call get so we call the get node find out lovelyz neighbors so you're going to um update the indegree here but uh if the neighbor visited valentine's uh the neighbor then you're just going to continue otherwise we are going to say a node in the free output um neighbor node in degree talk at the neighbor minus one and if node in degree the get the neighbor is equal to zero then we are going to um push that into q visited.added all right so now we have everything and finally we are just going to return visited the size is equal to courses so antenna we have most of the code in place let's depend on this platform to help us to do the debugging work um so it says class expected that's okay so i think uh yeah so that's the thing i didn't do right okay so this is some typos so let's say 41 so 41 we have the key set node in degree key set okay so it's got no in degree uh some typo here degree so the q pop or just pull i guess all right so now it's uh good let's learn some other text examples so this one is wrong answer let's see why uh the second one is clear outputting is true but actually it should be false so we have zero one and one zero so essentially first of all note in that indegree is initialize uh everything as with indiegrass zero oh okay so actually we didn't we forgot to update the node in degree here so prerequisites uh node. put this is the two nodes on the node degree dot get to plus one so in this case i think we should be good yep um let's uh rest to other test cases all right and then let's do a submission okay so it seems like everything works well and that's it for this coding question and remember don't forget to do some testing after uh after you're done with the coding part so that's it for this question uh if you have any questions about the uh about the solution or about whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,828 |
guys welcome to my uh reconstructing session 1828 curious our number of points in that circle so you are given array with point i x i y is according it's the eyes burning until the planes uh viewers are subscribed to my channel okay so multiple points can have the same coordinate nicer you're also given a regular qr j so you also give a q j basically curious is actually yj or there is a circle right so basically you have some points and after some circle for each curious j computer number of points inside j circle point on the border of circle i can't see there's inside so basically for each circle right so you have a multiple circle for each circle you just compute how many circles uh how many points are inside that circle yeah that's it okay so this point are these problems very let's say maybe we see this example so we have the curies we have three circles this blue green and red and we have three points four points so for this uh two three one i think to rewind this green circle right so there are three points on the green circle so the first one is three and the two points on the red circle and the two points in the right and the blue circle so three two yeah so it's very easy right let's assume the answer is zero the assertion and the answer is just this and uh for queries this is the coordinates of the circle exposing the y coordinate of the center and the radius let's assume number zero then i then once we fix the curious and i we get the points how many points so this is the x the point and we calculate the distance if the distance is less than the if the center of that point the distance is less than or equal to the radius then inside circle right the number at one and for each queries we just appended it so just do the basically the two uh for loop and finally you just return ends yeah just straight forward right i understand this question is straight down the code straight before we can easily solve this one okay i will see you guys in the next video be sure to subscribe to my channel thanks
|
Queries on Number of Points Inside a Circle
|
count-ways-to-distribute-candies
|
You are given an array `points` where `points[i] = [xi, yi]` is the coordinates of the `ith` point on a 2D plane. Multiple points can have the **same** coordinates.
You are also given an array `queries` where `queries[j] = [xj, yj, rj]` describes a circle centered at `(xj, yj)` with a radius of `rj`.
For each query `queries[j]`, compute the number of points **inside** the `jth` circle. Points **on the border** of the circle are considered **inside**.
Return _an array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query_.
**Example 1:**
**Input:** points = \[\[1,3\],\[3,3\],\[5,3\],\[2,2\]\], queries = \[\[2,3,1\],\[4,3,1\],\[1,1,2\]\]
**Output:** \[3,2,2\]
**Explanation:** The points and circles are shown above.
queries\[0\] is the green circle, queries\[1\] is the red circle, and queries\[2\] is the blue circle.
**Example 2:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\], queries = \[\[1,2,2\],\[2,2,2\],\[4,3,2\],\[4,3,3\]\]
**Output:** \[2,3,2,4\]
**Explanation:** The points and circles are shown above.
queries\[0\] is green, queries\[1\] is red, queries\[2\] is blue, and queries\[3\] is purple.
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 500`
* `1 <= queries.length <= 500`
* `queries[j].length == 3`
* `0 <= xj, yj <= 500`
* `1 <= rj <= 500`
* All coordinates are integers.
**Follow up:** Could you find the answer for each query in better complexity than `O(n)`?
|
Try to define a recursive approach. For the ith candies, there will be one of the two following cases: If the i - 1 previous candies are already distributed into k bags for the ith candy, you can have k * dp[n - 1][k] ways to distribute the ith candy. We need then to solve the state of (n - 1, k). If the i - 1 previous candies are already distributed into k - 1 bags for the ith candy, you can have dp[n - 1][k - 1] ways to distribute the ith candy. We need then to solve the state of (n - 1, k - 1). This approach will be too slow and will traverse some states more than once. We should use memoization to make the algorithm efficient.
|
Dynamic Programming
|
Hard
| null |
848 |
Hello friends, in today's video we are going to discuss this plate problem shifting is the latest problem of yours, which team has given you SDO and cigarette friends, the interior has been tested and both casting gas and stuck SIM are written by the author and you have a separation. Will tell you what operation means, if you take operation then you can check one and convert it into Sarwar Pushp, then this one will also be converted into tumor. And dare and director people, I have done all the circular motion and reached the next stage. If it is okay then what operation do you have to do, you only have turmeric, only yuva21, so what do you have to do, plus titration, you have to take it and stick it for a time, okay, then you have the final stage. If you look at the output, you will see the example of how it works, its ABC is in this, first of all, what is there in shift is that you have to catch the first one character, set some time for it, okay, next this is five, then you have to catch the first two cats. If you want to catch it, you have to type next friend, then you have to catch the first cricketers, it is okay to set a reminder, according to that, how to solve it, see, this is an Aishwarya way by doing the string like this and you just have to do this by doing the second given and this. The indexing is that it is 0560 so you have to grab the first place in this one and how much do you set it just one thing so if you set one 3123 and subscribe then you have set the system like this is fine now let's talk so hatred is fine here So you set dabi time 12345 ok and ok and ok and so shift it to the side what is it 12345 where have you reached yes you have reached ok and watch the animal tractor completely if the director does not want to tamper with you then you seconds Now after the operation, she has reached here. Now let's talk about the third option. This is the third option because it takes a little patience, you have to concentrate on it and select it. You have to do night shift. This eye will not accept you. This is your eye. If you contest this then it will reach yours. Okay, similarly if you add 'G' then you will reach on 'C', you will add 'G' then you will reach on 'C', you will add 'G' then you will reach on 'C', you will insult 'C' and it will spread towards 'If you have fooled him, then you will insult 'C' and it will spread towards 'If you have fooled him, then you will insult 'C' and it will spread towards 'If you have fooled him, then you will reach there'. ' reach there'. ' reach there'. ' Okay, so this is the answer of RP Yadav, so basically quora, what will you do if the police face? If you want to do it then it will be given to you daily because what are you doing, you have children here, remember this yellow talented profile, then it means you have jewelery here or you have van login solution, so much capture, the one who is going to Delhi is fine. Have festive spirit otherwise you will get this tax Posted by What do we have to do One thing is you okay when it comes to some operation and how will you do tuition that what happened for the first time you just first character someone then made it clear that you provided the chakra That you declared two letters first, the third option is that you declared first, okay, you do n't have time, what have you written here, don't look again and again, see what was happening, do this first, you only performed the operation three times on this. Okay, now go and set it here, you shifted here twice and this block, recruit your teachers here, Pacific, only and only one bucket, see this, here, you shifted here only once, only for fashion, what happened, okay, so what is happening to this? Isn't it, whatever about you, whoever in the Air Force, on whom did you impact in the entire street, did you not put these first three values on your duty character? three values on your duty character? three values on your duty character? Okay, first Joe and the first unit certificate, did you impact and whoever delivered the war in this magazine test. I should go to my inter college. You are 359 for this post. Three plus five plus no. So how many times have you done this fastrack watch this sentence here? Okay, now let's talk about the tractor. According to this, A first, the pressure with the arrows had put its effect on it. Okay, now talking about the center, what happened here, miss this a, these two misplaced settings, open secret, your Android will be jelly, their value will be and with tips against the center. Okay, what happened to the third chapter, what happened to the third news, I have my iPad, so I made it to you here in the night shift, if you like this tree, we are coming out, the hot effect is out, start taking your time behind that 98715 appeared by getting up. In the middle of Kitna Hona Industry Has Reported Cases you this diary that you will know that you have to chant so many times okay but directly on your own now play this from here na ABC has been given to Diet Yatra so you know it is ABC If I send you one more shift then if you send a Hussain then where will you reach and you will start the B option, reach and where will you reach and you will start the B option, where will you reach, you will reach on the back and the effect is here also from you Lifted and subscribed from you Okay and how much on 90th your internship will reach crores If the album has reached then you can do this directly in front of you that what else has you prepared for the vacation? Again and again Muzaffar who came first is putting his finger on many operation group directors. This means that this Joshi will have an impact on the third team. Vaccines will be tested on option time Inspector of corruption will be first tested Apart from operations chips title device Play the training Removed that the texture will get digital More depend on what did you do first As I talked about what should we do We are extracting sufficient Are certificate me just wife in a small kids markandeya katju and we are rapping that meaning if you right now half said that you right now your present character is jail and you do holy setting is the expression of z whose benefit is five if you that If you click on then what will you have to do here you have to type pregnant inches plus while staying in the temple, but what mode of operation do we do, okay, we will give tips about it, then we will reach this platform and 2000 will be reached through which we will reach where. So this is your only operation is working like this, so what are the modes used in the work, used it for gas rap, to use rap, the mode has been shifted off and now let us see that you are using it only for scientific purposes. Kind of value, today is the meeting, now you have such a powder only and only so that you have to select asif time, okay, so what will we do with it which is of your assignment, right, if you are like this 312, what is this possible if your this So, what will happen here? I - A Pyun, you like this very much, happen here? I - A Pyun, you like this very much, happen here? I - A Pyun, you like this very much, zero is fine, see this, zero is fine, now what to do in zero, certain number of shifts after 10 years, like share, we, you, free time, set operation, if it becomes Karachi then This will be zero copy, so your warts, how much do you have to shift, then it became pimples, now you will do one in the nourished plus side, neither will you go back to the character of Note 4 Redmi Note 4, so you have become in the city, okay means, you will do this I - A So what will happen - will do this I - A So what will happen - will do this I - A So what will happen - on doing A, your career value becomes internal and in the interview, you will do plus 1, otherwise your intake will be converted into character, so this is how it is working, see, have you done this? The shift is that tube of 2016, we have to wrap because I, if you do all this, your value and all the examples, subscribe by doing so much everyday plus, if it gets torn, then you can't do anything in this time, husbands of Islamic countries will do 228, okay So what will happen here if you guess what should not be met then your sarcasm will be done okay so you set Shyam that you cannot do audit so I have 2068 to rap and you will do character - director - a So you will get enter and if you will do character - director - a So you will get enter and if you will do character - director - a So you will get enter and if you do inch plus character then you will get this character. Okay, take care of this thing and return it to us at the end. Friends, I hope you like this explanation. This explanation is coming in Oct 29, still your pocket is gone. If yes, then you should definitely reply in the comment section. There is a map behind. If you want to do any latest updates in the placement center through any video, please tell us. We will definitely make more videos related to this. If you like the video, please like the video and subscribe to the channel. Have shared with friends so many people want to watch this video, see you soon in the next video, take care by then give us.
|
Shifting Letters
|
shifting-letters
|
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length.
Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`).
* For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`.
Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times.
Return _the final string after all such shifts to s are applied_.
**Example 1:**
**Input:** s = "abc ", shifts = \[3,5,9\]
**Output:** "rpl "
**Explanation:** We start with "abc ".
After shifting the first 1 letters of s by 3, we have "dbc ".
After shifting the first 2 letters of s by 5, we have "igc ".
After shifting the first 3 letters of s by 9, we have "rpl ", the answer.
**Example 2:**
**Input:** s = "aaa ", shifts = \[1,2,3\]
**Output:** "gfd "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `shifts.length == s.length`
* `0 <= shifts[i] <= 109`
| null | null |
Medium
| null |
1,721 |
hi today we are going to look at problem 17 21 swapping nodes in a linked list so we are given here of a linked list and an integer k and we have to return the head of the linked list after swapping the values of the kth node from the beginning of the linked list and case node from the end of the linked list and the linked list is one index so the linked list starts from one the first node in the linked list starts from index one two three it does not start from a zero okay that's what it means when they say one index link list right and uh the thing which we have to do is we need to find two nodes right uh so they are given a number k so from the start we need to go to gate node from the end we need to go to the case node and find the uh once we find those nodes we just need to swap the values of those nodes right they don't want us to swap the actual nodes just swap the values of those two nodes right so let's take an example that they have given over here right so uh so the linked list has is of length 5 and k is 2. so since k is 2 the second node from the start is this one and the second node from the end if you count backwards this is the second node from the end so that's very clear right now once we have to once we have found both of these nodes uh it's pretty easy we just need to swap the values of both these nodes let's take a look at how we are going to find the second node from the start and the second node from the back of the linked list right so finding the second node from the start is very easy right so you just have head over here you just do the counting and you go to the second node so let's uh the trickier part a little bit trickier part is finding the second node from the end and what we can do is one technique that we can use is probably we can just you know find the length of the linked list by iterating it over once so that's the first iteration and once we have the length of the linked list like the number of nodes in there we just subtract k right and then uh find out what is the node where we have to uh go right that's and once we have that we just iterate to the linked list again and stop when we are at that particular node right so that's uh it's one way that you can use you know to find out the second node or the kth node from the end of the linked list the other way that we can use is we can use a fast pointer and a slow pointer technique a two pointer uh and the fast pointer is ahead of this low pointer okay by the k places so if let's for our case let's uh consider that key is two in this case okay so we will have the first pointer okay initialize to here so that's my first pointer right and my slow pointer is going to be before one over here right so the difference between fast pointer and second pointer has to be two nodes okay or k and so for that we can just create a dummy node or something right and then we can have the dummy node point over here so now the difference between fast and slow pointer is two spaces or k spaces right and then we just i trade both of these pointers by value one each and every time so once we do it the fast pointer will go over here the slow pointer goes over here node one the fast goes over here and then eventually the first pointer will go to mal and when that is the case we need to move two spaces back because that's how the slow point is going to move right the distance will be maintained because we are going to move each and every pointer uh for that every iteration so in the end the fast pointer will be here and the slow pointer will be here right so if you see now our slow pointer is two spaces uh from the back of the linked list right or k spaces from the back of the linked list another thing before we go to the coding to see is initially when we initialize right the fast pointer two spaces from the start right if you see we also need to find right another node that we need to swap the value which is k spaces from the beginning which is the fast so we could just when we initialize fast over here right to this node we can have another pointer right which is going to point to let's call that as the start right that points to fast before we move and uh do all this iteration and get the second node or the case node from the end we can just point start over here and so let's take a look at how we can code this so as we talked before we are going to use a dummy node right for using the two pointer technique if you remember no i don't care about the value of this node and this dummy node has to point right so what we are saying is there will be a node a dummy node and then we are going to initialize all of our variables uh that we talked of before right so let's do that so this node we said we have a pointer slow okay slow points to dummy another node we said we will use is which also points to dummy just okay and the first thing which we know need to do if you uh recall from what we talked we need to initialize the fast note right to uh to go to the uh yes position right or the beginning position which means we need to initialize fast this is zero this is one and this is we will initialize this that's the first step so for that what we are going to do is we are going to just run right just this is just initializing the fastness okay so after this runs uh for the example we will be at the node 2 over here right and now once fast is here so what this means is from the beginning of the node i am k spaces i am to the case node from the beginning right so i'm just going to initialize my start variable also the start pointer to point to the now my slow node is at dummy right my fast node is here and i just need to keep on iterating while fast is not equal to null so while fast reaches null what i'm going to do is i will save equal to slow dot next right so the difference between both the nodes is always going to be two and one the fast small i'm pretty sure i'm like two spaces behind now right so that's what i'm looking for so now slow and fast is in there now with what's remaining is just to swap the values right so you can just create a temp int variable right and you can just say it is equal to the slow dot value right oh dot value is equal to value all right so this is this and then is to just return the hat let's take a quick look at it to see if there are any compilation errors or something okay let's try and run this uh before we submit just to make sure there's no compilation errors or anything okay it looks good let's try and submit this so that is it uh so it's uh pretty fast as you see uh looking at the time complexity right so if you see we are in worst case in any case actually we are going to traverse to the linked list only once so the time complexity for this uh is going to be o of n right because i'm going to traverse only once and there is no uh space that is varying as per the size of the linked list right all the space is constant right whatever variables we have initialized that's all is what we are going to use so my space complexity for this solution is o of one uh thanks a lot guys for watching the video if you like my channel please uh subscribe uh thank you so much take care bye
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
100 |
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question 100 same three basically given two binary trees we need to say if they are the same or not and two binary trees are considered the same if they are structurally identical and the nodes have the same value here are some examples guys yeah let me show you how to do it so i'm going to solve this question recursively and the good thing is that we will not even to declare a helper method to do it so we can do everything within is same tree method which expects two input parameters the three node p and three node q so two binary trees and when you're solving the question recursively the first thing is which you should start is to think about the base case and in our case the base case would be to check if three node p and g node q are both equal to now because if they're both equal to now it means that they're the same binary trees because now is equal to now and if that's the case we can just return true simply as that guys so this is our base case now let's do another else if so when two binary trees are not the same um for example if one tree is equal to now but another one is actually not equal to now it means that there cannot be the same and if that's the case we can just simply return false makes sense right yeah because we just checked if p is now enqueues now because this is our first check you can just you know check this condition by applying or because we know that we already checked if both are them are now so if we check if p is equal to now or q is equal to now it means that like if any of them is now but another one is not now we can just return false so yes guys and another one um so because we already have these two checks we if we didn't return anything uh by this moment when we came to this line it means that like okay both values are both three nodes are definitely not equal to now so there are some values inside these three nodes and we can just check if these values are the same or not because if these values are not the same it means that we can just stop and say that the three notes are not equal and just simply return false so if p dot value is not equal to q dot value return false okay guys so we did these three checks uh which means we checked like the current values so we checked the current root of both three nodes and if it basically reached this line of code it means that okay both three nodes have some values and these values are still the same so now we want to do a recursive call and just to go to the left and right subtrees of both p and q to check the rest of the values to basically traverse through the binary trees and yeah we just can call each same tree method first of all on p dot left and q dot left so we're going to the left subtrees of both p and q and we can also have the end condition to do the same for the right subtree p that's right cue that right and yeah if for these two recursive calls in the end both of them will terminate recursively with this if condition and they return true it means that yes the trees are the same and you know we traverse through the whole p and q trees and the and all the values within these two binary trees being the same we will just return true if not we will return false simply as that guys simply as that okay let me run the code to see if it works and it does let's submit now yes guys perfect that's it was the little question 100 same tree very simple but quite interesting problem please make sure to subscribe to my channel share this video with your friends challenge them to see if they can solve this problem or not and guys i will see you in the next video and remember lead call today keeps an employment away see you guys
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
495 |
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys we are going to solve question number 495 teemo attacking in lead code before i start with the video guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started with the problem statement now so basically guys we are given a hero called as timo who is attacking an enemy called as ash with poison now teemo can attack at any time intervals and basically we are given an array called as time series which is having all the time intervals or time values second values whenever teemo is attacking ash whenever teemo attacks ash then ash goes into an effect of poison for a duration of duration variable so for example in this case the duration is 2 so ash goes into a poison effect of two seconds whenever he is attacked okay now this can also be taken from this formula that for example if ash is attacked at time interval t seconds then he is going to be in poison effect until t plus duration minus 1 at second okay so uh this is the time interval until he is going to be in the effect now it is possible that timo attacks ash again but whenever he attacks again then either it could be when the poison effect has already ended from the previous attack or ash could already be in the poison effect so whenever teemo attacks again when the poison effect is not ended then the timer for the poison effect is reset and now the new poison effect will end duration seconds after the new attack so for example if uh in this case let's say this example uh in this case timo attacks first at second number one so ash is going to be in the poison effect for second one and for second two because the duration is two right now let's see on second number 2 uh timo attacks again so because ash is still under the poison effect then the timer clock is reset and again ash is going to be in the effect for t plus duration minus one at the second so in this case ash is going to be in the effect from second number two plus two minus one which means three so ash is going to be in the poisson effect from uh second number two and also on second number three now we have to return the total number of seconds ash is in the poison effect so for example in this case ash is poisoned for second one two and three that's why the answer is three okay so i hope the problem statement is clear to you guys constraints are also straightforward time series is in non-decreasing order the value of the non-decreasing order the value of the non-decreasing order the value of the time series goes from 0 to 10 to the power 7 time series has a length from 1 to 10 to the power 4 that means time series have at least one second in it okay so let's go forward with the solution now so the first thing is we are going to declare our count variable and this count variable by default is going to be duration okay why is it going to be duration because we know that time series array has at least one value okay so even if the time series value uh array has a zero value or you know at least it starts from zero second then whichever second it starts wrong ash is going to be in the effect for duration number of seconds okay so by default account is going to be duration now we assume that um ash is already attacked once so uh we are going to check for the next attacks starting from uh not from the zeroth value of time series but from the uh one h value of time series so for integer i equals to one so we will start from the second time that ash is attacked so i is equals to 1 to i less than time series dot length i plus okay now that we know that ash is attacked a second time we need to make sure that if he is attacked while under the effect of poison or after the effect of poison is over so we need to check integer poison effect over time or i would say previous poison effect over time okay so the previous poison effect is going to be over after time series i minus one s value plus duration value okay so this is going to be the time after which the previous attack is ended okay now we need to make sure that the time series value is greater than or equal to so if time series ith value is actually less than or equal to the previous poisson effect over time that means ash was still under the effect of poison when he was attacked again so it means that we have to reset the clock okay by resetting the clock we basically mean that whatever is the time difference between the current time and the previous poison effect over time okay so that means for example ash is supposed to be in the effect of poison until second number four but he was attacked again on second number two so that means the duration between second number two and second number four we cannot take that into consideration now because the clock is reset at second number two so from second number two we have to again counter and add the duration okay so we are just going to subtract from count the previous poisson effect over time minus the time series i so that we can discard the time of poison which we took into consideration before uh before the new attack happened so we discard that time and then we are going to again add into count the duration so that the time is reset and again as goes into the effect from the ith time to the duration time okay finally we are just going to return the count variable which is the total number of seconds ash is in poison effect let's run this code guys let's see if this works for our example and there you go you can see that it is accepted and it is going to get accepted for other examples as well talking about the time complexity so the time complexity is order of n because we are taking uh all the time series values only one this is a n uh for loop space complexity is order of one because no extra space is being used so that was the solution guys i hope you guys like this solution and if you do then please do not forget to like this video and share this video with your friends please do subscribe to my channel guys and hit the bell icon for future notifications if you have any questions comment suggestions for me write down in the comment section below i would be happy to address them i'll see you guys in the next video until then take care and bye
|
Teemo Attacking
|
teemo-attacking
|
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack.
You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`.
Return _the **total** number of seconds that Ashe is poisoned_.
**Example 1:**
**Input:** timeSeries = \[1,4\], duration = 2
**Output:** 4
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
**Example 2:**
**Input:** timeSeries = \[1,2\], duration = 2
**Output:** 3
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
**Constraints:**
* `1 <= timeSeries.length <= 104`
* `0 <= timeSeries[i], duration <= 107`
* `timeSeries` is sorted in **non-decreasing** order.
| null |
Array,Simulation
|
Easy
|
56,605,649
|
1,825 |
hello everyone let's take a look at the code 1825 it's the last question in the weekly contest and it's a hard problem and also it's a hard problem but it's not that hard it's just very complex since you may need a lot of coding and you mean to debug a lot okay let's take a look uh so if you haven't used this problem you can take some time to read basically we need to implement three functions mk average and element and the calculate mk average okay so it's a sliding window problem since we need to keep the window of size and we need to keep three containers one for the largest k elements one for the smallest k elements and one for the middle elements and we also find that elements can be duplicated so we need multiset so we need to maintain the smaller and larger like size of k okay let's take a look at the implementation so we need to keep m and k since this is the input to initialize our class and we need to keep our window so um when we add a new number we may pop the front element so we need to keep the all elements in the window and we have these three multisets to record the similar numbers larger numbers and middle numbers and we have this middle sum it need to be long otherwise we may get overflow okay if we can maintain this middle sum and variable correctly then it's very easy to implement calculate mk average when the size of window is smaller than and we can just write a negative one otherwise we just return middle sum divided by this middle size so this is average we want to get so the key point is how to maintain middle sound here okay let's implement element function um the element here is very simple since i implement two um other functions one is add element num add this element to my window and maintain some mod set and if the window size is greater than m then we need to pop the old element so we need to remove some element okay let's take a look at this add element the item element will add a new element to my window at first all these multiset are empty so we will go to this gif branch for example when m is 10 and when we add the first element the second element nothing special happens here we just push the element to a window but when we add the tens element something happens since windows size is same as m we will call initialize multiset to initialize this three multiset notes only wrong ones since after running initialize multiset middles will not be empty so this function will only run once here okay let's take a look at initialize multiset initialize multisite is very simple when we just add elements i will copy some window to another local web called account window and i will just copy all the elements in my window to my numbers here and just sort these nums and just put like the first k and smallest element into smaller numbers puts the largest k elements into larger numbers and puts middle elements in the middles and don't forget to update this middle sound so that we can get middle sum in one time okay so initialize um what you say is very simple after we're adding m elements then we add one more elements we will go here after adding m elements assuming we're adding one more elements and let's say if the new element is smaller than the biggest number in smaller so if value is in this green range which will happen and we want to keep the size of smaller to be k now we add value to smaller so size of smaller will be k plus one so we will try to move the largest element in smaller to middle so that the size of smaller will still be k okay so this is our middle candidate this is the largest element in smaller okay next i will try to uh like insert value to smaller and erase the middle candidate and insert the middle candidate to middle and don't forget to update this middle sound since we add one more element to middle here okay and we need to use the errors here since it's a multiset you see there is erase if serious duplicate numbers we will erase all of them so when you pass by the iterator here okay if the value is seeing this real color range it's very similar so i just skip it if the value is in the middle range is very simple we just insert value to meters then don't forget to up this middle sun okay since um so we know size will be greater than m so we want to pop the old element first we pop the other element from our window and this is this value is the pop element so we will try to remove this value from uh our multiset the first case is the value since it's a smaller set what shall we do first we just erase it same as before we need to pass the iterator here so we just erase the first value that just greater same than this value okay then since we want to keep the size of similar to b k now we remove one element the size is k minus one so we try to get the smallest element in the middle and move this element to smaller so this is a small candidate we insert this small candy to smaller and erase it from middle don't forget to update middle sound since we remove this element okay if the value is in this red range in larger set it's very similar so i will skip it if the element to be deleted is in the middle syringe is very simple we just remove it from middles and don't forget to update this uh middle sum okay so far so good so finally uh in this calculator m case average is very simple we just return middle sum divided by the middle size so this is all the implementation so actually this problem is not that hard like it's difficult because it's very hard to write a very clean code and we need to maintain a lot of state here so uh we need some more time to practice yeah that's it thanks see you next time
|
Finding MK Average
|
find-minimum-time-to-finish-all-jobs
|
You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream.
The **MKAverage** can be calculated using these steps:
1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.
2. Remove the smallest `k` elements and the largest `k` elements from the container.
3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**.
Implement the `MKAverage` class:
* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`.
* `void addElement(int num)` Inserts a new element `num` into the stream.
* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**.
**Example 1:**
**Input**
\[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\]
\[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\]
**Output**
\[null, null, null, -1, null, 3, null, null, null, 5\]
**Explanation**
`MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5`
**Constraints:**
* `3 <= m <= 105`
* `1 <= k*2 < m`
* `1 <= num <= 105`
* At most `105` calls will be made to `addElement` and `calculateMKAverage`.
|
We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks
|
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
|
2114
|
974 |
I will be discussing this solution to Lead Core problem number 974 Subaru is something divisible by K so in this problem you are given an array you have to find the number of sub arrays whose sum will be divisible by K so what is the sub array a sub array is a continuous portion of an array so in this example Phi Teresa summary 532 will be a summary similarly just the element 3 will also be a sub array so in this particular example you have 4 5 whose sum is equal to 9 and just 7 2 whose sum is equal to 9 so the answer in this case will be equal to just 2. so I will explain you the concept of prefix sum and I will also discuss this solution with you so what is the concept of prefixer in prefix sum you will have a track of the running sum of the array so in this particular example what is the sum of the first three elements it is equal to 9 right so this will be equal to the sum from the 0th element to that particular point so if you want the sum of the first four elements you can just go here 7 that will be the sum from the 0th element to that point similarly if you want the sum till this point it is just equal to 4. so one observation that you have to draw here what is the sum from the second element this element to this element so if you want to find this out it is just equal to the sum till this point minus the sum of the element one element prior to this so 4 and 4 that is equal to 0 so if you look here 5 minus 2 that will be equal to 3 minus 3 that is equal to 0. similarly if you want to find the sum of these three elements it is nothing but 4 minus 9 that is equal to minus 5. minus 2 minus 3 similarly if you want to find the difference between any two elements it is just equal to the prefix sum till that point minus one element before that point that is just equal to pairs of I minus PS of i1 minus 1. so how do you find the answer to this solution so in addition to Prior sum we have one more row which indicates the divisibility of this by the particular element K so in this example K is equal to Phi so I just indicated the prefix sum percentile or the modulus by 5 so 4 9 mod 5 is 4 9 1 5 4 similarly two and four so we will just use a hash map in order to store the uh prefixon modulus and whatever the count is there you will increase so for example the count of four here is 3 right we will store that value similarly uh at till this point it is equal to 4 so we will store this point and we will also change the answer accordingly so let me take you through the example so here the running sum is 4 and we will just increase the count by one we have initiated the hash map with 0 because from the first element to that element the sum is just equal to this right so we have just initiated the hash map with 0 with a count of 1. so at this point the count is 4 so in the hash map did you have any prior to that no so the answer doesn't change the answer will just be zero so if you go to this element your answer will be one why one because they already exists a prefixon that is equal to 4 so your answer will increase by 1. so similarly when you go and the hashma value changes to two similarly when you go here the answer will increase by two Y2 because you already have 4 which is equal to and now it will increase to 3. similarly when you go here 2 do you have any two already prayer in this hash map no so the answer won't change the count will increase by one similarly when you go for four here the answer will increase by 3 why because we already have the value of 4 equal to 3 now this value will just change similarly when you go to the next the answer will increase by 1 because we already have zeros values as one and the count will change to 2. so if you do the sum of all of this that is just equal to 7 in this case that is the required answer so here is the code for the problem this is in Java we have just initiated the hash map and we have initiated the answer is equal to 0 and prefix sum is equal to 0 and we have also put a value that is 0 and 1. so the prefix sum is just equal to this it is modified and it is mod by Phi and this particular example uh you will just mod it by key and you will just add it to the hashback before adding it to the hash map if the hash map contains this prefix sum already we will just increase the count so let me run this yeah it's working fine thank you for watching the video please do like and subscribe
|
Subarray Sums Divisible by K
|
reorder-data-in-log-files
|
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104`
| null |
Array,String,Sorting
|
Easy
| null |
1,624 |
so hello everyone and a very good afternoon to all of you so today we have a new problem which name is largest service string between two equal characters lead code 1624 problem so before going forther in this video please make sure that you have likeed and subscribe to this Channel and also it's my advice to all of you that please read the problem carefully and try to build up the intuition and then try to do the code if you will simply see this video and then do the Cod it will not be beneficial for you so if you want to make some use of this video so please try by yourself then see this video If you will check at any point so let's uh see the problem statement given a string s return the length of the longest sub string between two equal characters excluding the two characters if there is no first sub return minus one and a sub string is a continuous sequence of characters within a string so the problem is saying that we have given a string and we have to find the same characters and the number of characters between the same characters will be our answer so let's see the example one we can see in example one there's a string and the two same characters are there but the number of characters between the same characters is zero you can see a then a the number of characters between the same characters is Zer so our answer will be zero if it was like a o a then our answer will be one because the number of characters between the same characters a is one which is O Okay so let's see the example two here we can see a and a number of characters between the same characters is two because B and C are there the same characters are a and the number of characters between the same characters is B and C so the number of characters is two and here you can see there is no same character so the number of characters is zero and we have to return minus one because there is no same character so this is a problem statement let's think about the approach so let's have a look on the constant so constent is going s do length it means n is going from 1 to 300 if we use big 10 square technique then it will be 300 Square means 9 into 10^ 4 so 9 into 10 4 Square means 9 into 10^ 4 so 9 into 10 4 Square means 9 into 10^ 4 so 9 into 10 4 is a very good solution because it will work perfect big of any Square solution but it will work perfect because the constant are very slow means very low in very low range 1 to 300 it if it was like 1 to 30,000 then it would be was like 1 to 30,000 then it would be was like 1 to 30,000 then it would be very hard then we have to do this in big but here is the conent is going from 1 to 300 then we can use big of n perfectly so let's think about the approach for this problem so here you can see we have to find the number of same characters and the characters between the same characters and the count of the characters also so we can use two loops and the first Loop will go from I to size minus one and another loop will go from that I + 1 to 5us one loop will go from that I + 1 to 5us one loop will go from that I + 1 to 5us one let's say let's do the code so that you can understand properly let's define answer equals to Z why I'm defining answer equal to minus one because if there's no same character then we will directly minus one that's why I'm defining it minus one so let's apply a loop 4 inal to Z to I less than then s do size then I ++ I is going size then I ++ I is going size then I ++ I is going from zero inex to 5 minus one here we are using two pointer approach okay I is going from 0 to I 5us one and our Z will go from let's define the Z into J = will go from let's define the Z into J = will go from let's define the Z into J = to I + 1 to J is less than S do to I + 1 to J is less than S do to I + 1 to J is less than S do size then j++ J is going I + 1 to S do size then j++ J is going I + 1 to S do size then j++ J is going I + 1 to S do SI and it's like s i to S of J if this condition is true character equal Max answer I characters exclud that's why we are doing minus one okay or finally let's see if this or not you can see it is working perfect let's submit this yeah it is working perfect taking 3 millisecond by is it is taking 3 m second because you can see big Square solution but and it now it's your task to see how we can optimize this solution we can do this solution in bun reverse also it's your task to do okay I will not explain the big end solution because if I will explain that b you will do so it's your task to see how we can optimize this and the space you can see here we are not taking any space we go of B spaces because on we are only using the variables in answer we are only using the variable we are not taking any space so space complexity is Big over and the time complexity is Big of n squ because we are using two nested Loops that's why time complexity is Big of n squ so now it's your task to see the Big W and solution and how we can optimize this so try by yourself here if you do not try then you will learn nothing okay so we'll see next video and if you like this video then please like share and subscribe and we'll see
|
Largest Substring Between Two Equal Characters
|
clone-binary-tree-with-random-pointer
|
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.
**Example 2:**
**Input:** s = "abca "
**Output:** 2
**Explanation:** The optimal substring here is "bc ".
**Example 3:**
**Input:** s = "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.
**Constraints:**
* `1 <= s.length <= 300`
* `s` contains only lowercase English letters.
|
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
133,138,1634
|
509 |
hello coding enthusiasts welcome back to another exciting episode on called Master Quest today we are stepping into the captivating world of Fibonacci numbers and as you may notice the classical problem in computer science to demonstrate the use of recursive function right so let's get started and find a question description later the problem statement initial the Fibonacci numbers commonly need Ed with f former sequence such that each number is the sum of the two preceding ones starting from zero and one so F0 is going to be zero F1 is going to be 1 and FN is equal to f n minus 1 plus FN minus 2. for each n greater than one right so if F of 2 is going to be 1 and F3 is going to be F2 plus F1 which is going to be 2 right so let's come back to the visual studio code and try to implement this problem now let's quickly implement the solution for this problem as the first step we need to define the function signature so let's say FIB or an input n is going to be in and then we should return it right so to implement this question we need to consider two base cases if n is equal to zero then the Fibonacci number for zero is going to be zero so let's return 0. and else if n is equal to 1 then it should return one otherwise we should return um 5 for n minus one plus 5 for n minus 2. right so we expect this solution working correctly and to make sure it is working correctly Let's test it with some examples let's say FIB for zero one and two right there we go now let's run our surf file is zero one and one right so this should be the correct implementation for this problem and to make sure everything working correctly let's come back to the browser and submit our solution to listen make our code clean here and then hit the submit button there we go here's the solution for this question thank you everyone foreign
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
478 |
Hello everyone! This is the LeadCode problem "Generate Random Points in a Circle". Given the radius and x,y positions of the center of the circle, write a function to generate a uniform random point in the circle. Input and Output values are in floating point; A point on the circumference of the circle is considered to be in the circle. Here's a drawing to help with better understanding. The blue circle's location and the size is based on the Input x, y and the radius. It could be anywhere with any size. It's easy to calculate the coordinate of these four points. This one should be x - r, x + r, y + r, y - r. Let's say we have a new point (x1, y1). x1 should be randomly generated from x - r to x + r. And y1 should be randomly generated from y - r to y + r. This range is not going to be good enough, because the new point might be in these four corner, and they're obviously not in a circle. But these points have one thing in common: the distance from a center to any of these points is greater than the radius. So to solve this problem, randomly generate a point that is in this range, then check the distance between this point to the center. If it's not greater than the radius, then we find the answer, otherwise redo this process until we find the point. It's time to write the code. First define some variables. Define x1 as x-coordinate of a new point. Randomly generate a float point from [self.x - self.r, self.x + self.r]. Define y1 as y-coordinate of new point. Now use “Pythagorean Theorem” to check the distance from the center of the circle to the new point. Compare it to the radius, If it's smaller or equal, Then we find the answer, otherwise we have to repeat this process Thank you! 😊
|
Generate Random Point in a Circle
|
generate-random-point-in-a-circle
|
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.
Implement the `Solution` class:
* `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`.
* `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`.
**Example 1:**
**Input**
\[ "Solution ", "randPoint ", "randPoint ", "randPoint "\]
\[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\]
**Output**
\[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\]
**Explanation**
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return \[-0.02493, -0.38077\]
solution.randPoint(); // return \[0.82314, 0.38945\]
solution.randPoint(); // return \[0.36572, 0.17248\]
**Constraints:**
* `0 < radius <= 108`
* `-107 <= x_center, y_center <= 107`
* At most `3 * 104` calls will be made to `randPoint`.
| null | null |
Medium
| null |
166 |
hi Ricky here this is little to question number 166 fraction to the croissant isomer this is an idiom difficult question asked at it keep it integer representing them numerator and denominator of a fraction returned a fraction in stream comment if the fraction part is repeating enclose the repeating part in classes okay let's check the division for one numerator 1 denominator 2 so 1 divided 2 is 1.5 there are no repeat second is 1.5 there are no repeat second is 1.5 there are no repeat second numerator 2 and in a rate of 1 so hopefully is - ok last is numerator to hopefully is - ok last is numerator to hopefully is - ok last is numerator to denominator 3 so 2/3 so and so instead denominator 3 so 2/3 so and so instead denominator 3 so 2/3 so and so instead of point six so we need to express tell em bit number okay I think there are a lot of a fortune in hateful here to solving question and my approaching is using Eugene reminder and then when reminder is repeat the minis limited 3 4 7 8 3 and when you found the same remind twice that is the signal the limiting number is generated so we will check that and then when reminder is that if the limiter our reminder is 0 this is perfect case for this one and then we just return while there are more fit reminder and definition each other it also good we just return but if we the same is awkward and then we needed to explain it appearances I will implement with this approach ok first I will calculate and reminder is either use load tip even if mode and then it also possibly seem like a tip number so I needed me needed to use a IDs change it to party tip and abs and I will check the sign minus M multiplied t mmm smarten channel as I press in this case I wind up a positive number it led them to any sign but interviewer asked to me please to use proper plus for positive expression and then we need to change it and then let calculate fracture I will that fraction the only the list of listed for Tyson and Frosty's side plus number but number in this case number is integer so we needed to cast to stream and then if reminder is 0 it is perfect cake perfect case just return join fraction alright and then as you need to add spot behind our fraction and then we need to use dick shallowly at this time and thereby remind is natural I will check remainder in ditch fictional has the minder if yes we will use fraction insert get pictionary this is index for same word but previous see in certain meanings move the index after index in cloud that index the move to one point two later and then insult this data so we needed to input open palaces and then end our array we append across palaces close finishes and then I will rate no return is for function and then iteration for break right and then otherwise I will talk dictionary reminder and value is last index of friction prints and then I will cook great again and reminder is thief mode and reminder but I plan to take to divide and then divide with ABS positivity no and then question and then refresh see what is seen okay reminder I think you mind oh alright there's some okay let's check complexity how many iterations here there are only one while statement and they stand more no and how about space okay fraction is always so we can say it take linear time and deep om space thank you
|
Fraction to Recurring Decimal
|
fraction-to-recurring-decimal
|
Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return **any of them**.
It is **guaranteed** that the length of the answer string is less than `104` for all the given inputs.
**Example 1:**
**Input:** numerator = 1, denominator = 2
**Output:** "0.5 "
**Example 2:**
**Input:** numerator = 2, denominator = 1
**Output:** "2 "
**Example 3:**
**Input:** numerator = 4, denominator = 333
**Output:** "0.(012) "
**Constraints:**
* `-231 <= numerator, denominator <= 231 - 1`
* `denominator != 0`
|
No scary math, just apply elementary math knowledge. Still remember how to perform a long division? Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern? Notice that once the remainder starts repeating, so does the divided result. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
|
Hash Table,Math,String
|
Medium
| null |
73 |
all right hello welcome back to my Channel today we are going to talk about political problems 73 set Matrix zeros so this is a very popular problem it is a former blind simplified list yeah I hope you can enjoy this question I'm going to use two methods so because this is a in place you must do it in place yeah so it means when we're gonna change some values we should not use another DP or Matrix we don't need to return anything because we're gonna make the operations in place yes so here is a follow-up is a follow-up is a follow-up could you device a custom space solution so I will try two methods I will not try the Brute Force because the brute force will be unsquare if n is the length of the Matrix yeah it will be n Square pattern let me check yeah but for the but for my second method I will use the O M times and also for the third method at the first M times a but the third method of the space is just oh one yeah I will not use them I will use a constant space solution for the third method I'm not going to use the brute force method because the brute force is Success like this you're gonna Define another DP array if you find zero so you put those and columns to zeros and you find another value you put close and columns to the rules yeah that will takes much more time yeah now let me explain in the what about my second and third method and then go to the code Editor to finish the coding now let's say in the whiteboard if we have a matrix like this yeah so this is the row and the column if we have a low end column we want to put the row index and column index into our set if we find a zero yeah if we follow zero point so in the low set so we're going to put a 1 inside because the index is one and also in the column set we're going to put so this is a column set so we're going to put a 1 inside the set so after that I'm going to Loop through the Matrix so if I find any c any index that is in low set or column set so for example this is the inside of the low set and this is inside the column set then I will set those points to zeros and then first return the result so this is for the second method I'm going to use the actual memory I'm going to use the set or you can use array it's also the same yeah and the third method is I'm going to use the constant space so how should we use the constant space as we can see if we use the set instead we can use the first rows and first columns as ever as I will set so for the first though I'm going to fact if there is a for example it's this one yeah for the left side if there's zero I'm going to put a zero to my first low if there's a zero in the first yeah uh column I'm going to put it in the First Column if this is 0 is in the I'm sorry this is a second though I'm going to put it in the second Zone and second column yes and after that what I'm going to do I'm going to just Loop through this uh loop through this Matrix so if there is a zero I'm going to put everything for zeros for this row and if there's a zero in this column I'm going to put every values in this column but yeah in this way it might pollute the lower column so if there is a zero for example there has already be a br0 it might pollute this row or column so I have to check if this is all a column has a zero or not because if it has a zero so this row or this column should always be zero yeah so I have to tag if I polluted or not so this is the suspensive case it is not polluted so for example if here is a zero yeah so for this I'm going to put it and for this one I'm going to put it all their loose yeah for example if at this point I have a zero so this line will be zero this line will be yellow yes let me go to the code Editor to finish the coding yeah for example this is a zero and here will always be this color of zeros foreign column set yeah for though and column set I'm going to Define to set and I'm going to define a low end column as RNC so this is the length of the Matrix and this is the length of the Matrix zero it's the column the length of the column I'm going to use for R in rinse R and for C in Ruins capitals say so if Matrix are say equal to zero I'm going to put it in my low and column set so close to the add this R and column through the add this is say after adding I'm going to use another loop yeah it's totally the same but I'm going to Loop through the set so for R in hello for saying column if this R equals to zero or column this is say equals to zero I'm going to set the Matrix are say equal to zero so this is the first method let me set if it works okay yeah so r e u and for saying column yeah I have to check from The Matrix I have to stack from The Matrix because for this one I didn't do anything I have to check from The Matrix so for Aryan reads R for say in read C if this r in my low set or let's say in my column set yeah I have to tack one by one then I can set Matrix RC to zero now let's set if it works yeah so this is idea is we put those and column index into the set and then we are going to Loop through the Matrix yeah if any index is inside low set or inside of the column set we're gonna set this Matrix R cell to zero now let me submit it to such if it really works yeah now let's try the third method I'm going to put it in constant place yes and only O M plus l space yeah and here is the O M plus and space yeah because I use a low Saturn column set but now I'm going to use a constant space so for the cost in the space I'm going to use the first row and First Column as ever yeah as ever agree for memorization of other points yeah I have to check if this First Column or first result and First Column if it has a zero or not because if it has a zero for example if it had for this one there is no zeros it means okay we can first yeah text the right result but what about for the first though yeah so this is the first to do and this is the first column it has zeros yeah and then I'm going to text what's inside yeah for example I'm going to put all these ones as a zeros but uh yeah but for my purpose I'm going to use the first result and First Column as my actual memory yeah actually it's not actual memory it is in place memory for the first result and false column that means I'm not going to use this 0 to text those or columns I'm only going to use something yeah some say below the first though and at the right side of the First Column because in that way I'm going to tag if there's any zeros and then I put it to the low end column I'm not going to use this two zeros this is why I have to set if there's zero or not because after that I'm going to set this zeros if there is zeros I'm going to set this first row to zero and this First Column to zero yeah no let's let me code it to tag if the solution is right yeah so basically it should be I'm going to check the so the row one has zero I'm going to set two variables and the column has zero so this should be pause yeah if it has zero I'm going to set it to 2 and then I'm going to use the RNC as the length of the Matrix and the length of Matrix 0 as the column and then I'm going to Loop through the column and rows and columns so for R in Ruins R and for saying ruins c as column so if Matrix RC equals to zero yeah so if I find a zero for example yeah this one or this one if I find a zero any yeah you can see any pictures if I find a zero so I'm going to in fact if it is uh if this is R equals to zero because if r equal to zero so the low one has a zero so equal to two yeah I'm going to select if this is c equal to zero so the column one has zero should be two this means the column has a zero yeah and then I'm going to put the values inside of the first row and First Column so it was somewhere like this one Matrix r c equal to zero so my Matrix are zero so the equal to zero and The Matrix say 0 say equal to zero yeah why I'm going to do that because for example if this is a zero I'm going to set this place as a zero and this place and as a zero yeah because for the next Loop I'm going to suck before this assessed in the sub place in these areas I'm going to attack yeah how can I tag I'm going to use this though and this column to start and then set all them to zeros yeah so in that way I will complete this question yeah now let me just to complete this part so this part will be for R in Ruins 1 2 r and for say in Ruins one two column so if this yeah if so I'm going to text so if the Matrix r0 equals to zero or Matrix zero C equal to zero this is my meaning if this one has a zero or here has a zero I'm going to set the row a column to zero so the Matrix are say equal to zero yeah so this part is very important and then I'm going to tag the final part if I didn't attack let me run it to do tag what's going to happen yeah as you can see the first case passed because the in the first image there's no zeros in the first row of First Column it is okay we're gonna start to finish it but what about the second one it is wrong yeah as you can see the second part is totally wrong so we have to check if the first row or First Column has a zero or not because this is because we've already used the first to do and First Column as ever memory yeah as other in place memory to solve the problem but if before there's not a it is not a zero after that we settle zero it may yeah it may cause problems let's say with the result yeah so you see what happened because here in this loop we're gonna start from this sub part yeah except the first row and First Column in the sub part we are going to type if there is any zeros so in the sub part we didn't yet in the third part with without some zeros it is 2 and 5 will be set to zero as you can see this one yeah this is the second law this one is zero and this one is zero but except that the first row and First Column we didn't set yet yes what should we do yeah we should attack if the first row has a zero all the First Column caps are zero if it has we're gonna set the first result o to zeros and then the First Column out to their Loops yeah now let me finish this part actually it should be quite easier yeah so this is a common sense because from the beginning we didn't use this part and after that we finished the all our operations we have to check the first to those and first columns yeah because before we didn't track that we have to stack all together because here if we only select the sub Matrix within the attack first row are first columns now we are going to set it how should we start so if first row one has zeros yeah if this is Row one there's a zero inside yeah it means this the one has a zeros what we're gonna do we're gonna put all columns in the one to zero so for say in range columns and the Matrix this are should be zero yeah because it's the first though this is zero C so they equal to zero similarly we need to circle the First Column so now let's check the First Column so if column one has zero yes so for example this one the column one has zero we are going to put its rows inside of this column to zero yeah so for R in Lewis capital r and here should be R and zero so we're gonna put this first column two there so yeah now let me run it to check if it really works some local one has a zero uh Row one column one did I do something wrong uh Row one low column yeah this should be call number one I'm going to Define column one yeah and column one now let me run it into that if it is okay yeah as you can see it works now let me submit it to tag if it can pass all the testing phases yeah as you can see it passed all the testing phases and it's pretty fast so thank you for watching if you think this is a helpful please like And subscribe I will upload the model called Problem success
|
Set Matrix Zeroes
|
set-matrix-zeroes
|
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution?
|
If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
|
Array,Hash Table,Matrix
|
Medium
|
289,2244,2259,2314
|
133 |
That's guys welcome to my channel in this video they are going to discuss playlist to problem number 133 clove husband solve question in the president new to our channel subscribe that they give no reference above no dinner connected and directed graph to please note The graph is connected native under its return of the day happy birthday to you for the original please give the video of the help of two to two playlist of the dress of the notes and western note special notice connected to a is Connected to be similar and disconnected to know what is the name of the island copy e that in case of ongoing copy do not no deduction odisha created with different memory address 1020 value set the self radhe krishna will never forget to death in the liver detox foods 98100 subscribe handed under to copy node value problem staff nurses staff noida 2010 new connection between you and not the different from obscurity to give this question on to interest in a graph condition value vitamin teacher type and the list of but Switch Off Merit List Play List Off Na Ok End Tak Hamare Is Andhe Simplicity 1512 All Subscribe Must Subscribe Thank You Or Relative Veer 1212 2383 Latest Vacancy In More And Not For Graphic End Subscribe That Exams Plated Off Like Point Mode On The Different People To 9 4 9 Do n't Forget To Subscribe And Subscribe That Bigg Boss Is Back President No Element President Hai Vinod And Examples For The Next To Subscribe To Main Secondary How To Make The Edge Between The New Note S Same s that they regret to correspond singh and jhajjar vini 210su graph in the way to go for this broken scandal minutes but let's question is they do it subscribe now to receive new updates date of the world in this connection between to right into its own when The battle-field subscribe to 200 now while celebrating its nod lets and visiting this one lets make you don't know you just not responding to all of the year old and New Delhi to is so amazing today happy kar point mintu this and also make inventory Flat Se Visit The Next Three Days And Making Responding Entry The Amazing Similar Video Channel for you The Amazing Shopping Apni But One By One Track See What It's OK Fast Forward And Doing His Travels Map 151 Do Ki Saugandh Old Once Ne Bigg Boss After 100 Years Old Ne Brar A New Breed Of Its Verdict Today Match Prediction For Venus Solve Vipin To Do And Know That's The List Of The Year 2 And Travels To-Do List Of 2 And Travels To-Do List Of 2 And Travels To-Do List Of Units Notification Updates List I Am Big Fan Of Will See And Smart And Take The New Entry Latest News Today Can We Do To The Defense Minister Of Wonders Picture We Entry Into All The Best Results For To Two Countries 123 Add New Notes For Rent Near Ones And Specially Solve Will Enter 251 To 302 323 325 One To Do Torch Light Happiness Or Another Edison C List And This Buffalo Is All The Best Friend That Similarly Vacancy Like Ka After Spreading Understood S Information Enables One To Show This Apps Connected To My Friend October Nurses Connected To Three Days Bane Apps For Pyun subscribe The Channel Please subscribe our That And Others Commerce step2 switch to step solve this problem and very nice and give vote subscribe to the Page if you liked The Video then subscribe to the Page आ Recommend यू ट्राइड टो मॉलस्ट अप्स एंड्रोडियो कॉर्ट यार्श फिल्स आ Recommend यू ट्राइड टो मॉलस्ट अप्स एंड्रोडियो कॉर्ट यार्श फिल्स आ Recommend यू ट्राइड टो मॉलस्ट अप्स एंड्रोडियो कॉर्ट यार्श फिल्स टॉव लैटर डे टॉव लैटर डे टॉव लैटर डे चेल्बरिया in long-term so add Yes and Subscribe Thank you all the way Me Unwanted Sorry Which Will Be Mapping The Old Not The New Note Making Borders of Notes Chapter Notes Limited To Create New Not Responding To Give You No Story To The Day 's Leader And Decency With That Is The Old Not Which Give 's Leader And Decency With That Is The Old Not Which Give 's Leader And Decency With That Is The Old Not Which Give Into Force And Value The Time You Not Regret And So The Continued With The Same Value Do It Or Not Appear Only Tools That I Tested Name WhatsApp Mix It Sign Up You For Bestie Post Initial Giver Not Slept With 900 Clients - 900 की With 900 Clients - 900 की With 900 Clients - 900 की ने मेटस क्यों से एंड पोट एक एजिनियल न्योट ने मेटस क्यों से एंड पोट एक एजिनियल न्योट ने मेटस क्यों से एंड पोट एक एजिनियल न्योट क्यों है क्यों हैं के क्यों है क्यों हैं के क्यों है क्यों हैं के अंधेरोन में का अंधेरोन में का अंधेरोन में का नाम तिलक हु एस नहीं इम्टी विहार टू नाम तिलक हु एस नहीं इम्टी विहार टू नाम तिलक हु एस नहीं इम्टी विहार टू रोम वैफ द नुव्वे नुव्वे नुव्वे front after removing रोम वैफ द नुव्वे नुव्वे नुव्वे front after removing रोम वैफ द नुव्वे नुव्वे नुव्वे front after removing list remove left side like this hai ya vihar to a guy a slap day The point of and to the no DPR popping out the front element members of the front element and me to the point of that you will reach the dev name or Bihar to traverse Saturday stomach and that hotstar that me Indian neer van are next rewards that the old course nibbles so S They Already Know The English Class 9 Beehive Chapter Note Amazing This Personality Ki Agar Aap Ki Bigg Boss Vapis Haq Hai Previous Song They Organization That Know The Prana Nodal All Its Neighbors Said Know The Giver Original Gram To The That's right from That's right from That's right from your off the old name just how to get the new notes knowledge and art to the new note number to the agency list of new note is next to a demon of Indian why not do it with all hands great end of India Rate hai how to download listen for a new note ki agar ko whatsapp facebook app a new note ajay ko ke sadis hua tha what they are doing but samudra note 100 from this edition se list burhanuddin processes and margiya president elect a paragraph in more retention key Problem Particular Not to Do Not to Subscribe to Channel To Do Required Express Can They Achieve This Avoid Using Why is this Software Different Now How to Post to Amazon to the President Not to Go to That Children Account is Account Top 10 220 That I Enemies Thing That Sugarcane Vihar I Have To PM Bihar This Is How To Make 10 Notes In The Not Get Process Is 128 To The Same Arrangement Top 10 A Sense Map Nurtured To The Why Rate Shift Boxer Not Right Shoulder And Honesty Is The Cockroach Anushtup Entries Not Appear In The Map of Media The Create This entry was posted in the that can't see how its resources are you at any step in the future but have not entered into all right the particular does not withdraw into the fort and don't like this the Effigy to children at all You are here right away you are already contagion entry light maps old to you already late evening element is red and chief minister should where is the means its processes and don't see the temperature in hotels and need any additional visible space in the traditional medicinal hubs and simple They do n't say anything, I was out of the loop in Bihar that the [ __ ] just return new graph return you that the [ __ ] just return new graph return you that the [ __ ] just return new graph return you begin is the newly created note crush morning to the given old song Vihar to return am of not forgive subscribe morning so let's tell a tweet time that Aap C Type Of Neighbors Night Ko Achhoot King Finally Summoned Hai To Were Not Handle Colonel KS Right Show Vihar To Like And Sewerage Bill So S Not A Personal Ki Mehndi Haathon Return ADrama Main Surat Hoon Ki Yeh Accepted So That's All For This Video Please Read and please subscribe to
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
217 |
okay guys let's solve 217 contains duplicate so we are given an integer array nums and we want to return true if any value appears at least twice in the array and we want to return false if every element is distinct okay so in the nums array of one 2 3 1 well clearly there is two ones and so a number appears at least twice one appears twice so we return true in this example 1 2 3 4 we have no duplicates and so we return false the way we'll solve this is by using something called a hash set and a hash set is great because to add elements to it add is O of one to take something out of it that's also o of one and to check if something is in the set it's also o of one so we go through the first number and we say is this in our hash set no it's not so we're going to put it in there we'll look at the next number and we say is this in the hash set no it's not okay we'll put it in there we'll look at three not in there four not in there either and then we see one and we say oh that's in the hash set so since that's already in there that means this is going to evaluate to true because there is a duplicate let's pretend for a moment that this one wasn't here so we got 1 2 3 4 we are then at the end of the array and from that we would be able to Output false because we got to the end of the array therefore there must be no duplicates so let's write our code we have a hash set which is going to be H and that's going to be just an empty set for now we'll go through for each num in nums we'll check if num is in h so if it's in the hash set we can immediately return true cuz there must be a duplicate otherwise what we want to do h. add num to put it into the hash set and if we get to the end of the loop we can simply return false cuz there must be no duplicates if we run that will give us correct and I hope that was helpful have a great day guys
|
Contains Duplicate
|
contains-duplicate
|
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
|
219,220
|
1,695 |
hey everybody this is larry this is me going with q2 of the weekly contest 220 lead code uh maximum erase eurasia value so hit the like button hit the subscribe button join me on discord let me know what you think about this farm and just in general i'm gonna go over my thought process as well as the solution during the contest um so i solved this during the contest um and yeah so the key thing to notice is that you know for these kind of problems well maybe the one of the first things that i would take a look at is just the constraints because if n is small enough then obviously you just do two for loops and square and that's like most naive way most straightforward way uh and that's fine right but in this case n is equals to 10 to the fifth a hundred thousand squares can be too slow for most computers um unless the test case is weak which is not something that you should rely on in general but yeah so we're trying to find a linear ish or n log n solution so for this the way that i did it was by a sliding window so the key thing to for sliding window is to just recognize that you know there's an invariant that you're trying to hold on to right so something that doesn't change something that as soon as you um and we'll go over my thought process even more but something that when you change it stays the same right and for this problem uh one key word for me is just noticing sub array and by only and only one sub array right so sub array is just a continuous um list inside an array if you will and because of that we know that this that we can move left and move right in a sort of way and that's basically um how i did it because um so basically the reason why this works is that okay if there's a subarray that satisfies these conditions meaning containing unique elements if you add one more unique element in that way that's always going to give you a bigger answer right well um and the key thing to also notice that all the numbers are positive to make that true um you may not notice that but um but if it has negative number then that condition is no longer true and the sliding window may be a little a lot trickier um so yeah so knowing that it's positive you always want to be greedy meaning that okay if you have a window of size k uh and k plus one is still unique then you wanna add on to it right and conversely um yeah if it no longer becomes unique you could just remove elements one at a time until it becomes unique again so those are basically the properties that we're looking for in sliding window uh during the contest i actually solved this in about two minutes uh because this actually comes up often in lead code to be honest i feel like a little bit less often in interviews but still a good thing to practice on because uh in variance and just this idea of this and looping variants are something that comes into play a lot in real life i mean a lot of it more trivial than this per se but it is something to kind of you know uh that helps you debug your code so all that said let's go over uh my code so that we can go over the logic together and in this case uh we use a set to kind of keep track of what's unique right so as we said the algorithm is just gonna be sliding windows so for me i always have a left pointer and a right pointer that goes from zero to n uh so when we so basically we just start at the point at the same place i'm using my hands so hopefully you see it i know that i'm not drawing on screen i don't have the technology apparently i'm on a 6eo laptop so that's my excuse i'm sticking to it but anyway so you have to start with the left point and the right point in the same place and then okay now you try to insert a number into the set right um meaning that okay now we want to expand the segment by one number uh or the window by one number right uh and now does this window still have unique numbers right well it will have unique numbers if um this number is unique if this number is unique then you're done if it's not then you have to keep on remove removing from the other side of the segment or the window until it is unique so that's basically my strategy and basically what i did is okay while this number like if this number is already in the existing segment we keep on removing it and also in this problem you're actually trying to get the score by taking the sum of the elements and because of this the sum of the elements uh every time you remove a number from the segment well you subtract that from the current total um and when you add an element to the segment or the window you add that to the total that's basically what i have here uh so every time so this is actually removing the left digit or the left number if it's already in there because it matches the right because we're going to add this we want to add this um number to the window but before that we have to add the last time we saw it first or we have to remove it first and then we also subtract that from the total and then we move the window to the left um and then after this is done the invariant that i talked about is that after this loop is done oops after this loop is done when we insert num subway this is guaranteed to be unique right um because that's just how the loop and rams go and then we can as a result add this to the total and then just take the best total so now you have a snapshot of a window so let's get the windows score and that's pretty much it and then we take the best of all the windows scores uh and that is how i solve q2 sliding window so what is the complexity of this algorithm let's for the sake of um you know doing this math let's say that the set operations are all one i know then certain languages that log in and i know that there's you know uh there are collusion issues with hash tables and stuff like that but let's just say that this is all one right if this is all one then what you may say oh they're two for loops right there's a while loop and a follow-up so this is n square why is a follow-up so this is n square why is a follow-up so this is n square why is this fast well actually that's one way to think about it and maybe if you want to analyze it that way sometimes people will say it's n squared but that but the other way to say um is that uh you could advertise that out because in a way if you look at each number well what can happen to each number instead of looking at just the loops you look at each number and each number well each number could be added once and also removed once right and that's it the number cannot be removed or add multiple times so in that case it is going to be o of one per element so and you have n elements obviously so it's going to be o of n which is linear time in terms of space well you know we have a set and in the worst case each element of the array is going to be in the set so it's going to be off and space as well um that's all i have for the uh complexity of this problem linear time linear space um and that's all i have for this problem really so feel free to hit the like button the subscribe button all that stuff and also you can now watch me solve it live during the contest really quickly i actually during the prom uh i solved this without recognizing the sum part i just thought it was the number of elements for some reason uh and then i had to hack that in real quick and actually still did it in about two minutes so you know so it's a short portion anyway check that out now bye-bye yes you got check that out now bye-bye yes you got check that out now bye-bye yes you got it one okay um is that right okay no that's not right what we want is a set oops um some of the elements okay uh hey thanks for uh watching this video explaining the problem uh let me know what you think ask questions because then i can answer them preemptively or join the discord uh hit the like button in the subscribe button as well that works and hopefully i'll see you again bye
|
Maximum Erasure Value
|
maximum-sum-obtained-of-any-permutation
|
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`.
**Example 1:**
**Input:** nums = \[4,2,4,5,6\]
**Output:** 17
**Explanation:** The optimal subarray here is \[2,4,5,6\].
**Example 2:**
**Input:** nums = \[5,2,1,2,5,2,1,2,5\]
**Output:** 8
**Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\].
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
|
Indexes with higher frequencies should be bound with larger values
|
Array,Greedy,Sorting,Prefix Sum
|
Medium
| null |
63 |
That hey guys welcome back to my channel in this video will go into solve unifil amit jeevan kya hai aapka admin to end de raha hai and it is said that you have a robot on the top left corner i.e. at 80 you have a robot on the top left corner i.e. at 80 you have a robot on the top left corner i.e. at 80 and this note is on your bottom right It is known at the corner where there is a star, he wants to grand that star and this is a robot, right here you can turn to the right and turn towards the right, okay and here it is also told that in this grade I have given 140 rupees to meet you, it is tomorrow and given space, now you can get up through the space only, now if you are worried, then your 5 minutes will be considered, okay, if you cannot pop out, then with this turn off. Now, how many such unique passes can you make? Take it till the bottom right corner to wish, you have to fold it five here, the problem is that it is the same, if it melts then it is fine from the unique point, both are similar. There is only slide difference here, so it has been turned off in Part-2 and there you have in Part-2 and there you have in Part-2 and there you have not been given any more chicken and without the festival, it was giving you total unique pile. Okay, that problem can be solved if you have installed it. If you have it or are doing it, then it will be easy for you to solve it, first of all, I have made a video of it, you should watch that video and understand it, because after understanding it, this problem will become very easy for you, so what have I done? I will tell you about many relationships here, it would be good if you watch your video, then I understand that both the problems are different, okay if you are telling here, then here you have kept my heart of Mintu Inch, whatever is here is the star here. It has to be brought till here, how many possible passes can be made? Okay, so it will do the possible profile, but what is the problem in this, it also has to block four from this corner to this corner, but it has given possible paths like this and the sticker. If you can frustrate the teacher then what will I do? I will have to just extract the video and send it here also. Now let us come to this problem, how can we give an example to the schools. Whatever happened in the previous problem, let me tell you what happened in that question according to it. How can we solve this problem according to that observation? So watch the video. If the quality is fine, it will be fine. I am telling you a little bit about the supports. Suppose you are a physical admit person then how do you solve it. Now. What is Giridih MP3 here, have you given MP3 or not? Now do also three and lengthens the. For example, let's go with the famous name. Okay, so take it here. We will check the manual, one by one. For, sir, if that corner of the results had actually existed, then we would have seen how much possible faith we could have had to go there. Okay, then they would have done the induction first, it would have been easier to understand, mother observation of when an object. It would be better to do this. Okay, so if you had a star here, you would have only one way. Now audio fixed height descent. If you had a CR here, then what do you have to do to reach here. A moment to reach here. The robot's mouth could be curd, so it is towards diet, so we can do it towards money, okay, so we will do it like a diet because if it goes towards the heart, now we will have to free it to come here, which is It is possible, otherwise, to come here, your face is that one, to come here, there is a star here, so it is not there to come here, no matter how big your column is, why is this? If the path was on the first road on this first column, then till here, there would always be only one stake state path, only one is ok, in this room i.e. there will be a problem for crops, there i.e. there will be a problem for crops, there i.e. there will be a problem for crops, there can be only one possible part in all, then here If it was so, then what would have happened to come here, now only one would have become towards Don because I can make our momentum like John, if you walk from here and say, we will do it, to even walk from here, we will have to do it like a flat which That is possible, otherwise why would you need to go here, then to push it towards the doll to drop it here, or it will not happen, okay, no matter how much we cry here, still the state moves towards the doll, now qawwali was going to happen. Now look, if I was from here for this, how possible would be the part I could have become one and two, here this two would have become, if it had been here, then Vansh would have become how to allow, you will do it best, look here, both of them have sworn to support these parties, so here But there should be support of both of them, for this the representative was not made tied, one to Om Shri is being made, now how famous can be learned by making a trick for this 1 ATrue MP3 Loot Gaya Ko Report Fold Hatha Hai The Sets Hai Na Pichola You should back it and use the warning that it is only free that this photo was fort a photo gone 5th and 6th then you are off that this is the first for the first Kolam, everything is possible for you, only one way is closed that is to become a pass. But if we look more specifically at the grid, we are filing the value as per the previous column in its previous form, Hindus swear by this, but what obstacle is given to us in this problem, so keep the obstacle in mind also. It will happen. Look, now let us come to this problem which is our today's problem. What did you see? Jesus has given you this option, you cannot use it later. Okay, this thing cannot be untouchable. Now let us come. What will we feel here? What will we do here? Suppose, if there was any worry here, then you tell me. Support here, I have kept my own, if the matters were inauspicious, then first of all we would have come from here to here. To come here, it would have been possible for us to go another kilometer back. To come here, there would have been a habitation. In this song, we are not separated from mother and you are the face, so to come here, let's say that we will keep crying and keep crying, then you could have come here. To come here in this row, in this form, you have to eat more food than in all the other columns, to come here, you have to go from here by doing it like this, but this is optional, that is, this brother-in-law is us and ours. It is not possible for this brother-in-law is us and ours. It is not possible for this brother-in-law is us and ours. It is not possible for it to be here no matter how long it is, because otherwise we do not have any way to come here, that is, everyone is a vegetable, okay, all of them are zero here, okay, now you understand, you are here too. If the tax had been optical, what would we have done in this condition, you could not even come here, after this, whatever happens, what happens to you, everything will be zero, okay, when we have this option in the grade, we will understand that in that path. No matter how much we feel that this Yo contract is not possible at first because it has already been run and is a chicken, then we cannot go ahead, it will happen here again, no matter what happens to the Gujjars, there will be electricity here, but this is our First of all know in the example, there is nothing like that, now don't worry, one is possible here too, Vansh here too, one here also, one is ok, now tell me what is the obstacle here for you and he If tomorrow is there, we can't come here. We can't kill him while you are hypocrites. Do you know that you can't help us? Well, now we can't go. Now what do we do first? If we both take an oath, then here we are. But not everyone will do it because it is Mario, then see, only here is your possibility, Africa when Rapchick returns, not tomorrow, if there is an option, then definitely know, now keep it zero in DP, then after this, see whether your Jio is this space here. There is money, both of them will swear that there will be one right here, okay there will be one, then you will come here, this is the time of these two, together in 101, then one, swear because it is zero, now there is no worry, otherwise what will be connected there, then it will go. What is our answer? So you understand that whenever there is an obstacle, we will accept it. Earlier we used to slide it, before novel, we will check that there is no infection anywhere in this one, here, then you will find the heart line here. But there is no forest anywhere in this row and in this column. If there is, then what should we do? After that we will not be worthy of this place, after that we will not be worthy of this place, we will move away from there. But we can do Mohini size, okay, apart from this, when we start seeing all this for this, whatever happens from here, all these problems have happened, from here till here, we will see for this, you will also check whether there is an option or not, now it is okay. They will give her death. Okay, on the other hand, understand that they were doing this. There is a serious problem. These two swear that they will add the shankar of the previous row press problem. If you guys do sexual intercourse here, then what is this? Yes, if you cry, then you will meet her according to the point. Okay, so you understand both the differences, what we are going to do, in the first code, we are going to change this number slightly. Okay, here you will remove the more end, obstacle has also been given, find the measurement, also removed the row, we have already removed it. But amitphysique, first change it to 10, is it already there, is it there from where it starts, is there an option on the same side, is there a color button on that side, you will cry, on the other hand, see where you have to reach, here you have to reach here. But we have to reach here, is it optical? Is there an option there? I am going to do the button zero. Priyanka will do the DP. The deputy director is taking the Mi*. We are going to take the balance of these. is taking the Mi*. We are going to take the balance of these. is taking the Mi*. We are going to take the balance of these. First, we will check the space if there will be a hostel. What will we do if there is zero muscle mass in seed sowing? We will make one straight stitch in it and if we find it anywhere, we will smoke it. Okay, we will back it up. You are already a vector, so by default it is definitely there, okay. If it is zero, then you will back it. Next, the size of all this is going to be fine. Similarly, you will see that diameter for the column. For reader volume, the first thing you will do is if it is zero, then that too, as soon as you know, press it from the inside because Arya. Social value is going to be forced because the film cannot go, okay we have sliced the first toe enforce okay we have sliced the first toe enforce okay we have sliced the first toe enforce problem, what will we do after that, we will see in future, when Bhim Rawal will be there, this will be an obstacle, then GDP is back cutting, we will grow, otherwise we will say. Have plus 2 and fever will do the time of schools, will do the same, will do the final which is ulcer disease - 1m - on the wall, then final which is ulcer disease - 1m - on the wall, then final which is ulcer disease - 1m - on the wall, then I will go to the answer final in it and do this ritual, do the problem, it is here, let's submit, what should I do now, the one with unique pass Look at what I have given below, then you will understand very well. Okay, thank you.
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
1,996 |
late code 1996 the number of weak characters in the game you are playing a game that contains multiple characters and each of the characters has two main properties attack and defense you are given a 2d integer array properties the properties of i is equal to attack i defense i represents the properties of the eight charact character in the game a character is said to be weak if any other character has both attack and defense level strictly greater than this character attack and defense level more formally a character i is said to be weak if there exists another character j where attack j greater than attack i and the defense j greater than defense i so return the number of v characters so uh we are given some properties of some characters in a game and this properties represents two values attack or defense so properties of i denotes attack of that particular character and also the defense of that particular character and it is a 2d integer array now we need to find whether a character is weak we need to count the number of weak characters so a character is said to be weak if the attack level and the defense level is less than another characters both attack and defense level so suppose we are having a character a here and we are having another character b and this is having an attacking level say 100 and b is having a defensive uh and a is also having a defensive uh property of say 150 just two values now b is having attacking level of just 10 and this is for attacking so b is having an attacking level of just 10 and it is having a different c level of just one say 100 so when we look at this the attacking level of a is 100 and this is greater than the attacking level of b now uh as well as just uh looking just the attacking level we also just check the defense level so defensive level of a is 150 and attacking level uh defensive level of b is 100 and 150 is also greater than 100 so both the attacking level and deficiency level of character a is greater than the attacking level and defensive level of character b so b is said to be weak so b will be weak so uh now so this is what actually we need to find we need to how many number of we character we characters will be there so if there is some other character say c with an attacking of say just five and defensive of just nine and this is also another weak character b is a v character because it is having a lesser attacking and defensive power than a and c is also a weak character and it is also having a lesser uh attacking difference than a and b so this is another weak so if we are given something like this as an input then the answer will be 2. now let's get into the input here 5 6 3 6 so let's take that so 5 6 3 6 so let's have a three players a and we have another player b and we have another player c and a is having an attacking level of 5 and a is having a difference level of 5. now b is having an attacking level of six and b is having a defensive level of three now c is having an attacking level of three and c is having a difference level of six now uh let's compare a and b as attacking power is five b is attacking fire power is six so attacking power of b is greater than five but we when we check with the defensive power of a is greater than five so we cannot say this that is a weak one uh with respect to b we can also just check with c so we check whether uh is uh attacking power is greater than c so if we check that phi is greater than three with respect to three let's see a character c it's uh attacking power is just three it's having five but uh when we check with the uh defensive power this is having six this is only having five so uh c is greater so with respect to a and c while comparing asc we cannot just find a character which is weak now we can also just take with b and c here b is having greater attacking power but b is having lesser defensive power than c so from this example we can we will not find any weak character either one is good in attacking otherwise the other one will be good in defensing so here the answer will come out to be zero and uh the brute force approach is just checking each and every uh characters uh with one another uh along with its attacking and defensive so the complexity will be big of n square so where n is the total number of characters so we need to compare uh with every combinations of the characters now let's check with the other example let's take this example 1 5 so let's check this example so here also we are having three characters here we have a character we have a b character we have another character c and a is having a taking power of 1 difference the power of 5 b is having a taking power of 10 and difference the power of 4. c is having an attacking power of 4 and defends the power of 3. so when we compare n b a is having lesser attacking power but a is having greater defensive power so uh we cannot uh get into a conclusion uh like which one is a weak we cannot find one now uh we can compare and see when we compare a and c is having greater attacking power but a is having greater defensive power so with respect to a and c uh again we cannot find any weak character now let's compare b and c now let's when we compare b and c we can see the attacking power of b is 10 which is it is greater than this four so a b is having greater attacking power now as well as when we check with the uh defensive power 4 is greater than 3 so here when we take these two examples both the attacking power of a and defensive power of b is greater than c so c is weak so here this is a weak uh character that we are looking for so here we will return one so when we compare every combinations we need to do big o of n square times now is there any better approach uh for most of the problems when we see like this ranges in a 2d array we can just think of sorting based on the attacking array uh or the sorting based on the defense c1 when we sort here what we need to do means here we can sort the character based on attacking power in decreasing order so when we sort the characters based on the decreasing order we will get 10 comma 4 then we will get 4 comma 3 then we will get 1 comma 5 now we already checked the attacking power because we sorted it already so the second characters uh attacking power will surely be less than the previous ones same way the third character's attacking power will be less than the previous ones now we just need to check for this one just that defensive power so we can just look for 4 and 3 we find that 4 is greater than 3 and we already know that 10 is greater than 4 the attacking power is greater now we just need to care about the uh defensive power so 4 is greater than 3 so we can increment the count by 1. now what if this were also 10 so when this was also 10 here we sorted based on the decreasing order like decreasing order of the attacking power but here we have two equal attacking powers when we have equal attacking power condition we need to sort based on increasing order of defensive power so when we do that we get 10 comma 3 first then 10 comma 4 then 1 comma 5. you get 1 comma 5. so in this case there will not be any weak character here the answer will be 0 so this is the condition that we need to do that is when we need to sort the given 2d array based on the decreasing order of the attacking power and then in some conditions the attacking power will be same and at that condition we need to sort based on the increasing order of the defensive power now after doing that we can just compare the defensive power and calculate the count so this is what we actually need to do so let's try to implement so if our uh already given properties is equally equal to null or properties dot length is zero just a pre-check pre-check pre-check there is no uh properties array we can just zero if we can just uh didn't consider this because it's already given the length will be from 2 but we can just again check for that and we can just say less than or equal to for one also there will be only just one element so there will not be any minimum now we need to sort based on attacking power in descending order when attacking power is equal sort based on increasing order of defensive power so that's our formula here so let's have the length how many candidates so we can say how many character in the characters it will be property dot length now we need to sort arrays dot sort of properties just doing this arrays dot sort of properties will not do the trick we need to add a custom comparator and in java it can be easily done using the lambda function so here uh from this property studio array we will be getting two property let's say call it property one and property two and property one of zero means attacking power property one uh let me write it here property one of zero means attacking of attacking and uh property one of one means defensive same way property 2 of 0 means attacking and property 2 of 1 means defensive so from this properties we have applied lambda function so we will get two property one property two uh when we will be comparing these two and how uh this is a small uh syntax error from here we need to pause so when uh we are making the attacking power in descending order when the attacking powers are not equal so when property 1 of 0 is not equal to property 2 of 0 so when they are not equal then the ternary operator then we will be doing the decreasing order with property one of zero otherwise it may be equal if it become equal we need to sort based on the increasing order of the defensive power so integer dot compare of property one of 1 comma property 2 of 1 so now the arrays will be sorted so if this is our array so if this is our input after uh doing this sort operation uh this will be rearranged as 10 comma 4 comma 3 and one comma five now if we have any uh equal elements as i explained earlier like if we are if we have another 10 here then we are making uh then the it will be arranged based on the increasing order of the defensive power so it will be 1 comma 3 first 10 comma 3 first then 10 comma 4 then 1 comma 5 so like this now um so now we sorted so now uh we sorted based on the attacking power so the attacking power of the first character will be larger than the second and it will be larger than the third like that so now we just need to care about the defensive power so let's say int minimum defensive power equal to a small value let it be integer dot mean value now let's take the weak count which is equal to zero now we just goes through each and every uh each and every character inside the properties array and we just check if the minimum defensive power is a number of weak characters if the minimum defensive power is greater than property of one so at that time we just increment the v count and we will be updating the minimum defensive power with the maximum value now we can just uh return the weak count at last and this will be the answer okay yeah it's a typo i need to put the colon here instead of the question mark is that's the ternary part this is the true condition so in ternary we will put the condition and after the question mark it will be true and after the quality will be the else part so let's uh test with all the test cases so the sample test cases are passed let's submit it okay so here uh the time complexity here we are doing uh sorting so big o of n log in and here we are going through each and every character so here it will be big o of n so big o of n log n plus big of n big o of n log n plus e n so it's big o of n log n and uh in case of space complexity it's uh since here we use the quicksort this rs.sort internally uses quicksort this rs.sort internally uses quicksort this rs.sort internally uses quicksort and quicksort uses a space complexity big of log n so space complexity will be bigger flow again the
|
The Number of Weak Characters in the Game
|
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
|
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105`
|
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,042 |
Hello friends, welcome to things light, today I have come with three leader questions for you, the best part is that all 23 questions are relative flowers, yes all your questions are related to which, since today is a rose day, so I am especially this Collect three problem sets which I will tell in today's video. Basically in today's video I will show you only one problem but I will give homework to two problems. If you are not able to make questions then what will I do next day when I am next Begum you mean which I When I upload a video, I will cover the same problem, so you must write in the comment section and tell me if you made both of them successful, then don't be too lax, I will start asking a question, see, before telling the question, I want to tell you something. I have given a lot of platform in this YouTube channel which brought you when you turn school in new model school which will give you fresh soil which helps in the next Newton School's favorite is about to start, you will get the link in the description, you click on it. After doing one big thing, that must be done, let me start telling him that if there is a question then there is a question right there that you will have something in an open garden then I will tell you every day because of the lack of garden it is very interesting. Do you subscribe? What do we have to do, what do we have to choose, Chanakya, what should we do between the two Patans, this is the garden, this is blue, this is this stop, this will not work, this is white, this is what Gurus means, there will be two home guards investment, its color should not change, we have to do that. Well, for this, let me tell you the best way for this, before telling everything, see this, it is guaranteed and suggest you take this point, then you will have to face the answer of my video, then when the answer is there, then I will not be a symbol. What should I do? Now that the factor has been created, you can see that here I have taken this vector as two back way through which the graph is created. This graph has been created from the list presentation but - that is because I am but - that is because I am but - that is because I am taking Jio indexing. So you can see here line number six to line number nine will make gram plus I am a back Italy which will give us red which camera answer will be better incident will give that planet which color flower fair which tomorrow coat will get then what Now what do I do, I offer these flowers, I run this zero train, I go back and have a garden, after that, I simple color, because this is a rally of color, macrame, small time, just like this, let's make it beating at the hands of bullion time, as if it is What should I do in that, if we have signed anything potato, anything color, its adjustment of life is, I have marked it just like people used to respect in the graph, as if let's assume that I am on this road right now and I Its names were the people who were its Edison notes, one of them was a married woman from the blue countries because they will use only four flowers 20123, this is how you believe, okay so now I have zero, let's go to 12345, okay, now whatever you believe means. It does n't matter what we consider to be on, it was zero want toe, so here I see what is there, I come on man, what water am I, don't run it at all, you are the one on whom I am running it in the pictures. It is not being assumed, okay, so zero - here you are assuming that - here you are assuming that - here you are assuming that we have 1234 monitor light, okay, after this, what do we have to do? Now look here, let's assume that we assume that This blue and this of ours which is white, in late, when this is the first, this is not white, this is blue in this is white, then we used to say white and blue, which I assume to be white, I second this number, what is the height, this is the third number, what is blue? Then the third number is Bablu, so I hit one on this side, so now what train do I have for Red to hit this number so that he can automatically call this option? Okay, so now what do I do here? Now I have one more thing here, see what is being said here that all the best for them into living helps, meaning this will be our password option, then the meaning of doing will be one more here which will be this boy, so we will have this second one. There is an option, if you do this then it will settle down. There is an option here to turn off the water, as if you turn it off, then you have to finalize everything by doing this. Now I have this question here. If there is a question, then this should be done. I asked this question. It means that it is online and it was asked here. This question is definitely a very good question. Thank you, if you have problem in this, simple block Google Agro and 2019 Rose Garden, now you will Google it and you will understand which question it is. It's a very good question, if there is any problem in it, then write in the comment section and tell me, I will make a video on it, sorry for that sailboats video, thanks oh thank you so much and if you want to celebrate every day, then celebrate every day like this. Day, if you all want to add five questions related to flowers, then free questions, so I told you two questions, come find the flower, both of them can become so big when these erode Tamil Nadu Yoga, but you have to make five questions, only then this field staff and meaning of yours. There is a live saturday definition but this is my definition ok sir that's all sizes for 5th
|
Flower Planting With No Adjacent
|
minimum-cost-to-merge-stones
|
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._
**Example 1:**
**Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** \[1,2,3\]
**Explanation:**
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\].
**Example 2:**
**Input:** n = 4, paths = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,1,2\]
**Example 3:**
**Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= n <= 104`
* `0 <= paths.length <= 2 * 104`
* `paths[i].length == 2`
* `1 <= xi, yi <= n`
* `xi != yi`
* Every garden has **at most 3** paths coming into or leaving it.
| null |
Array,Dynamic Programming
|
Hard
|
312,1126
|
383 |
hello everyone so in this video we will be uh doing lead code problem number 383 which is Ransom note so we are given two strings one of them is Ransom note another one is magazine so we will be returning true if Ransom note can be constructed by using the letters from the magazine that means that whatever letters we have in magazine a random note should be a subset of those letters for example here we have got a B so our random node needs to be a subset then it uh then only we can return true so we have to construct a string Ransom node from another string magazine how we can do that is by using a hash map so we will keep a count of the letters and Ransom note and we will also keep a count of the letters and magazine and then we will check if the letters in Ransom node is the is a subset of the letters in magazine so let's go on delete code and check that so to execute that first we can do is we can keep account of our Ransom note count of the letters and then we will also keep a count of the letters in our magazine by using the inbuilt when that is counter now we will check if string one and string two the letters in string 1 and string two are equal to our string one so if they are equal then we will be returning true else we will just return false we will run this yeah so that is pretty much it so this is how we do uh like we execute a ransom node and thank you for watching this video I'll see you in the next one
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
367 |
hey what's up uh welcome to another easy liquid question today we're going to solve lee code 367 valid perfect square uh this is going to be a very short one you're given a number and you should check whether that number is a valid perfect square so how do we solve this question well first of all what exactly is a perfect square so a perfect square is a number that's equal to the square of another number that's either less than or equal to the perfect square we can solve this question by iterating through values less than the perfect square and then multiplying those values by themselves to see if any one of those answers would be equal to the perfect square we can use linear search to do that but that wouldn't be optimal since the sequence of values that are less than the perfect square are inserted order so we can use binary search that would be a much faster and much more optimal approach so we're going to use binary research to do that so i have illustrated a number line here to help you visualize the process so what we're going to do is we're going to iterate through the values less than the perfect square and we're going to find the middle element we're going to find the median value and then we multiply that median value by itself and depending on whether the answer we get is larger or smaller than the perfect square the potential perfect square then uh we can either move to the right of the number line or to the left of the number line so we have a number here 16 and then we should determine whether 16 is a perfect square so we're going to use two pointers a left pointer and a right pointer i'm going to put them here left pointer is pointing to 1 and right pointer is pointing to 16. and then based on those two values we find the middle element and then we're going to find the middle element to be 8 that's the median value now that we're at 8 we can then multiply 8 by itself to see whether the answer equals 16. so we do 8 times 8 and that would be 64 and that would not be equal to 16 but then the answer that we get when we multiply 8 by itself is greater than 16 which means the number that we're actually looking for should be less than 8. so we move on to search on the left side of the number line because we know that we're going to find smaller numbers so we move the right pointer to the median index which is 8 and then we calculate a new median index and that would be 4. and we do the same thing we multiply 4 by itself to see whether the answer is equal to 16 in this case it is so it means that um 16 is a valid perfect square so how do we know that the value is in a valid perfect square let's say we had something like 14 right so if we had something like 14 we would finish iterating through on the values less than 14 and we wouldn't find any value which when multiplied by itself equals 14 so then we know that 14 isn't a valid perfect square so that's how you solve this question and i feel like these are questions that you're only going to get in the phone screen so it's good to brush up on those scales too so what's the time and space complexity of this algorithm well for time complexity uh it's going to be o log of n since we're using binary search so time complexity is o of log of n since we're eliminating half the elements every time so at first we had 16 elements to go through then we had eight elements to go through and then we had four elements to go through so we're eliminating half the elements every time so it's all vlog event actually since computers run in base 2 this would technically be o of log to the base 2 of n and if you want to go in depth in the interview to explain why um this runs in um oil vlog event time stick around for a few minutes or if not you can fast forward to the code so log to the base 2 of n actually means 2 raised to some number let's say x would be equal to n that's how it reads in exponent form so their total of n elements here we already know that n is 16 so that would be 2 to the power x would be equal to 16 and then this would definitely be 4. so 2 to the power 4 is 16 and then in the next iteration would be 2 to the power 3 and that would be what 8 you guessed it and then 2 to the power 2 would be 4. so as you can see we're eliminating half the total number of elements that we have to go through every single time roughly half every single time we make a computation so that's why binary search runs in log event time so that's it now for space complexity is o one since we're doing everything in place so let's dive into the code for this question alrighty so the first thing we're going to do is to declare the two pointers that we're going to use that's the left pointer initialize it to one and then we declare the right pointer initialize it to number and then we're going to loop through the values less than that number in a binary search way to determine whether this number is a perfect square so we do while um right minus left is greater than one so if it simply means that while the value of the left pointer is less than the value of the right pointer it means that we haven't gone through all the numbers in this loop which means that we can still continue doing computations in this loop otherwise we're going to break out of this loop so while we're here we can calculate the median value so that would be integer need would be left plus right minus left over two so this would give us the median value and now we need to multiply the median value by itself to see what answer we get so we say if meat multiplied by mid is equal to the number jack but this is a perfect square so we just return true else if need multiplied by made is less than the number it means that we're looking for something bigger so we search on the right side of the array so we can just set left to be mid and then otherwise if meat multiplied by meat is greater than the number it means that i think we don't even need to calculate that it means that we're looking for a number that's smaller so we have to look on the left side of the array so we set the right corner to be equal to the median value and if we've gone through all of this and we did not find a number which when multiplied by itself equals the perfect square we can just return false that should be it i think we have to take care of a few edge cases uh in cases where we might have numbers that are like one or two we already know that those are perfect squares so we can just say if num is less than two we just return true now you might want to clarify this with your interviewer to see whether you're going to get negative numbers or something like that and that's something you might do to strike a conversation with your interviewer so that's pretty much it for this question let's run this and see what happens uh there should be an if here i always make mistakes all right it's uh accepted let's submit this hopefully it's successful alrighty so for some reason it did not work let me try to debug this so if we change the data type of the median value to be long and then we typecast all typecasted to integer when we are assigning the left and right pointers to it that could work now let's submit this and yeah i think that was a problem i am not really sure why i feel like it's because we do have um huge constraints on the values of the numbers that we're gonna get so uh yeah so that's how you solve this question if you like this type of content please consider subscribing to the channel comment down below if you have something to say and smash the like button for the youtube algorithm and share this video around the community and i'll see you in the next one bye you
|
Valid Perfect Square
|
valid-perfect-square
|
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.
A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as `sqrt`.
**Example 1:**
**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.
**Example 2:**
**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
**Constraints:**
* `1 <= num <= 231 - 1`
| null |
Math,Binary Search
|
Easy
|
69,633
|
22 |
hello everybody and welcome to another episode of your favorite algorithm Channel today we're going to be doing leak code 20 to generate parentheses so this is the second parentheses problem we've seen we had just recently done valve indices so we understand what a valid string of parentheses is and what the nesting rules are so I won't go into that in too much detail but let's introduce the problem real quick given n pairs of parentheses write a function to generate all combinations of well-formed generate all combinations of well-formed generate all combinations of well-formed parentheses for example given N equals 3 a solution set is and then we have these 5 results so these are all the possible combinations of valid parentheses so N equals 3 well that just means that we have 3 closing prints and three open friends at our disposal and we have to use all of them so what I'd like to say about this problem before we get started is the code for this problem is actually not it's not very complicated this is more of kind of a logic problem so I suggest when you are trying to solve this problem just come up what are the set of rules that need to be followed to construct a valid set of parentheses if you can come up with a set of rules that form a well formed string of parenthesis then you have everything you need to write this function like always go ahead and try to solve the problem first if you get stuck or you just want to see how I solved it then check out the video otherwise if you're ready to get started come with me to the white board on the screen here I have N equals three and we have three opening prints to work with and three closing friends so what I want to talk about is a set of rules for ourselves that we can come up with to construct our string of six characters or our valid set of prints what are the rules that we have to follow to construct the string if we can come up with the rules to construct the string then we have written our function essentially we have written our function so let's say we're starting out with an empty string well what can we add we can't add a closing kren right because no matter what we add after this closing paren this string will be invalid right because if we add no matter what we add after this well there's our last character it can't be valid because we're closing something off that doesn't have an open and opening counterpart to it so that's invalid and likewise if we had so we have to add a closing print if our string is in right we have to start or sorry not a closing print an opening print so we have to start with an opening print in our string so that's the first thing that we can take out of this but also if we have added an opening print we can do one of two things right we can add another opening paren or we can close it right but what we can't do is we can't then add another closing print and why can't we do that well because no matter what we add after this point if we have added more closing prints than we have opening prints - to prints than we have opening prints - to prints than we have opening prints - to match up with them then no matter what we add after this our string will be invalid so the first bit of information that we can take in our function for constructing our string is that at any given point in time the number of opening prints that we have must be greater than or equal to the number of closing prints that we have so that's the first rule that we know that we have to follow when we're writing our functions and that's something we can be sure to follow well while we're constructing our function well what's another bit of information that's really important that we can take out of this or through our reasoning right so let's say that we're following this number one rule here right so we're adding an opening print and we're adding a closing / in which means we can either a closing / in which means we can either a closing / in which means we can either add another add a closing print or we can add another opening print right so we'll go ahead and add a closing print and now let's add another opening print well what do we know now right so we have added how many opening parens well we've added one two three opening parens right following this number one rule here saying that we can't ever add a closing parenthesis or unless there are more opening parens right and here we can see that we've exhausted our number of opening prints at our disposal so now we know that the only thing we can add is a closing parental here is stating that our opening prints must be at any given point in time greater than or equal to a closing print we cannot add a closing parenthesis also but the second thing we know is that if our if we have added all of our clothes or our opening parens then we need to add we can only add closing prints right so if the number of closing well let me write it in an expression that's going to be a little bit better so let's say that our opening parens have to be less than or equal to at any given point in time and right so these are the two rules that we have to follow to construct the string well how do we know when we're done constructing this string right well that's simple right N equals three we have three opening prints and three closing parens so we know we're done constructing our string so our final rule is when the string length is equal to six right or we can say two times n right so if our string length is equal to two times n then we're done and we can store that valid string if we follow these three rules then we should be able to construct our valid strings and now we just need to be sure that we're not duplicating them now there are two strategies we can use to solve this problem we can do this in a depth first fashion or we can do this in a breadth first fashion now I'm going to choose to do this in a depth first fashion because it's more space efficient and the reason why it's more space efficient is because as you can see with these two rules we need to keep track of how many open prints and how many closing parens we're using in our string so that we know what we can add or what's a valid ad what's the next or what is a valid character to add and our next index in the string so if we're keeping track of all of our opening and all of our closing parens in a breadth-first fashion we have to keep breadth-first fashion we have to keep breadth-first fashion we have to keep track of a set or we have to keep track of what it has been about how many opens we have used for every string whereas if we do this in a depth-first fashion we do this in a depth-first fashion we do this in a depth-first fashion we only have to do this for a given string right so that is going to be more space efficient because we only have to keep our we only have to use of space at the call stack of size of n right a size the size of the string whereas if we doing a breadth-first whereas if we doing a breadth-first whereas if we doing a breadth-first fashion we have to do it in terms of the size of our answers or the number of answers which is going to be greater than the length of the string inmate and I think in all cases somebody could prove me wrong out there but I think in all cases at least in most cases so now that we have an idea the logic we're going to use to solve this problem let's just go through an example of what the function looks like I'm going to show you what the function looks like and then we'll just see how it executes so now that we have discussed our rules for generating our valid combinations of parentheses I've gone ahead and done something I don't normally do I've just thrown the code up on the screen so this is basically the code we're going to use to solve this problem in fact this is I mean it's pretty much exactly the code we're going to use to solve this problem I've kind of pseudo coded it a little bit and what can we do in this function well the first thing we can do is we can check the see is our string it's our string the length of n times 2 if it is then if we follow our rules we know we have generated a valid string so we're going to push it into our right the second thing that we can do is if our opens if our open prints are less than n then we want to add another open print to our string if our closing friends are less than our open prints then we know we can go ahead and add a closing print two to our string now the reason why I have thrown this code up on the screen is because we're going to be solving this in a depth first recursive way and I know you could ninjas out there like hey recursion no big deal but us code karate kids we gotta do our wax on wax off we gotta stay on the floor and we got to understand how this code is actually running so how we're gonna do that is we're going to track the call stack we're going to track the execution line in our code and we're also going to keep track of our answers in the array down here and we're going to be building the tree that this code creates at the same time as we're tracking the code that's running so strap yourselves in it's going to be a little bit of a long ride if you're not interested in learning about recursion or how this recursive function works then you can just look at the code and type this in and probably get the right answer but I thought it would be beneficial to just kind of go through how this code is right so the first thing we're going to do is going to push a call to Jen friend with an empty string onto our staff and we'll move on to the next line and our opens our lesson in so we're going to push another call Jen print onto our stack with one open print we'll do that in our tree as well and because we are going into the execution of another call Jen friend we're going to start back at line one we're going to check the string it's not n times two and we still have open friends let's use our open friends and not listen and so we'll push another call with to open prints onto our stack and we'll represent that in our tree and we'll go into the execution of this function we will check our string it's not any x tube we'll move on to the next line opens our lesson n so we'll push another call to open front to Gen trends with three open prints onto our stack and we'll go into the execution of this code our string is still not in x to our opens are now equal to n so we cannot add any more open friends so we'll move on to the next line our closes are less than our opens so we can push a call to Gen Tran with an O with a closing prayer in a de to our string onto the stack and we'll go into the execution context of this function starting back at line 1 our string us not the right length our opens our equal to end so we can add another one our closes we still have some left to use because there we there are less than our opens so we can push a call to Jenn friend with another open closing paren to our string onto our stack and one to the execution of this function our opens are equal to n still our closes are still less than our open so we'll add another one pushing that onto our stack and will enter the execution of this function call so now our string is of length n times 2 so we can push into our answers array our about our valid string of parenthesis so we'll add that to our array our opens are still equal to end our closes are not equal to our open so we cannot add any more and we're going to return from this function called popping this off the stack and now we're going to enter back into the execution context of what is ever on top of our stack and where were we in our lat at what line of code were we in when we last for in this execution context when you're last in this function call well if we look at our tree over here we can see that this is the string that we generated at this point in time and when we called Jen paren from this execution context we added a closing parameter n-- to that added a closing parameter n-- to that added a closing parameter n-- to that line in our function call so we'll return to that line and then we'll move on to the next line of code in that execution context and we will return from that function called popping it off the stack and we'll check to see again where were we well are we were on in this function called now on top of our stack we were right here in the tree we added a closing trend so we'll return to that line popping that off the stack and we'll do the same for the next function call popping this off the stack as well because we added another closing friend so we'll pop that off the stack and when we back up our tree so now we are here in our tree where we have two closing - in our tree where we have two closing - in our tree where we have two closing - opening parens and now we can enter back into the execution line that we were on in this function call well we were adding a closed opening print so now we're going to move on to the next line of code where we are going to now check to see if we can add an opening an open or a closing print so we can so we'll do that pushing that onto our stack and will enter the execution of this function call our string it's not the right length our opens are two so we can add another one of those we'll push that onto the stack and we'll enter into that function call our string South right length R opens in a three so we can't add another one our closes are less than our opens so we'll go ahead and add one of those pushing that onto our stack and will enter the execution of that code our strings not the right length our opens our three our closes are still less than or open so we'll push another call to that onto our stack and now our string we have reached another leaf right so we're going depth first we reach the bottom of our tree again our string is the right length and times two so we'll push that into our answers alright we'll go to the next line of code we can't add any more friends so we'll skip through all this and we'll return from this popping it off the stack and we'll return to this function call here and you can see where we were last time we were here we were adding an a closing friend so we'll move to the next line of code and we'll pop that off the stack and where were we in this function call well we were adding another closing paren so we'll move to the next line of code and we'll pop that off the stack and where were we here with our string that looks like this well we were right here and what were we doing last time we were in the execution context of this function called well we were adding another opening print so we want to return to that line of code or that line in our code and we want to move to the next line our closes our lesson are open so we can add another one of those we'll push that onto the stack em onto the execution of that code okay our opens our lesson in so we'll add another one of those pushing that onto our stack and will enter the execution in this function call our string us to not the right length our opens are now three so we'll move on to our closes we can close this one off so we will push a call to that onto the stack and we have terminated again and another leaf and we'll see that our string length is n times two so we'll push that in for answers array and we'll move to the next line we can't add anymore so we'll go all the way down and we will return from this called popping it off the stack looking where we were and our last function call will return to that line and then we'll go to the next line popping that off the stack and then we'll look where we were in our last function call here or a string looked like this we were here so we were adding an opening friend so we'll move to the next line and we'll check to see if we can add another closing friend we cannot so we'll return from this call and why couldn't we add a closing friend here well because our closing friends in this execution in the execution context of this function call our string has two opening prints and two closing friends so we can't it does not satisfy this if statement so we move on to the next line and we pop it off the stack so now we return to where our string looks like this two closes and our two opens and one closing print and where were we well we were right here and what did we just do well we had just added a closing print so we return to that line and then we'll go to the next line of code which is to return from this function call and pop it off the stack and now back up to where we have to closing prints so now we have two closing friends what was the last thing we did well we added or now we have two opening prints what was the last thing we did we added a closing friend so we returned to that line and then we'll go to the next line of code and we'll pop that off the stack so now we're all the way back up to the top of our tree so we had already explored the branch where we start with adding opening prints and now we'll explore the their side so we'll go to the next line of code and we'll add a closing / in of code and we'll add a closing / in of code and we'll add a closing / in we'll push that onto the stack and will enter the execution of this function call our string is not the right length our opens are less than n so we will push that onto the stack our string is still not the right length we still have opens left to use so we'll push that onto the stack and will enter the execution of this function call our string is still not n times 2 so we'll move on our opens are now equal to n so we can't add anymore so we move on to the next line we can now add a closing parenthesis on the right line our opens are all used we can add another close so we'll push that onto the stack and now we've terminated again in another leaf node so our string length is n times 2 so we will push that into our answers array and we'll move through our lines of code because we can't add anymore friends popping that off the stack and will return to where we were when we were last in this execution context of this function and then we'll move to the next line talking this off the stack and we'll do the same for all of these function calls until we get to this point here so we last left off that was right here and we just added an opening for n so we'll move on to the next line of code which is to add a closing friend we can do that so we'll push that onto the sack and we'll enter the execution of this function call our string is not the right length we can add an open so we'll do that pushing that onto the stack our string is not the right length we have used all our opens we can add a close friends so we'll do that pushing that onto the stack and now this satisfies the if statement our string is n times 2 so we'll push that into our answers our it and we'll move through our lines of code because we cannot add any more friends popping this out step and we will then just pop our way all the way back up through the tree until we get back up to the top and now we're going to return our array so in all of our previous function calls we were returning the array but it really didn't matter because we were just pushing our answers in into our answers array which is down here this is the point that matters that we're returning this array because we're in our final function call and when we set this equal to a variable we want to store that we want to store this array in a variable somewhere so in our final function call or our strings empty and our opens are 0 we have explored both branches of our tree which had given us all of our possible combinations of bal currents and we will now top this up stack returning the array and storing it hopefully in a variable or returning it as our answer of course I guess so I hope that was useful I hope that was beneficial I definitely helped me when I was learning recursion to kind of go through it line by line like this so javascript is single threaded and what that means is every time we hit a line of code we cannot move on from that line of code until we've resolved it so every time we make a function call like this when we recurse we have to go into the execution context of this function and resolve it before we can move on to our next line of code and I think going through this process anytime you're trying to figure out recursion just going through the process of following the thread the single thread through all the execution context and the different function calls will help you understand how to write better recursive functions and just understand recursive functions in general in the next section I will quickly go over the time complexity I don't completely understand it so I think we can just look in on it together but I can give you a short little explanation of what it's all about and we can make some statement about it all right I'll see you in the next section so we did go over the space complexity a little bit earlier but I just wanted to put this on the screen so this is the time complexity this problem and I'm just kind of like waving the white flag here I want to apologize to my friend Dakota who spent a lot of time proving this to me I wanted to prove it to you guys but my Matt my math proof skills are not quite as advanced as his but I will say that this time complexity is exponential in nature and it based on so the input is generating the nth Catalan number so you can see here I've drawn on the screen on the bottom here this is the beginning of the number sequence of the Catalan number so this is what we would get if we were to put our friends in so if we put in zero prints there's one arrangement for that if you put in a 1 / n I guess there'd be if you put in a 1 / n I guess there'd be if you put in a 1 / n I guess there'd be one arrangement for that and then it goes from two so our the set we went through was 3 which is 5 and it goes to 1440 to 132 429 and so on so the Consul on number sequence if you're interested in learning about it I'm gonna check it out I just couldn't be get out in time to explain it to you guys but yes this print problem is a pretty famous problem that's representative of the Catalan numbers which gives you this time complexity 4 to the N over N so if you guys have figured out how to prove this in a really easy easily understandable way please leave a comment on my video and reach out to me and let me know how you did it anyways lets us see what this problem looks like in code so the first thing I want to do is define some default parameters so we want to pass in a string we'll just define that as empty string then we're also going to want to pass in how many open prints we're using and we'll set that to 0 to start with and then what else do we want well we also want to pass in an array to store all of our answers so we'll do that so the first thing we want to do is we want to store a variable for our create a variable closes how many closes do we have well that's just going to be the string length minus our opening friends and then if our string dot length if it is equal to n times 2 then we want to push that into our array so we'll do it right now push and we'll pass in our string so what's the next condition oh we want to say that if our opening friends are less than n then we want to make another call to generate prints and we want to pass in the same arguments and adding to our string we want to add a opening front and we want to increment the number of opening prints that we have used and we'll pass the same ran to catch all our gangsters so let's the other condition we want to fulfill well if our closing prints are less than our opening friends then we know we can make another call to generate parentheses and we'll pass in the same arguments but this time adding to the string a closing print we won't increment the opening friends and we'll pass in the same array to catch our answers and that theme you just want to return the answers so we'll return the array and that's pretty much all there is to it so I'm going to run this see if you have any bugs and we don't and look I got this terrible runtime I'll run this again still pretty terrible but we'll go ahead and take a look the answers and I'm going to look at some of the other solutions and see how it compares to what we wrote hmm looks like it the best solution well here we have it so it looks pretty similar to ours right they're passing in they're passing it in the string and then a left and right paren and then the results array and what they're doing is they're just saying that if left is less than n so in our case it would be if open is less than n then pass they make it called a junior parentheses adding an opening print and incrementing left and then they're saying if write is less than left then they call the generate parentheses and add a closing print so it's pretty much the same as ours so I figure hey let's just rip this and see if it's better get a better runtime because I run it so many times I haven't been able to get the good thing good run time that makes me feel good about myself so we'll just see how the best submission on the code is doing right now and it gets the same so our summation just goes there that's all I really wanted to prove but I think the main focus of this is really more the logical reasoning I mean this is pretty much three lines of code so it does a lot of work but it doesn't take a lot of code to do all that work it's more of a logic based kind of problem anyways I hope you learned something from this video I hope you learned something about recursion if you were a code ninja already and I hope to see you in the next one
|
Generate Parentheses
|
generate-parentheses
|
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
**Example 1:**
**Input:** n = 3
**Output:** \["((()))","(()())","(())()","()(())","()()()"\]
**Example 2:**
**Input:** n = 1
**Output:** \["()"\]
**Constraints:**
* `1 <= n <= 8`
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
17,20,2221
|
149 |
Hello gas welcome back to my channel thank you go challenge maximum points on online which line is being made in which the maximum number of points has to be returned by returning it ok the number one has to be returned and which line has to be given in which the maximum number of points is so like in this Only one line is being formed, how many lines are there in it? One is this line bunny which has four points, one is this line bunny which has three points, then what will we do, will we return three points each or will we return four points, how will we do it? Okay, okay, I have fixed one point and whatever lines are being formed from it, whatever lines are being formed passing through that point, I will consider it among all the lines and all the other points on those lines will be considered. I will pass the line through all of them. Okay, for H point, I will go to each point, then what will I do, I will go to the second point and Aadar point. Okay, I have fixed this late in between those two points, I will go to all the points. It's done. Let's see it. It's done. Me, you are okay So all the other points corresponding to it, I and what will I do? Okay for example, what will I do with Violet? So what is the value of It will be okay and then if I go out with it like this then its slow key value will be, what will I do, I have taken out its shop from every point, okay, now the maximum value in it will be my maximum number of points, okay if that point I will conserve all the lines passing through Okay who is this so he got late booed plus van will be my answer Okay Containing this point Line with maximum number of points Containing this point Containing line By doing this, the maximum number of points in the line in which we are coming will be mine which was free plus van. Okay, so what will I do, I have drawn every line for this point and all the lines are passing through this point. And I have removed the line which has the highest number of points. Okay, so I did this for this point. Now what will I do, I will do this for every point and whatever is my maximum will be my answer. Okay, so this much point too. It is possible that the maximum number of points can be a. Like, is it four in this, so it could be that there could be one more point here, okay, what would have happened here, corresponding to this, how much of my income would have been one more. Its value becomes one, okay, but if I consider this point, I will take this one new, okay, then what will happen to me, from here it is becoming 5 points, okay, if it is more than four, then my other points will also have to be taken. I will have to concern about the second point, which is the maximum number of points by content of the point, so I will run it for another example and show it, so what we have done is like this is my example, okay, I have gone to this van common, now its Corresponding, in its corresponding, I will go to each point, I will go to 2345678, okay, I will find it, so what is this point, what is my infinity, okay, then what will I do to it, whose slope is my infinity, I will write that down separately. I will take one variable, okay, so I will encounter that also separately, so what will be the value of this vertical, it will be van, okay, so I will take one more variable, it is used, van, so 11 is mine, the one with van. What is the value of yours? How much is your value? Okay, so what will I do now? I will tell you why this overlap of mine will come less. Okay, this will come less than counting my points. Okay, and my vertical is the same, so one of these. Out of this and out of this, who is the maximum, three, okay, and which people are these, this is the slope of this, because we can denote infinity, so we have converted it into a variable, C, okay, so if it comes twice. So it becomes two, what do I do? Three plus one makes four points, it is in this line, but now what will I do by not doing four, instead of doing 1 plus, I will add two more pluses to it, okay these overlapped ones, I will do more pluses, I am okay So it will be 6. If it is lying three times, then what does it mean? Just add two more points in this line. Okay, so there are 6 points, which means that we are going through that point and I am the maximum number of points. Okay. If you earn three then the maximum that comes will be my answer. Okay, if we do this, how can we do this lock? Okay, then how can we do any slope? I can always do this with NID. Why am I doing this, I have made a video so that you can watch it, I will put the gender in the button, okay and if like, what do I do with this, if I multiply this and then if something like this comes then what will I do with it, I will remove the GCD of both of them and I will divide both of them, okay, so I will divide it with GCD, okay, so this is the way to get the slope, one goes , , , so I will leave that one, okay and I will explore all the other points, then what will I do if that point If it is from, then I will increase the value of overlap and continue. Okay, if that point is from point van kam t, in this case, I am standing on van common tu and the other point is okay, this is y1 - Y2, I will remove the GC di of both of them, okay my. GCD of mine, so what will I do, like if I get 9/6, okay, so I have plused it here, I am taking the maximum of this line of mine, which of these is my maximum. Whatever value is there, I will extract it, my type must be lying in it must be lying in the leg of the van, so is it the maximum or the value of the vertical is the maximum, okay, this does not mean anything and added laptop plus in it, okay, it has local max. I am going to another result and I will return the result at the end and give it, okay because after fixing one point, I am fixing another point, okay
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
215 |
hi dear folks today's lead code challenge is kth largest element in an array in today's problem we are given input as an integer array and a value of k and we have to find the kth largest element in input array for example we are given input as this array of integers and a value of k is equals to 2 then if we'll sort this array in descending order we will be getting output as 6 5 4 3 2 1 and we have to find the second largest element here so first largest element in this array is 6 and second largest element in this array is 5 which is our output we can solve this problem using three techniques one is just a simple one we can sort the input array using arrays dot sort and then we can find the element at n minus k index for example using arrays dot sort will get the input array as 1 2 3 4 5 6 as this is in ascending order we need the element present at fourth index here we can calculate fourth index using formula n minus k where n is equals to length of input array in this case it will be 6 and k is the given output which is 2 so we need to return nums n minus k or nums at index and minus k which will comes out to be nums 4 and its value is 5 here the time complexity of this approach is n log n and space complexity is o 1 let's move to the second solution is a variation of quick select algorithm in quick select algorithm we know that we get a private index and that index has element at correct position as it should be in a sorted array so we will check if private index value is equals to k minus 1 then we know that we got the answer we'll return the element present at private index as an output also further if we didn't get pivot index is equals to k minus 1 then we will choose the property that elements to the left of private index has value smaller and elements to the right of private index has value greater than the element present at pivot index let's take an example here we'll start with 3 and we will try to find its correct position in the input array so as per quick select algorithm after first iteration we will be getting array as one two three five six four so here 3 will be at the correct position as it should be in the sorted array and the value of 3 is 2 that means 3 is present at index 2 also all elements to the left of 3 are smaller than 3 all elements to the right of 3 are greater than 3 so what is the expected pivot value here as we are sorting the array in ascending order it should be n minus k what is the value of n here 6 and k is 2 so we have to find the private value as 4 but after first iteration we got private as 2 so we know that 2 is lesser than 4 so we need to go to the right side of private element so we will be playing around array 5 6 and 4 so we will be taking element 5 and we'll try to find its correct position after the iteration of quick sort algorithm we will be getting our array something like so all element to the left of 5 are smaller than 5 and all elements to the right side of 5 are greater than 5 and what is the value of private here it's 4 as the private comes out to be expected by it so we will be returning 5 as output here that is the element present at private index time complexity of this approach is inverse scenario it is o n square and in best case it is o n and space complexity of this approaches o 1 and last solution is using min heap so we will be creating a priority queue and we will be inserting the element still while iterating over the input array and when we are inserting the element in priority queue we'll check if its size becomes greater than k then we will remove the first element from the priority queue and at last our priority queue will be just having k largest elements here i have created a priority queue i am iterating over this array and i am adding the element at ith index in priority queue then i'll check if priority queue size is greater than k i'll remove the first element from the queue let's start with the dry run here my first element is 3 it will be added into the priority queue my priority queue size is 1 and this is lesser than k so nothing will happen next in second iteration value 2 will be inserted and priority q will look like 2 and 3 as it will insert the element in ascending order the size of q is 2 which is equals to k and then it will go to the next iteration now my element is 1 and my priority queue will look something like this 1 2 3 and the size of priority queue is 3 which is greater than 2 and it will remove the first element from the priority queue which is 1 now my priority q after removing the first element will look something like 2 and 3 similarly on inserting 5 priority queue will become 2 3 5 its size will be greater than 2 then it will remove the first element which is 2 and after removing 2 it will come something like three five then on inserting the next element which is six it will become three five six and this is size is greater than k and we need to remove the first element which is three and after inserting the last element which is four priority queue will become four five six its size is three which is greater than k and we will be removing 4 here and at last priority q will be having values just 5 and 6 and in order to get the output we need to pull one element as well so it will be removing or returning the kth largest element time complexity of this approaches and log n and space complexity of this approach is ok plus 1 or ok i have tried quick select and min heap approaches here both are accepted by lead code that's it for this problem thanks for watching this video and i request you to like this video as well thank you once again
|
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
|
59 |
hey guys let's take a look at number 49 at 59 spiral matrix 2 we're giving a positive integer we should generate you some spiral matrix like this about two three four five six seven eight yeah actually we have done a semanas question which is 54 spiral matrix so you if you haven't look at my video please search number forty five fifty for my channel there's a detailed explanations of how I solved this problem spiral matrix so the core solution core of this problem is that the handling of changing directions we use this vector to express a direction and just change move the cursor through the direction array to simulate the turn right and we just yeah and another thing is that update the item to know to tell that it is already Travis and then finally when everything's we cannot when it will we have met enough numbers we stop yeah so I'll just copy pay the solutions to this one the 59 and do some slight modifications okay so the first thing is that if and include 0 returns empty if and equals 1 return watch all right it's directions are the same turn right is the same result it calls you need them to we need them to be because the numbers we even it them to -1 negative for me them to -1 negative for me them to -1 negative for me great and feel zero and then that's item create a new array and feel - one okay create a new array and feel - one okay create a new array and feel - one okay so we got this array of all - Ron and so we got this array of all - Ron and so we got this array of all - Ron and then when we Travis them and push when told ya total should be and square right yeah and if result what is result okay Nate count equals zero yeah well count is some money like total we do it we will stop at one count is figure that also counts should be 0 we 0 you do it then wait a minute the count should be we will stop when count equal to total that means total from zero to total it actually should show some yeah this is right and then we have three round we first one and then she don't pushed it item but you say set it to PI J equals count for we just used to one and then someone or equal to total first round second round the last one yeah this much better okay we updated to count the next possible is this right if it is overflowed or it is Travis it is already set then this one is equal to go for P it's not equal to -1 we try go for P it's not equal to -1 we try go for P it's not equal to -1 we try right can't - can't pass one this should right can't - can't pass one this should right can't - can't pass one this should work I think so let's hope it works hmm some something wrong matrix is not define Oh doctor I'm sorry this is a result it is it this was result run the code yeah it seems that we can get accepted no new is not try the type of expected return type not many state we're waiting where is the 28 so on input the prettiest one so it's a little weird event 0 accept it was just one return ah my bath should be something like this yeah okay they test it which one my bad we should care more about the output format yes let's up submit again okay we're accepted and actually this does not need more addressing that so if you are interested and I need to understand more please take a look at my video of number 54 this search on my channel and hope it helps and that's all for this problem 49 matrix by row matrix - thank you see 49 matrix by row matrix - thank you see 49 matrix by row matrix - thank you see you next time bye
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
1,880 |
hello everyone welcome to coderscamp so in this video we are going to cover this problem check if word equals summation of two words and it is one of the easy category problem which is asked in lead click on test 243 here the input given is three strings the first word second word and the target and we have to return if the first word plus second word is equal to target so here they have given us each character in the word will be assigned with the integer like a starts with 0 and goes till 25 is it and if we add the values of first word and second word which should be equal to the target in that case we have to return true otherwise we have to return false so let's consider the first example given acb cba and cdb so if you convert the first word acb then it is going to take 0 to 1 and as the 0s in the front can be ignored and the number is 21 and then the next character or the next word cba can be represented as 210 and the target can be represented as 231 and if you add 21 and 210 it is going to be 231 again so our output is going to be true so first let me write a method which converts a string to a number let me name it convert and it takes a string as a parameter and returns an integer value as a result so i am declaring a variable integer variable result and i am going to iterate my given string so inside that i'm gonna calculate my result so which is nothing but we are going to convert each character to a number first so this will actually convert each character to a number so every time we convert it to a number we are going to append it to the last of the result so which is nothing but result plus result into 10 so it will multiply a 10 and add this number at the end so finally the result will have us the complete converted number so we are returning the result so now in main method we are going to call this function to calculate the number form of these three words so directly i am going to return convert of first word plus convert of second word is equal to convert of target word so it simply compares and return the value accordingly so let us run and try so yes let's submit yes the solution is accepted hope i made it clear and it runs in 0 milliseconds so thanks for watching the video hope you like this video if you like the video hit like subscribe and let me know in comments thank you
|
Check if Word Equals Summation of Two Words
|
largest-merge-of-two-strings
|
The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer.
* For example, if `s = "acb "`, we concatenate each letter's letter value, resulting in `"021 "`. After converting it, we get `21`.
You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**.
Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._
**Example 1:**
**Input:** firstWord = "acb ", secondWord = "cba ", targetWord = "cdb "
**Output:** true
**Explanation:**
The numerical value of firstWord is "acb " -> "021 " -> 21.
The numerical value of secondWord is "cba " -> "210 " -> 210.
The numerical value of targetWord is "cdb " -> "231 " -> 231.
We return true because 21 + 210 == 231.
**Example 2:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aab "
**Output:** false
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aab " -> "001 " -> 1.
We return false because 0 + 0 != 1.
**Example 3:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aaaa "
**Output:** true
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aaaa " -> "0000 " -> 0.
We return true because 0 + 0 == 0.
**Constraints:**
* `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8`
* `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**.
|
Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to consume the next character from. You should choose the next character from the larger string.
|
Two Pointers,String,Greedy
|
Medium
| null |
976 |
Hi gas welcome and welcome back to my channel so today our problem is the largest parameter triangle so in this problem statement what have we given here, we have been given an arrangement of names and what is the largest parameter of an We want to find a triangle. Okay, so which triangle will we find? Here we have given our example which will have different elements. We will see which of the possible triangles can be made by using these three sides. So which of them is your last parameter. It will be that you will give it after returning it. Okay, so let us see this problem through an example to see how we can solve it. Look here, see what has been given to you, it is given like this in which there are three elements here, in this also your If there are three elements then it is not necessary that yours will have three elements because you will see the contestants, here we have given three, your smallest size can be greater than three and less give equals, you can go up to 10, you can go to the power four. Your element is ok, so how will we find here whether a triangle will be formed at any place or not? Look, if you have three sides given to you by ABC, then how will you find that by joining these three sides, we will form a triangle. If you can make it or not, then you must have studied your concept in school. If you add the two smaller sides, then the total value should be greater than the largest side of yours. So which one is right here? We will do it, if it is happening then we will start the return. Can our debt menace be formed? If it is not happening, then debt menace cannot be formed. So we will see how many possibilities we have, then whichever one will be the largest among them. I answer will be ok, so what will we do here, let's see ok so here you look at this, what will you do with it, you want two smaller ones, first you want the sum of both the sides, then you want the third largest, then how will you find it, then what will you do by sorting it, people write short. We will do 1 2 so these two will be smaller these two and this list will be this A this B one so add these two and see if its value is greater than this one is greater dat min we can create a pay add here so we can use this Sam will see these three: 1 + 2 + 2 4 1 5 see these three: 1 + 2 + 2 4 1 5 see these three: 1 + 2 + 2 4 1 5 Because here only one triangle can be formed, so you will see only one on the right, and if you have any option, then you will not see it, otherwise your answer is in five years. Now here you have 3 sizes, here also you have only one triangle can be made, now we will see whether we can make it or not, so these two are smaller, we will add them both, this will become tu, is this greater than tu? No, it's not a date, we can't make iron here and we can't make a triangle, so what will Dan do here also, zero, okay, this is done, now this can also happen here, which triangle will be formed if you have 1212? Here you will sort it 1 2 So what will you do here, you know that you have sorted then where will we get the value of maximum side from garden then we will start looking from the back, we will look at these three first. You will see these three, plus you, give greater 2, that is, if it is possible to make your own, then this will be your answer because we know that we are going from the back and this is the last side, it is okay, whatever is the larger side. It will be from your back only, so if we find it here, if we find out that it is possible for us to make a triangle, then what will we do at the same time, we will return the answer, then 2 + 2 becomes your four, which is then 2 + 2 becomes your four, which is then 2 + 2 becomes your four, which is greater than yours. That is, it is possible, what will we do, its parameter is add to all three, you plus you, that is, six will be yours, okay, apart from this, if it is possible here, then what will happen to you, it will be less than this, right, so we will attend here, now we will come. Let me explain the code part, this problem is quite easy, what will we do first, we will short it, we have shorted it, after that what will we do, we will look at the last three elements, so what we will do, we will start with impossible size -3 what we will do, we will start with impossible size -3 what we will do, we will start with impossible size -3 and this is your Greater than equals should be till zero and keep decrementing i. Okay, what will we do? Name i + vein i + 1, let's see if this is greater than i + vein i + 1, let's see if this is greater than i + vein i + 1, let's see if this is greater than i + 2. If this is gutter, date mains, our + 2. If this is gutter, date mains, our + 2. If this is gutter, date mains, our possible is to make a sorry triangle, so what will we do? We will do the sum of all three here, we will turn it here, okay, if we do not find this condition fully fulfilled anywhere, then hey, if you do not find this condition anywhere, then the date mains is not possible for you because of the elements you have given. We cannot make a triangle by doing that, finally what will we do Dan, we will do zero, ok so I hope you have understood the problem, if you liked the video then please like, share and subscribe, thank you.
|
Largest Perimeter Triangle
|
minimum-area-rectangle
|
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
**Example 1:**
**Input:** nums = \[2,1,2\]
**Output:** 5
**Explanation:** You can form a triangle with three side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106`
| null |
Array,Hash Table,Math,Geometry,Sorting
|
Medium
| null |
1,732 |
hey everybody this is larry this is q1 of the leeco daily uh sorry bi-weekly contest leeco daily uh sorry bi-weekly contest leeco daily uh sorry bi-weekly contest 44. uh find the highest altitude so this one um for each element of the array they just tell you the difference between the previous array so from that you just do it one at a time um you start from zero and then you just keep track of the highest by looking at the elevation change and knowing that x could be negative um and that's pretty much it this of course this is linear time constant space um i don't really have that many things to say about this one so let me know what you think and i will see you uh or you could watch me stop it during the contest next as well and let's go you uh yeah i did not do well on this one at all i think i just need more sleep uh this deep both q3 and q4 were tricky so yeah um don't know what else to say uh thanks for watching hit the uh hit the like button in the subscribe button and i will see you next fall bye-bye
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
985 |
hi everyone.this look at number nine hi everyone.this look at number nine hi everyone.this look at number nine eight five some of even numbers after queries so we have a ray of integers an array of queries for each query the first one is value the one second one is index so it means we add the value to the index two numbers have been there hmm then the answer of the query is the sum of even values of the original integer array return all answers to the queries what okay the like this is input one two three four the query is 1 0 minus 3 negative 4 to 3 the output so the beginning is this one so the first query is 1 0 means add 1 to the first element so it is 2 to 3 for the sum of email and value is 2 to 4 8 and then 2 then minus 3 to the first one this is the second query so I'm not first the second one so 2 minus 1 3 4 sum is 2 4 hmm this is not even an algorithm problem I don't know why did this so yeah this is the result I don't know what does this mean okay the empty results so and then therefore query of that query of queries that's it's not query this is Val index and that comes a very one plus a very zero right okay then result some result push a reduce readings yes yeah hey Ivan he's even returned some gloss item finally your training result yeah not a number what a reduce 0 if item trim some Hey is this one and then we a ah God they reduce some item between Sun plus I if he's like activist even then item for zero I don't know any you mmm-hmm the string I don't know what mmm-hmm the string I don't know what mmm-hmm the string I don't know what should I improve maybe we can prove that the sum of the numbers might not be change maybe we can just calculate the previous sum and see just it directly gets the final result maybe so for that case we don't need to every Travis every time net current some clothes okay this one so now we need to see but the original one is so if the original one if the only unit one is an odd number and is a even number and the query one const knew hunker equals this one three now if crease so the sum faster delta equals that's also equal 0 if Reve if it is even and the current is art it's not zero results push current some - we zero results push current some - we zero results push current some - we save if it is and still then plus current bias brief if pre is not fast car the other cases boosts up oh let me do nothing we query 1 equals thing is working hmm wrong answer what a query course current mm-hmm maybe what a query course current mm-hmm maybe what a query course current mm-hmm maybe it's both up hot life just no more art so we remove the privet and then we minus 3 how to be on and even so we minus 2 uh-huh Delta equals L equals the Sun passed out and we'll push result push some hmm this is faster yeah I think it is good enough okay that's all for this question see you next time
|
Sum of Even Numbers After Queries
|
bag-of-tokens
|
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length`
| null |
Array,Two Pointers,Greedy,Sorting
|
Medium
| null |
829 |
Hello Hello everyone Manush and today we are going to solve a very interesting question in the address system portal, the name of which is which coating number is even, so this is a high-tech problem but we will solve this high-tech problem with high-tech problem but we will solve this high-tech problem with high-tech problem but we will solve this high-tech problem with medium easy approach. Right, what exactly is this question and how will we reach the solution? Let's see this time. Okay, yes, I am okay. Will you get some share? An interior and rest. What do you have to return? Return the number of ways you can write an essay of. Which duty positive integers are tight? These three things are to be kept in mind. Which duty positive and end teachers are okay. For example, let me give you the board exam. It is tight that if you look at it, then basically 215 examples have come out of me. Okay, in this example, I have to take care of the music, I have to take care of these things that on which duty I should come and it should be a positive integer, I wrote it carefully, so first of all I told the fans, first thing is this. That is to make shift 80 one number what is the other way can make it on 15th from 12345 till its time that one number see here 324 504 506 and what is the way ghee pass 60 and in more ways of pastor let's see that the youth Girls are A 7 Plus 8 This stand, see which duty numbers are added to the wells, this is the star way to celebrate the holiday, this is the second way, after doing the third and fourth cricket test, Meghnad wants Kachoris, why did you say, then carefully, this is how we approach it. What will I do to know that if I tell the number office or not the number office, then how will I go and press write the answer? From here, first of all I said, it is very simple, okay, the numbers are basically numbers of elements of tonight, which I will pick and refuse clearly. I can equal to two and okay then I sleep equal to one equal to two equal to three like 1248 one 125 do this till the same upper limit till the upper limit I set it without any delay, what does Jhansi mean? Ke equal to one essence means you have to pick only one element and if you have respect then one element is clear then do any of them otherwise I will be made from here True Aaya it can be made from here Ke equal to quarter What from two -What can I plan and -What can I plan and -What can I plan and create chords from here, how 738 This is also my answer by clicking on the shooting ke ko lokayukta tau size two element Arrow That speaker's taste comes Yes G4 plus five plus 6t By copying the element Phase can be made carefully, how to right chacha, where can it be made by grinding the element, four elements can be made from here by clicking on 2004 element, I can make my target by doing five elements also, yes at J5 rate, I can come from here I am one plus two plus three plus for class 5 A quarter 215 come right through so I can make the blouse in this way, apart from this I don't know about it, now I need this, apart from this water so basically this is how much limit can I make, its upper limit What is that, first of all we cross the upper limit of how many elements can be added, I have to do that whether I can make my time or not on Friday, I don't want exactly this amount, I don't want this method only, in how many ways can I create this system with just the account. Don't account roadways wages and class and electricity in the account, when you blow it on the road, I do n't want that thing, I don't want the number, this path and number fails, Raita, by the way, send me the number here so that a team can be formed, I don't know those ways. K Shift Add 12345 Add 2 but it was not sent I just wanted to know how many ways can you make the holiday ok so what I said is start with equal to one go to your matup and I will check how it will be made or not Okay, let's see how to find the upper limit. Okay, now the next point, what was the problem? Hello, how to find the upper limit. Okay, so let's see our madam, how will it turn out, so I support the suggestion rate sequences start. With -If it is of karte type of lens then it is of If -If it is of karte type of lens then it is of If you limit it then basically this egg is the upper limit of this one, instead of flight, so pay attention to what will be made in such a situation, the time of the pass has gone to sleep, see, it has become 101 to three, how much time has it been in the mention pet total, from the term of this. So this is its circumference deposit this is x plus Sum of first and minus one alarms show submission of what happens * and plus one by two submission of and * and plus one by two submission of and * and plus one by two submission of and square that and 2nd place one to one plus one by this at solution of and cube and 2012 whole square main tere once confirmed. Now take whatever you have to write, it is okay, this is what happened, the sequel is liberalized, Reddy, this is one plus submission of one and minus one, this is the number to Z, I will update one of these pans, so this is * K - 1929 That's minus one by two equal to en-light That's minus one by two equal to en-light That's minus one by two equal to en-light so what has become this linear equation in two variables this is the linear equation that in this you have just gone right direction to the variables so how can we solve it pass in the thing that came down to call If you want to solve me then I should be plus 2 equation. It is here also have two equation which person needs equation and what is secondary neither try with values nor try with values neither try with values nor try with values neither try with values nor try with values post with drag flick and arrest the second rally nikalte ko. The date was this, please do the balance, on the other hand the question comes, one more two spoons, so now what will happen here, I will request, I will write the answer face to face, if it is okay, then I will give it to X's family, replace that, then it is equal to the end in the store. - K * k equal to the end in the store. - K * k equal to the end in the store. - K * k minus one by two divided by cheap rate This is the rate in question so let's go to the specific what action There should be energy if there are positive entries, once in this it is guaranteed, see Frontiers Positive A Positive and Employees at College Greater 1008, what should I find, still I am extracting the upper limit, it is okay, if I am in the top in the first, then in Tears should be positive devices then let's go ahead if Let me see the 2ND grade of the day * k minus one okay so this grade of the day * k minus one okay so this grade of the day * k minus one okay so this quality next I first quality hua green off k in terms of n that in this time and date mixture is on how I will say k equal to one k equal to two While checking from 2 to 2, how long will I use the oil, it will continue till 2 animals are greater than * K - this is the animals are greater than * K - this is the animals are greater than * K - this is the rate and for everyone, what will I have to do, which answer is coming here No, it's fine, now from here till now I have come to know that for whom the answer will be velvet and for whom it will not be so, I just have to check that it is for which and on the side of which the answer is valid or not. Well and note so from here the question period This is a simple thing, now this valid one is the axis and the teacher will be a positive, this means there is an internship, this means that this time I will check the electricity meter, my e-mail address and - e-mail address and - e-mail address and - Chintu's - this Chintu's - this Chintu's - this is one. Bye to memorable moment leter right his encounter kya ki to for axis in teaser what conditions should have come the condition should be that if the diameter of my ter's models is equal to zero name does it means axis is valid na add that Counted in total number of send off was tight, so yes, absolutely correct, here we have made this complete Ghoshal, before that I said, worry about using 121 one element to make it like that, I moved two elements forward and made three lines. By doing this till the upper limit, how many elements is the maximum picture so that it becomes the answer, it is okay, remind me, then I said, what is the maximum limit people can go, then take a bold look, from here I angrily expressed from Express on Express press release to Express K - Tak Yeh Care Limited Express K - Tak Yeh Care Limited Express K - Tak Yeh Care Limited Dekha To Se Matup Question Money Kya Below the condition is that you can call as long as 2n is greater than this * K - one. * K - one. * K - one. This is how the condition of your upper limit add will be till then and when - When will it be activated and for how long will the bracelet and when - When will it be activated and for how long will the bracelet and when - When will it be activated and for how long will the bracelet remain that figure? How if you put the minimum on Dominator bike or if it is called Ricardo Silva, it means that this part is being completely divided and one is becoming mine. If there are advantages then I can make a classification. Right for beginners. If I can make this thing, add it in this way on your face, add an account of your business, rate it, then let me kiss it and we will dial it, rate is fine for this team only. Then if it happened, then it is good, it is so big, come on, lion, still it increases it a lot, which is 181 problems, but in such an easy way, people were only and only maths, so I was the first one to give this account which is equal to zero. And I will add and return the account, this will be my answer Stanley and before that, see, before that, I have to make one thing, from where to get the broom, see the point, after all, starting from 121, from the clothes to here, how long did the condition last till you 2n this greater than * condition last till you 2n this greater than * condition last till you 2n this greater than * k will keep going on right America or until how to *when is greater than that *k how to *when is greater than that *k how to *when is greater than that *k minus one will keep going on rate and every time what do crotch k do two plus now every one In the fort, I will check whether mine is deleted or this one of mine which I am making in the sequence, is it correct? For this, a girl is possible, otherwise Lanka is possible. By clicking on the last two elements, it is possible. No, this is right, so how will I remove me? Successful I have to remove no matter tight so my t is equal to net how to see this is mixed in tomato juice - net how to see this is mixed in tomato juice - net how to see this is mixed in tomato juice - this is matter side end - not this is matter side end - not this is matter side end - not happened - ki multiply ki - vansh divide by two this letter has come - vansh divide by two this letter has come - vansh divide by two this letter has come right So it is a simple thing, if my T's models equal to zero, then this will be created in the answer, this will give the account, that is, by clicking on the element of this calendar, if you do not create such a condition, then by clicking on the element of I, that I can make Bigg Boss in quantity and the time of the day comes, I write and add and return. The only thing I had in my account was that once I open it, I grind the coffee and if I submit the decisions of the reports today then turn it on. After taking advance rights, let's try it once in a year. If we train for the same exam clipping then it is good, then we should continue till checkup. Is this condition equal to one, will this scenario be favorable? 215 is equal to 15th. Where do I change? Anicut, Umth rate, quality, 16 to 16, three layer rice, 250 previous * - 16, three layer rice, 250 previous * - this is a cover of 110, this garlic, Ranchi to end, if you ask till then, it is 238 or only - one, ask till then, it is 238 or only - one, ask till then, it is 238 or only - one, station to 538, hole. K * stick won't work station to 538, hole. K * stick won't work station to 538, hole. K * stick won't work Jahan se ko to kya that K * K - Jahan se ko to kya that K * K - Jahan se ko to kya that K * K - but if I do this section 2 538 and two into a bhuji's this thirty note garlic will be taken by the president this is just a complaint Now I will feature all what will go in the sequence Can't right I do n't care here no matter how will you get scared dormitory basically Raphael - K*K - 1929 basically Raphael - K*K - 1929 basically Raphael - K*K - 1929 that this matter is coming okay so why did the tomato come here and - 151 - che*k minus one why did the tomato come here and - 151 - che*k minus one why did the tomato come here and - 151 - che*k minus one so this picture It's done, only 5 - 2m is visible here - * - * * * * * * * Folded to three, 272 seats have arrived, what is located here at 2312 or else 5 - what is located here at 2312 or else 5 - what is located here at 2312 or else 5 - 50241 has become subject to protein in 1015 at 12:00 Not equal from here to 12:00 Not equal from here to 12:00 Not equal from here to here what to do if no matter airplane mode off is equal to zero then control will be plus then put here please model has one is equal to zero through 80 two is equal to zero here 12th death anniversary equal to two Zero here True Knowledge 4 9 in 2015 Difficult Once here 1234 So in this way and if you want that then I hope you enjoy folding it in such an easy way so do try it then subscribe the channel soon Kapoors
|
Consecutive Numbers Sum
|
subdomain-visit-count
|
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 = 2 + 3
**Example 2:**
**Input:** n = 9
**Output:** 3
**Explanation:** 9 = 4 + 5 = 2 + 3 + 4
**Example 3:**
**Input:** n = 15
**Output:** 4
**Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
**Constraints:**
* `1 <= n <= 109`
| null |
Array,Hash Table,String,Counting
|
Medium
| null |
367 |
all right let's talk about the perfect square so you are given a positive integer now so you have to recently the numbers the perfect square else false right so here's a diagram i'm going to just quickly just uh guide you through it how do you do it so you can actually traverse all the fun but you have uh you will get the oe but i will still teach you how to do it so you can just say uh from 1 to n right but imagine i times is actually equal to num and if this is true right you can return true so we don't actually need to traverse one three and again traverse one two square root of one and then we can just uh find out what is the perfect square of place right so return true if this is valid within 4 cells right and then this is going to be dle so the beta way is going to be what uh using the binary search so you have um the lowest pointer and highest pointers i'm gonna call i and j pointer so k represent y k represent i plus j minus i divided by two and this is uh least represent k and then you have to say if the number divided by k and also the normal okay is also equal to zero so uh this is hash action has to equal to k this is because what i times i is actually equal to norm so which is k times k is also equal to known right so this has to be a sentence of num's divided by k equal to k and num small k s equal to zero you can return true all right i don't know why i use this color it's not really easy to see okay so i'm going to say val equal to this number so if r is actually less than k and val is actually greater than k right this is also depending on this in denominator right so um what does well lesson k mean so val lesson k mean uh maybe this number is too big right because val is less than k like this well depending on k be honest so if this is 2b i just make it small so i just move my pointer j to k minus one and this mean too big so i move my eye pointer to k plus one right so you have to think about just being about like what does k represent i mean what does k associate with val and this is going to be super easy so i'm going to just quickly just uh resolution so i equal to 1 j equal to num uh while i less than equal to j you do something right and you have a k represent i plus j minus i divided by two and if and also sorry a and also value is actually true now divided by k and also remain equal to normal here right so if vowel is equal to y is actually equal to k and also remain equal to zero i can return true so everything else recompose so val equal to k this is also mean j times k equal to num right so think about this and also if i exactly less than k l squared and k right uh if i was less than here i just say if the value getting a number in the denominator is two uh it's too big so you will move your j to k minus one and this is greater so it's gonna be i k plus one right and there we go so then let's just follow the solution so yeah all right so let's talk about the timing space this is going to be space constant right and this is going to be time lapland like every single time you cut into the half so yes lock them for the time space is constant and i will see you next time bye
|
Valid Perfect Square
|
valid-perfect-square
|
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.
A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as `sqrt`.
**Example 1:**
**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.
**Example 2:**
**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
**Constraints:**
* `1 <= num <= 231 - 1`
| null |
Math,Binary Search
|
Easy
|
69,633
|
105 |
um hello so today we are going to do this problem called construct binary tree from pre-order and in order tree from pre-order and in order tree from pre-order and in order traversal so we have two arrays pre-order and in so we have two arrays pre-order and in so we have two arrays pre-order and in order um basically pre-order is basically pre-order is basically pre-order is just the tree uh processed in pre or the traversal so pre-order is traversal so pre-order is traversal so pre-order is root and then left and then right um and so here um the first root that's three right and then that's what we have here and then left so the root of the left side nine and then the since there is nothing after that we go back up we go to the right the root on the right side is 20 and so we go after the roots we go left the root of the left is 15 and then after that we don't have any children and then we go right so root left right is seven um and also we get in order array in order is we left then root the right so in the usual order left first root and then right and so here left first so the left most is nine and then the root of that three um and then we go to the right side but we recurse right so that we go to the left most so we get 15 left most and then we get the root and then go to the right which is seven so we get the two arrays in order in pre-order traversal and our goal is to pre-order traversal and our goal is to pre-order traversal and our goal is to reconstruct the tree and return it um so this is a representation of the tree but we'll return it in a format of a tree node and here just an example with just one node which is minus one so we just return minus one okay um so that's the problem here um one thing to note is that um they say here that we are guaranteed that pre-order in order have unique values so pre-order in order have unique values so pre-order in order have unique values so there is no duplicated values in the tree um so that makes it easier to solve so let's see how we can solve it um okay so let's see how we can solve this so the main thing to note here is that uh pre-order gives us the root first so uh pre-order gives us the root first so uh pre-order gives us the root first so here we get the root 3 first and then we go left so it's pre-order is root left then right and in order is left first root and then right okay so here we have the root the first root and then we go left right this here and so we do then we do right do left so left the root of the left nine and then we go right the root of the right twenty and then we go left the root of the left fifteen and then we go right the root of the right is seven so you can notice here as we go with pre-order we will get each as we go with pre-order we will get each as we go with pre-order we will get each time the we get an element from the front um we get the root and so that's the main thing to note here is that we can use uh pre-order to get the root each time right and then once we get the root so let's say we get the root is three we can check in our in order because in order we have the root separating left and right so we have root separating left and right okay so we get the root from the pre-order so it's three pre-order so it's three pre-order so it's three how do we know the left side from the right side well we can just get the index and then whatever the index of the root whatever is to the left of that index it's the left subtree whatever is to the right that's the right sub tree so this means basically is that this is the left sub tree and this is the right sub tree content okay and so that's pretty much it that's pretty much the idea and we can just recurse and keep doing this until we are at the end and the end means we don't have any elements to process anymore um so that's the main idea that we are going to go from now one thing that will help us with the pre-order so it's help us with the pre-order so it's help us with the pre-order so it's 3 9 20 57 if we make it a q a dq then we can pop from the front so we pop the first root and then in the next recursive call we pop the next one and then we pop the next one and that way basically we can obtain the root in the right order okay and then once we get the root so let's say we do q pop left to get the root of course this is the root value then we can just take the in order so and get the index so in that when we pop three we'll want to get the index of three so here it's one so we get the index of three so root value that will give us the root index right and then we could just do our recursive call and our recursive call let's call it recurs we need now to determine what are the parameters that we need to pass for the left and the right and we need to assign those to the left side and assign it to the right side assign another set of values okay so here we need to assign two parameters now what can be our problem so actually what we need we know that for the pre-order we'll just use a that for the pre-order we'll just use a that for the pre-order we'll just use a dq and keep popping so we don't need to worry about that but for the in order we want to get the indices of what's the start of the left side right what's the stop and what's the end right so that we can now okay um this is the right subtree we pop the root of it which is 20 we want to know where is 20 in this sub list right um and so what we need for uh basically our recursion is to know the start and the end that will help us also know when we are done because when we are done and the list is empty um then we will have start bigger than end okay so that will also help us with the base case okay so now let's see the parameters so we know that the parameters are start and end what's the start for the left side so first let's just start for the uh first call right so for our first recursion call i'll score this records in water right or recurs maybe for now so for the our first call well it's the entire array so it's a zero to the end here which is the length of in order minus one right so our first call we need to call it with zero and then the length of the in order minus one okay um this is the start this is the end now to process our left side what is the starting point and what is the end point well the starting point is the same as whatever it was the starting point before this is important because when we are looking at this one and we want to recurse on the left we want the starting point to the here so it's the same starting point that we got in the um the parent call right so this is start it doesn't change right because left is just from the start to this index here which is just the root index minus one right because remember for in order it's left then rooted and right which means that the left side starts before the root so we can just say um let me just give space here so we can just say it's the root index minus one that's where the left side ends now what about the right side so the right side begins just after the root and so it's root index plus one and when does it end it ends at the previous end okay it's the same and as the caller so and then we can return the node or the root whichever you want to call it that's pretty much it so um however one optimization we can do is here instead of doing having to do the index every time which would be linear we can just have a hash map that we populate initially using the in order array that will allow us to find the index easily with one operation yeah and that's pretty much it so let's write this down and make sure it passes test cases okay so let's write our calls here so we know that we need to recurse and the start point is zero the end is and the end is length of in order um minus one okay um and we want to return this um we can name it to recurse in order because actually we are recursing on the in-order uh array okay and so let's in-order uh array okay and so let's in-order uh array okay and so let's define this function here so that function is on start and then and start and here are for the in order array or list okay now we need um our pre-order we okay now we need um our pre-order we okay now we need um our pre-order we need to convert it to a dq so that we can easily pop left uh pop from the front to get the root you can maintain alternatively you can maintain just the index of where you are in the uh preorder list and just keep incrementing it um yeah but this one is just easier so we can do um pre-order pre-order pre-order queue or dq and that would be just uh we can use collections in python eq and then just pass as a parameter our list um and now we need also as i said to make it easier to get the index uh we want to map from the values to the indices uh for the in order list because every time we will want to check what's the index of the root in the in order uh list and so uh let's call this indices okay or maybe in order indices so we get the value to the index so it maps the body to the index and we can just in python it's easier to do this way you can do it with a for loop as well if you want um and now this would be far in order okay so now we have everything we need um we need our base case which is once it's the list is empty or start is bigger than end what do we return so empty we would want to return none so that the left and the right child are marked as none for the tree and now we need to do the node which we said the node value or the root value is going to be just popping from the pre-order list just popping from the pre-order list just popping from the pre-order list okay if you had maintained an index you could just pass that um and then let's call this root it's going to be tree node and we are going to pass root value and now we need to get the index so root index is going to be uh from the in order indices so that makes it easier for us and we are going to pass the root value and now we can recurse for the root the left and right alright and then at the end we can return our root node now here uh we're going to recurse we're going to pass the start as we said so start is going to be the same for the left side and the end of the left portion is going to be just before the root because in order is this left root right so let's just write that down left root right this is for the inward traversal so this means here is that the end is going to be just the root index minus one that's where the left side ends um and then we can recurse as well for the right side and the first element of the right side is just after the root so it's root index plus one and the end is the same right is the same end as before um and that's pretty much it here so let's run this make sure it passes um okay so here uh there is slight thing we need to do which is we need indentation to indentate properly um yeah so here it's not the pre-order it's yeah so here it's not the pre-order it's yeah so here it's not the pre-order it's a pre-order dq that we want to pop left a pre-order dq that we want to pop left a pre-order dq that we want to pop left from okay that seems good awesome okay uh yeah so that passes test cases um yeah please like and subscribe and see you on the next one bye
|
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
|
47 |
hey everyone welcome back and let's write some more neat code today so today let's solve permutations two the follow-up to the first permutations the follow-up to the first permutations the follow-up to the first permutations problem so we're given again a list of numbers and the only difference with this problem compared to the permutations one is that this one actually might contain duplicate values but we want to do the exact same thing we just want to return all unique permutations in any particular order so you look at this first example right we have duplicates we have two ones and if you don't remember our permutation is that okay so we have three numbers that means we have three spots for each of so for the first spot we have three choices right we can choose any of these three numbers and if we choose one of the numbers then we'll have two remaining so for the next spot we can choose two numbers and if we do that in the last spot we'll only have one choice so we know that we have three times two times one permutations which is the same as n factorial where n is the size of the input but this is for a regular permutation right when you look at this we don't have six permutations we have three and the reason is because the we have duplicate values in our input right so since this itself is one permutation right the list itself is a permutation of itself one way we could get a different permutation is swapping the first two values right but if we reverse the order of them we still get the same exact permutation one two and that does not count as a new permutation it's a duplicate it's the same as this one so we don't want duplicates i'm going to show you how to solve this problem with the difficulty that comes with it not having duplicates in our output so we're gonna solve this problem with backtracking just like the first one and so this is going to be our input so let me just show you why a normal decision tree uh with this is not going to work so we know we have three spots right in our permutation so let's say for the first spot we choose the first element right one so that's one choice for our second choice we can choose this as the first element right one but we see that they're the exact same right this is what's going to cause our duplicates but let me just show you why the third spot will have a two so now for this one we have two more choices right we chose the first one but now we can choose either of these so for our second spot we have two choices so we can do a one or we can do a two and if we did two ones we know for our third choice we can only do a two if we did one two we know for our third choice we have a remaining one and now let's do the same for this one so we chose the middle one so we have two choices one and two notice how we're getting the exact same result in both spots right so with this we'll have a remaining choice of two for this we'll have a remaining choice of one so along this branch we had two different permutations one two and one two one right that's our second permutation and for this one we had the exact same thing we got both permutations duplicated right that's not what we want to do and that happened because we started with the exact same value we cannot use duplicates in the same position if we want to end up with different permutations so this is a problem like this solution just does not work currently we have duplicates we don't want duplicates and so with the two actually we'll also have duplicates right if we choose a two then we have two choices right we can choose either of the ones and then if we choose a one we'll only have one value remaining a one for each of these paths so now you see even these are duplicates right and that happened because for these positions we chose the exact same value so we can solve this problem and the way we're gonna do it is instead of using this array as our input we're gonna modify this array into a hash map and let me show you what this hash map is going to look like so this is our hash map so we do not need this input array anymore you can see we took each number so we had a one in our original uh array right and how many ones did we have well we're gonna count that and we ended up with two and we also had a 2 value in our input how many did we have what's the count of that 2 well we only had 1. so with basically with this list we eliminated the duplicates right we only have 2 numbers but we didn't get rid of it completely because we counted how many of each we had so now with this map i'm going to do the decision tree the backtracking decision tree so we actually have two choices now because look at the numbers that we have in our hash map we have a one and a two so we have two choices for the first value a one or a two so again we're still doing the same thing we're looking for permutations of length three right and for our first spot we're choosing either a one or a two so let's go with this path so we chose a one for our first value so now how many choices do we have do we can we only choose two in this case well yes we have two of course right but since we only used one of our ones right so and initially the count was two but now we used one so now there's only one left so we're going to have to update our hash map as we go along this decision tree so we have one left so now let's use that one right so if we use that one then we'll have zero ones left right so zero ones along this path and lastly we'll only be able to choose a two which will leave us with zero twos right so basically this is one of our permutations one two and you can see that this permutation is never going to be repeated because we cannot make that permutation again over here we chose a 2 instead of a 1 and that permutation is never going to be repeated here because this one starts with a 2. it does not start with a one so now let's finish up this decision tree because we know we cannot add any more to this it's length three so the these counts are getting kind of sloppy but i don't think i pretty much have used them to illustrate what i wanted to so lastly we know that there's only a one left over here so this is also going to be a permutation so far we have two permutations in our left subtree now let's finish up the right side so since we started with a two over here that means we ran out of twos right we have zero twos left but in reality we have two ones left right because we only used a two we have two ones left does that mean we have two choices can we choose one on each side no because look at the unique numbers we have this is our only number left we've used up this one so we have one choice in reality so we can choose a single one and then the one count is going to be left as one so we have one remaining so we do have a choice left but it's only a single choice and it's going to be a one let me just make these green so now you can see that we ended up with three different permutations and basically we eliminated the duplicates by transforming our input array into a count hashmap okay so now let's get into the code so we are going to have a result which is going to store the list of permutations right the output and we're also going to have a list to store each permutation itself so we only have one variable to do this and lastly let's make our count hash map so i'm going to take each number and initially map it to zero so for every number in our nums input i'm initially going to map it to zero so the count is initially going to be zero then i'm going to go through every number and update the count of our map so for every number we're going to increment its count by one so with this we'll have a count hash map mapping every number in the input nums to its count and then all we have to do is create our depth first search uh backtracking uh our debt for search backtracking function and i actually don't even need to pass any input values into it because all of these values are going to be accessible inside of here because this function is nested inside of another function so in this case for this function our base case is going to be that our permutation that we have the length of that permutation is equal to the length of our input nums that means the permutation is a complete right we have no more values left to choose to add to the permutation and once that's the case to our result we're gonna append a copy of the perm uh list and the reason we're making a copy is because we only have one of these uh variables every time we make a change to it we're gonna end up updating the variable and since this is our base case after that we can return so next uh we're gonna brute force this right we're gonna choose every choice that we can and what that means is we can go through every number in count right count has eliminated the duplicates every key in our count hashmap is going to be unique and for this value we just want to make sure that the count is greater than zero that means we're allowed to choose this for our permutation we have enough values left and we're going to take this value and add it to our current permutation and if we add it to our current permutation we have to take the count of it and decrement it by one right because we're now going to recursively call debt for search again and once that depth first search is completed it will probably have you know gotten to its base case and ended up returning after that we can then clean up meaning we can take the count of the value and add it and add one to it right and also then take our permutation and pop from the ending so basically remove the value that we just ended up adding and so this is going to ensure that we do not have duplicates and we also end up getting every single permutation which is why we're going through every single number in our account hashmap and lastly since our debt first search function is complete we only have to call it and then we know our result will have the correct value so we can then return our result and as you can see this is about as efficient as you can get for this problem even though this is super brute force i don't even know what the time complexity is it's at least i think o of n times 2 to the power of n because 2 to the power of n is it might even be n factorial i just know that every time we make a copy we're doing this n part you know there's at most n factorial different permutations for a list of size n but i hope this was helpful i hope you understand a little bit more of what's going on in this problem if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Permutations II
|
permutations-ii
|
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking
|
Medium
|
31,46,267,1038
|
561 |
group this integers into n pass A1 B1 a to B2 substitute a and b n till the sum of the minimum of a comma B for that pair for all I is maximized return the maximize sum so what do they say in the question so they are given in aperture 1432 and that is of 2N the we can form in the given okay you could see one four three a base which you can form is 1 4 then 1 3 1 2 then 4 3. 42 then what else three two these are the best you can perform but what we need is we need to return the sum of all the minimum economy for all is maximum return the maximization that means let's say for example all the possible pairings ignoring the order of the elements whatever present here are 1 4 comma two three means you should form the pairs with the given elements included with this so if you consider one comma four then four comma 3 cannot be considered only three comma 2 is considered by 1 4 3 2 all elements are covered in this if you consider four comma 3 then what else you can consider four comma three means the remaining two is one comma two these two similarly if you take the third one comma three if you take four comma two is the other pair which is formed by this so total of three paths we can perform with all the elements included in that given pairs remaining three two then other thing is 4 3 1 3 next one is one two four three so with the given pairs these are the three conditions right you have to return all the possible pairings with the sum where minimum of these two will give you maximum sum so if mamma this pair is 1 so 1 plus here minimum is 2 that will give you 3 yes answer okay so next pair you will take it this is three minimum one minimum so three plus one that will give you 4. next again if you consider one comma 2 1 is minimum and 4 comma 3 is minimum again it will give four so what is the maximum sum that is obtained from taking minimum of the press maximum sum maximum of the sum obtained from taking minimum of the pressure take a minimum of each parent minimum of each value with that which pair whichever which combination of pair has given a maximum sum either this or this you have to write down this maximum sum this is what we need to write so you could see this is the maximum sum which is giving us okay this should be one comma two so here it should be 4 comma 3 1 comma 2 already taken right so you cannot take this so the second pair is nothing but 2 comma 4 1 comma three if you take this one and two so that will give you some S3 okay so this is the maximum pair which is what we need to return so I rewrite this so 2 comma 4 maximum sum is what we need to return so what is approach to solve the problem do we need to create all the pairs and then find minimum net of all the pairs and what is the maximum out of all the space no let's say let's we are sorting this array okay so if you saw this array this will give you four three two one if it if you see the maximize sum in these two so here it is one and three state connected consideration right so if You observe one and three one or three there at the alternate positions yes and they are not taking first element why first element is the highest element the height cannot be a minimum of the pairs for sure if we take highest element in Array can it be a minimum of any other numbers on Direct no because this itself is the highest array so any element will take care that will be minimum let's see let's take with we take the unit so four comma three we will give you three so this part is that next remaining part what you have two common ones that will be only pair so in this one will be the winner so or every alternate number that is especially the second alternative number starting from the array will be the minimum numbers let's say we take the example six five four three two one if you see this combination also what is the maximum sum you can get it so 5 3 1 5 plus 3 plus 1 that will be the maximum sum you can get from the minimum of the pace because let's say we start with the highest number six so any number with this should be smaller than 6 that will be the minimum of the pair so 6 cannot be the minimum pair so we can discard 6. so other number one we can take let's take the next highest number only five it can be a minimum back instead of making smaller one let's take the highest number so if it is highest number six and five which is the minimum of these two so that we can get the maximum sum if we take any other number six comma 2 this won't give you the highest the minimum of the number this will go to but if you take the next greater number that is 5 because since RS is decreasing order if we take the next element to 6 only that will give you the highest minimum number five so this is why we are taking this okay once this is done next move here if we take four currently in this part of the array 4 is the highest number so if we take instead of four then one that will give you one as minimum if you take 4 and 2 that will give you 2 as minimum if you take 4 and 3 it will give you 3s minimum which is better 4 comma three right it's the next number to four itself is a mineral number so three is taken into account 35 alternative number one that is why we saw the array in the descending order so that we can get the highest maximized minimum sum in the correct so we shall code this first we will have a variable called In Sum equal to 0 and for each number I equal to 0 I less than nums dot size I plus okay I do need to give I plus condition we can use I plus equals to 2. okay why they are given for sure it's a rf2 and integers so it's a even length and every alternative second number will be taking into account so sum plus equals to numbers of I Plus 1. here it will not take zeroth element in the community from first then three then five so on so at last return sum the record is missing here yeah before doing this what we need to make this step we have missed out that is what sorting the array this step so first we need to sort the array right so salt off added out begin come on I'm start okay so here it should be reverse begin they were sent because we have to sort it in the decreasing order that is the reason so we'll run this yeah for Java also same logic do the reversing in the decreasing order with increasing order relief we have taken so if we take it in equation order only one two three four we have to take first number third number next again I'll take a fifth number so that is why um I plus one here we are taken amps of five plus one but here we have we will take M sub 5 because array sorted in the increasing order um 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 next session until then keep learning thank you
|
Array Partition
|
array-partition-i
|
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_.
**Example 1:**
**Input:** nums = \[1,4,3,2\]
**Output:** 4
**Explanation:** All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
**Example 2:**
**Input:** nums = \[6,2,6,5,1,2\]
**Output:** 9
**Explanation:** The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
**Constraints:**
* `1 <= n <= 104`
* `nums.length == 2 * n`
* `-104 <= nums[i] <= 104`
|
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try to find the pattern.
|
Array,Greedy,Sorting,Counting Sort
|
Easy
|
2112,2248,2261
|
198 |
so in this video we are going to solve one very interesting algorithm that name has been given the house with our interesting name so thing is that you have given one array and the each index has the value so you can consider that each element of this array is a house this is the houses so each house has a certain amount of money there so each house has certain unit of money Associated right so you can consider this house has the two unit of money this house has the seven unit of money right but so Thief can go and they can move the house but condition is that heat cannot robe adjacent house due to some the security system so if you if Thief you Loop the house this house right so you know this is the index one two three four you can consider this is house number zero so if T probe house number two they cannot go they cannot enter the adjacent house saver but he is free to go any house so maximum possibilities he can remove this house after that this house and after that this house because this adjustment house he cannot do that and this adjacent of the nine he cannot do that so if you see that in this way he can take the maximum 2 9 1 so 2 9 1. so 12 amount of money he can resolve right but other possibilities are there it is not necessary he has if they enter this house they have to enter the this house no he has the option accept the adjacent he can go any house so in the case he can go this house then he cannot go seven anyhow he don't want to go nine he can directly come to the tree this is also possibilities so in this case if you see but after three he cannot go this house right so in this case how much maximum he can uh you know two plus three five other possibilities are there he will not love the first house he can directly of the from Seven from the first house not the GEOS you can start from here so if they are over the seven he cannot come here he can directly come to the tree right but once he evoke the 3 he cannot go the one so in this case he can go maximum 10. so you have to find out which house that Thief can enter so the return should be the maximum right so in this case if you see 12 is the maximum and the good options are there they can start from second zero house means this house then this house and then this house but it is not necessary that always they have to start from the first house right so that might report and also go the alternative that is not the question so suppose if one more house would be there and that value has the 20. in this case how you can get the maximum so of course if you start from the two suppose you go the two first he got the two amount of money then he goes the nine he go the one but if you go the one he cannot of the 20 right so either they have to now think after nine they had the thief has the two options either they can go the one or they can go the twenty so of course they will go the 20 and they will have total two plus nine plus twenty two plus nine first twenty he can get the 31. right so you have to find out which house keep can go to get the maximum meter this is the problem you have to solve that right so if you see each house foreign so if you start from the zero if you start from here the tip is going to start the row so here they have the two option either they can evoke the house zero get the amount of two but they will have the option he can remove next time after this house he can rope the either nine three one right with the four time being so he has the option nine three one means after 2 he can go this house right if they choose the first house if they will not choose the first house what option they have they option they have he can go nine seven nine three one right if they don't want to think start from the two so they have the these options right again each house they have always the two options so suppose no he already wrote the first house now here they have the option nine three one right so he has already taken the nine now here they have the two options either okay they can go three if we go for the three they have if they go for the nine they have only one option that is one but if here if they go for the three they don't want to go for the nine so two has already taken so they will have the option only two and three because if the moment that we take the three they cannot take the one so they will be these options right so in this case they will get the 12 in this case giving the five now here if you start from the seven so if they take the C1 they have the different options three one right here they cannot deny if they will not take the seven right what the other option they have the string option nine three one right so suppose after seven he choose the three then he cannot take the one and here they choose the nine when the moment they be choose a 9 they have only one option for the one so here you can take the 10 here they can check the 10 here five so in this case this is the 12 so the best idea option is the two nine one to take the maximum one but have you noticed here that each time Chief has the two option whether they can keep that house or they should not go up that house right so each step at each house he has the two option without that house or do not to you right so if suppose they are the at the position of the nine whether they want to hope this house or they don't want to leave the house so when they love the house because they will check if I go to the house we I am getting the maximum benefit or not if he's not getting the maximum benefit and he's getting the maximum benefit after the nine so he will not go up this house he will go the next house right so how we are going to solve this so first we will try to solve the manually then we try to convert into the code right so let me do that how we can do that the best idea there are many possibilities how we can do that but the best way what I consider this will be the one of the good option to solve that so let me this is index 0 right if this is the array this is the appointment is not there right and suppose this is the uh n this area name is you make another array of the similar size same size and give the name m or anything with the same size of the N so what are the size of the N make the same size of the this array also this is also a array right and they have the index now think how it will work without think how to put just manually think so suppose if they will come at the jio suppose only one house is there only one house and that house number is zero so at the G at this position how much maximum the chip can go so maximum he can keep the loop two because only one house is there next time suppose now they have the two house forget about this part think about only the two house if they have the two house how much maximum they can have if they have two they could not remove the seven so good option is that he can evoke the chamber so team house number one his maximum tip amount is the Seva now come to the nine so once he will come here so whether they should keep or not keep and what is the maximum meter at this position so now if 9 is there so if it is here the maximum possibility is at 2 plus 9 he will skip this part right if so here they have the two option either they can skip they are okay with the seven or they can consider this house and this house which is the maximum next means the heaven so they will go for the available means at the position of two the maximum return is the maximum tip amount is the two plus nine this is the maximum possibilities right come here so what is the maximum possibilities here because till 2 they have already earned the 11. so here what option is there if they will keep that here this amount the three amount so that means he could not keep this one he could have come from here so if there were Thief here so till one position there was the seven and the third position they will get the three so they can maximum the seven plus three they can go the ten but why they will go that 10 because they have already the arable so they will skip this house they are happy with the available again I will visit this part and come to the nine so nine have the option that either they can rope the house so he will check the previous house is the eleven this index 2 and this amount one twelve so they want to go up the house because they are getting the more than this value right let me again repeat this part suppose if any position suppose you are at the nine suppose you are at the ninth right and their index is 2. here you have the two options means first part is not problem second part is not problem because first part is the only one option you can put and the first house you don't have any option what is the maximum between the two seven you can put but we start from the nine one right so nine what you will do what is the value of index 2. the index 2 value is the 9 so you can check that 9 plus PVS to PBS house how much money was there because you cannot move the previous house it use of the nine right so what is the previous to previous value so we have already calculated previous to previous values too so at this stage you have the option nine plus two 9 means at the present house amount and this too means previous to previous how much they have already accumulated so two this has that this option another option heavy not above the house if you don't have the house there we have the previous house amount right if his house amount was the seven so this is the saver so they have to choose between the seven and the available so obvious L1 is higher they'll be put that now just consider for this fourth house in this house we have used the one index Pro and what is the previous to previous PBS to previous value is the available so they will check this value yes they will take the previous house value previous five accumulated index 3 is the available so of course this is the greater debut for the giveaway time right so now let me again repeat the same thing what actually I am trying to do here at any position suppose at the nine is the I index suppose this is the i is equal to 2. they have the two option right what two options they have either they can go for nine plus two means the value and index I n i is the value 9 Plus this is the mean right this is the memory I minus 2 because what much value is already accumulated previous to previous how you will get the previous to previous you have to do the minus 9 right this is the one option they have other option they have they will not Loop this house and they are happy with the previous house in this case if you see this house when he was doing here so he checked these three index 3 plus 3 minus 2 this value 3 minus 2 1 mem1 is the 7 either they can take the 7 and otherwise is Happy how much was the previous one right so he compare between the 10 and the 11 so 11 previous house everyone and he didn't drop the house so other option is that he can do Main I minus 1 so each node has this is only two option so what are the maximum of 2 will be put into the index and if you see for the each index we are keeping the highest value and memorizing this highest value it is easy for the calculator to the next house and this is called the dynamic programming we know that we are doing the normalization of the value so this is the whole Logic Let me just uh put the code in two minutes we understand so what if you do will you create first check if n dot length is zero means if that is the empty then no need to do anything we tell jio value if n dot length is equal to 1 means only one element is there so we turn the same element right we are not doing anything right otherwise what you have to do you take create one in Array of the name and size would be the same size what the size of the given average there right and then run the loop from second why second because this Two element I am going to fill so name U is equal to same what is the zero because suppose this is only one element name one here whatever you want to put what about the maximum of these two right so max of Max of NGO and N1 so these two things we have to do the manually then we can go the follow we start the forego from I is equal to 2 I is equal to n minus event I plus and put this logic means in this name I would be the max of this as it is Copy Max of n i Plus name I minus 2 is name I minus 1. and we turn the last index of the name that is the resumper let's let me show in the code so again I want to repeat that each point you have to consider that either you have to rope this house or you are happy with the previous house accumulated the money right that's just two things you have to think and all the algorithm is depend upon that right let me go to the code if first check if nums event is equal to zero then we have to return the zero right because data is not there and second if they have only one element right so we have to check if they have only one element then we have to return the same element right so we can return the same element right otherwise we have to create one meme that is if we keep the memory for the new element and size will be the same nums event right and in this name so first element we will keep what is the first element of the given array but second element we have to choose what is the we use the Java math Max in between the nums 0 and nums one right and then onwards we will use the for loop I will start from 2 because 0 and 1 we have already considered here right so now this event is equal to nums dot rent and I plus and just one statement name will be store which value we store the math this is the logical and Main Line site Max bit bin nums I Plus whatever we have over these 2 I minus 2. previous to previous compare with the I minus 1 just PV who is the maximum put it there and we have to return the final this last index of the membrane so we turn Main nums dot length minus one is the last element that's it so just run the code it should work so even if you want to with the different test cases so suppose I am going to give this or give this test cases what we have discussed on whiteboard so if you give this one and again run that code it also suit to 12 should become it is coming submit the code and see you should accept it with the jio uh milliseconds thank you very much don't please don't forget to subscribe and share any questions you have you can top the comment box
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
5 |
he was a guy's knee right here I do taking coding stuff on twitch and YouTube check the description for all my information join the discord got the community and I got the study guides I'm working on patreon so just stay aware we got a very popular problem longest palindromic substring number five one of the earlier ones so given a string s find the longest palindromic substring and s you may assume the maximum length is a thousand okay so we're given a method and we want to find the longest palindromic substring i would recommend doing a longest palindrome there finding if something is a palindrome first or doing some substring problems this one's a little more advanced we're gonna be given a string and we're going to be looking for well first of all if you don't know what a substring is a contiguous sequence of characters within a string for instance the best of is a substring of it was the best of times because the best of is part of the best of times right a palindrome is a word that can be spelled the same way forward is backwards okay so if we are looking for the longest palindrome let's just look at the examples here the longest palindromic substring in this a substring can be 0 characters it can be the whole string it could be 1 character it could be BA it could be B a B it has to be contiguous so the longest one that is a palindrome this that spelled the same way forward as backwards is BA be because BA is not the same way forward as backwards BA D is not symmetrical and not the same way forward as backwards so BA B is the longest palindromic substring ABA is also a valid answer so those are the only two and they're both sides three so we return either of them right c BB D is when we look at C BB D we are looking at BB is the longest palindromic substring because these the C and D are not symmetrical there's no way we could add those on right so there's a few ways to for us to do this problem and there's a ton of YouTube videos doing dynamic programming but there's a better solution I'm going to share with you here and there's an even better solution than the one I'm gonna share with you but that one's not expected in the interview so when we look the first way we could solve this problem is if we're given a string it could be smaller it could be big like B a B ad we if we want to find the longest palindromic substring first thing we could do brute-force whenever you go into an brute-force whenever you go into an brute-force whenever you go into an interview problem maybe start off by thinking what's the brute force what's the worst way to do this and then we can improve it well the worst way to do this if you guys didn't know you can generate all substrings of a string in N squared time and then you could go through those and then we'd have to a to check if a string is a palindrome is also linear time so it would be N squared times n which is going to be O of n cubed which is pretty slow we want to get down to N squared time complexity here so the brute-force time complexity is going to brute-force time complexity is going to brute-force time complexity is going to be O of n cubed right and I guess I could write fruit force right and the way that we're gonna do that is you just basically do a for loop through each letter you do it and then you have an inner for loop that for each letter it goes and it goes okay be is 1 we have one outer for loop that sees B and then we go and have an inner for loop that goes okay ba okay and then Bab and then okay ba D right and it generates all of the substrings for each specific character and then it goes to a right it goes to a and then it goes okay a B right you know what I mean and it keeps going all the way through it generates all of these substrings right and then after while it does that it also has an inner another loop that is checking whether or you could have a helper method but it's gonna have to check whether each of these is a palindrome and it's gonna have to keep track of which one is the longest so that's a very slow solution a better way to do this is one thing that you might notice about substring palindrome is that there's two cases for palindromes there's one case that is normal right a vba right that's a normal case right and this is looking like okay we if we started from the middle of the string and weeks had pointers and we expanded outwards we could say okay we have a left winner and a right pointer and start point we could say is this B are the characters on both sides the same and then we can keep expanding our boundaries to the left and to the right and keep checking all right like if this was the string we could start here and we could say we could have a left pointer at the middle and a right pointer at the middle and we could say okay this B is equal to this B this a is equal to this a and keep expanding until either the characters don't match anymore or we get to the ending of the boundary and we're gonna go out of bounds and we can keep track of the length that way so that's the way you're gonna do it because that is the fastest way to do it in this problem and there's another case though where you have something like race car and you don't really start checking you don't start checking the two characters at the same time because we would check like a and C or on one of the sides and that would be incorrect so what we do is we check this which we check we start at the middle point and this is just a special case because in a palindrome there could be that one character in the very middle that doesn't have a matching character all of the characters have matching characters those are as a matching character to say is a matching character the very middle one might not so what we're gonna do is we're gonna expand from the middle and we're gonna get this down to o of N squared I'm gonna write it out and then we'll kind of go through so the first thing that I'm going to do is I'm gonna write our expand for middle methods so it's gonna be an in it's gonna just return the length of this palindrome substring after we expand right so we could call it expand from middle or expand around Center or whatever you want to call it's just gonna take in a string as a left boundary and a right boundary and first thing we're gonna do is we're gonna say okay if s is equal to null or if left is greater than right then the boundaries are messed up or the string isn't all that's my stuff so we're just going to say zero there's no palindromic substring to return here otherwise what we're gonna do is we're gonna have our loop and we're just gonna say like I said if we're looking at a BBA we start from the middle we're gonna have a pointer to the left side like l would be equal to index 1 right would be equal to index 2 in this string and then what we're gonna do is we're gonna say okay while left is greater than or equal index zero and writes is less than or equal to s dot length so the last index are not less than or equal to just less than and the characters at those positions with those pointers so STR at left is equal to STR at right so if we're expanding from the middle and the characters keep being the same then we're going to remain in this loop and we're gonna keep expanding our boundaries so what we do is we just decrement the left pointer to keep going more to the left in the right pointer simultaneously to just expand it to the longest possible string where the character is continuously match and we keep we were it remains a pound room when it breaks like I said that either means we find like in this case if we started here we'd see okay we got a B and a B as a match but then a CNN a don't match so we'd break out and what we want to do is we want to just return right because right is gonna be the higher value minus left plus 1 because we're dealing with indices here right so this is going to be just our method to take a string expand from the middle of the string or from some point in the string and find a palindrome right now for the part where we just okay at first we can do some checking at the actual method level we can just say okay if s is equal to know or you know s the length is less than 1 then we're just going to return an empty string we're returning the longest palindromic substring that if it's an empty string or if it's less someone then there's nothing right we're not returning substring right so then we're gonna have a starting and ending boundary and this is going to be the boundaries which we grabbed a final substring at the end to return from so we're gonna adjust these boundaries based on these palindromes that we find while we're looping right so now we're just gonna do a regular event loop through the string we're gonna say eyes less than s length and I plus right we're just looping through the string letter-by-letter-by-letter-by-letter and what we're gonna do is handle those two cases the case where we have the middle character like race car right where race car has that one special middle character that doesn't have a match and then we're also gonna have to handle the case where it's just a regular pounder like a BB hey bb hey where the every character has a match so to handle those characters we are going to check length one is going to be equal to a call to our method expand from middle on s which is just our string that we're given and we're gonna pass in the boundary of I so the current index were out we're looping through each character we're gonna call it on I and we're gonna call it on I again so this handles the case where we start from a character and we want to call it to start from the against the same exact character so when we do this check when we pass in left and right it's going to be the same character so when we do SH are left as you go that's our chart right it's gonna say is e equal to E and then it's gonna be a yes okay and then we expand to check C versus C so that handles that case and then we'll check lane 2 is going to be expand from middle except we're handling the second case where everything has a match so we can just do I and I plus 1 right because this would check B and then the I plus 1 would be the other B and we could expand from there then all we want to do is we just want to keep the act of the max of these lengths because we're looking for the longest palindromic substring so we'll just say okay length is gonna be equal to math that max of these two lengths whether we started from this point or whether we started from this point we're just going to say length 1 versus length 2 because one of these could be longer than the other because we don't know which case we're gonna hit so one of the cases could be correct and we're gonna hit get a longer string from one of them so we take the math maxes of those strings and then all we have to do is check ok sorry we have to put an equal sign here if Lane is greater than end - start Lane is greater than end - start Lane is greater than end - start so if length is greater than the boundary of our substring we're going to get from our final string that means we found this is almost like setting a new max this is like setting our boundaries for the new longest palindromic substring it means we found the new longer substring so we'll adjust these boundaries and we're gonna set start will become I so the index that we're at and the index we're at is going to be the center of a palindromic substring so the start is going to have to be subtracting the length divided by 2 the end is going to be adding the length divided by two so and we're dealing with index out of bounds and stuff like that so we have to be careful here because we don't want the boundaries to go out so we'll do I it's - and then we're gonna we'll do I it's - and then we're gonna we'll do I it's - and then we're gonna do length minus 1/2 so this will take do length minus 1/2 so this will take do length minus 1/2 so this will take that palindromes length and the starting boundary will get set to the index the middle of the because we're gonna be checking like you know I mean if we're returning we found this right and this is one two three four five six seven length seven right and we're like okay we found a new longest palindrome we returned that we found it at this index then we want to take seven divided by two and put our starting boundary to the left and then make our right boundary to the right so we want to find those correct things indices hopefully that makes sense I know it's kind of its kind of tough for me to explain and then this one's just gonna be I plus length divided by two and then this is the way the reason we do the minus one is because of index out of bounds and then all we have to do here is just return s dot substring of our boundaries that we get in the end n plus one this is all just index out of bounds the plus one and the minus one stuff so that's the whole solution that is o of N squared compared to the dynamic programming where the dynamic programming has what did we do wrong all right crap guys my bad it was just I accidentally did plus instead of minus because I'm gonna so that was my bad I'm really I'm just gonna edit this together because I don't want to redo that whole thing sorry about that but basically what happens just to recap one more time I'm just telling you the solutions here I don't think it's that hard to understand the brute force is n cubed because you got it you would have a nested for loop and then you'd be calling to look if it's a palindrome a better solution is dynamic programming but that is a in there's a bunch of videos out there I might do one there's n square time and squared space but this solution right here expand around Center this is N squared time and no it's oh of one space then there's a manicures algorithm but it says you're not expected to know that it's a lot harder to understand this one's not that hard I think you're looping through you're checking for palindromes at each point you're looping through at each index so when you look at a string like race car you're gonna go R okay start at R and start at R plus one you know call this method twice on this position zero and zero put one and expand from those points and try and find the longest substring and then you just keep a maximum as you go through because eventually you'll get to a middle point like E and you'll find the longest palindrome right and over you just it just does one loop and then here's another at worst case another loop and that's ten squared and I think it's pretty basic to understand nobody made a video on this so I decided to thank you guys for watching sorry about that mess up at the end here so let me know what you guys think about this and yeah that's pretty much it please like and subscribe I really appreciate them in the supports the channel and let me comment below what videos you want me to do next thanks for watching and I'll see you in the next one
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,640 |
hey there everyone welcome back to lead coding in this video we will be looking at the solution to problem number one of lead code weekly contest 213 name of the problem is check array formation through concatenation now you are given an area of distinct integers and an array of integers array pieces where the integers in pieces are distinct your goal is to form given array by concatenating the arrays in pieces in any order that we want however you are not allowed to reorder the integers in each array so we are given an array and we are given an array of arrays so basically we have to arrange these areas so that we can obtain the given array for example let us see the example number two so here there are two arrays containing one element each and we can arrange them first we can take the array which contains the element 15 and then we can take the array which contains the element 88 and we can form the given array using these two arrays again if we look at this example so here so we are going to pick up the last array then we will be picking up the array at the index 2 which is 4 and 64 and then the array which contains the element 78 so this is first this is second and this is third so if we arrange them we are going to obtain the given array so this is what we have to do with this problem now the given constraints are the length of array is hundred and pieces to length at max can also be 100 all the elements are distinct that is given to us so how we can approach this problem now what we can do is let us say we are picking up an array inside pieces so we are picking this array now we will be looking at the first element so first element 16 so we will see what is the position of 16 in the given array so the position of 16 is the third position and we will start looking from the third position that if we can get the entire array that is 16 18 and 49 but we cannot get the whole array in this case that is why we are returning false for example let me go to the whiteboard and explain let us say this is the area which is given to us 1 2 3 and 4. now we have 2 and 3 so this is our pieces then we have one and then we have four now we can pick up this array and we can get the element one then we can pick up this array we can get the element 2 and 3 from here then we can pick up this array which will contain only which is containing only element 4 so 4 will come here so we can obtain this using this array now when we are picking up the piece in which the starting element is 2. so we will be looking at the position of 2 is this of 2 the position of 2 is this now from this position we will start looking ahead so we will see this element is matching then we will see the next element so if the next element is matching and this array is exhausted in that case we will consider that this piece that this particular piece is a good fit for this position now let me take a bigger example so let us say we have one two three four five six and in this we have one piece which contain two three four and five so there's one piece then this is another piece and this is another piece now we are going to pick up this first so this part will be exhausted next we are going to pick this piece because the element is 2 here and the element 2 here matches so now we will see if this entire piece is going to fit at this particular position so we will see two is matching with two three is matching with three four is matching with four and five is matching with five so this entire piece is exhausted that is why we can say that this piece is going to fit here and the same thing for 6 so 6 is going to fit here talking about the implementation so what we can do is we can store the index of each of these elements so uh we can go to the pieces one by one and we can see the position of the first element that where the first element is occurring inside the array that we want to form so the position of two is here then from this position we will start comparing ahead so we'll keep comparing till the point either this array is exhausted or the element doesn't match so if the element are not matching and the array is not exhausted in that case we are sure that we have written false in that case otherwise if the error is exhausted then we have to check for the leftover pieces so now let's code the same so as we can see that all the elements are distinct so and the range of the element could be 100 max so we are going to implement this using an unordered map of type int command now we will go to each of the element inside the given array and we will insert for the value at arr of i we are going to insert the index is equal to i so now we have the indices for each of the values and now we will go to all the pieces so for auto a belongs to pieces let us denote it by b now uh we need to find the first element of this particular piece so it is int x is equal to a of 0 this is the first piece now we need to find the position of this first piece let us take this as j so j is the position so j is equal to m of x now int i is equal to 0 while i is smaller than so basically i we are taking for i we are taking is a pointer to this array a so i is smaller than a or size and j is smaller than added or size now we already have the position uh inside the array which is j so j is smaller than error dot size so we are going to compare them if a of i is not equal to arr of j then return false as i told you we have to return false if the elements are not matching otherwise we have to check for the further elements and we can increment i and j now after this loop we have to return true let us see if it is working so it is giving this correct answer for this test case true false oh we are getting a false for true so why are we getting a false so both this condition should be matched we have a problem here this is i is smaller than s i is smaller than error.size and one s i is smaller than error.size and one s i is smaller than error.size and one more thing we have to check if m dot find x is equal to m dot end then in this case we have to return false let us try to run this so we are getting a true and we should get a false in the third case yeah so basically we have to return all right if i is not equal to a dot size then we have to return false and now we are getting correct answer let us try to submit this and it got accepted now talking about the space complexity we are using extra space here so in the worst case uh i think all the elements are different so it is already the worst case so we have to use big o of n extra space where n is hundred in this case and talking about the time complexity so this loop is running for all the pieces and in the worst case we can have 100 pieces and this loop is running for the size of a particular piece so basically in total this is going to be big o of n so time complexity is big o of n in this case so this is it for the video if you like the video please subscribe to the channel and please share it with your friends we have already uploaded this solution to problem number two and three of the same contest and we will be uploading soon the problem number four of this contest so stay connected hit the bell icon so that you can get the notifications thank you
|
Check Array Formation Through Concatenation
|
design-a-file-sharing-system
|
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`.
Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\]
**Output:** true
**Explanation:** Concatenate \[15\] then \[88\]
**Example 2:**
**Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\]
**Output:** false
**Explanation:** Even though the numbers match, we cannot reorder pieces\[0\].
**Example 3:**
**Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\]
**Output:** true
**Explanation:** Concatenate \[91\] then \[4,64\] then \[78\]
**Constraints:**
* `1 <= pieces.length <= arr.length <= 100`
* `sum(pieces[i].length) == arr.length`
* `1 <= pieces[i].length <= arr.length`
* `1 <= arr[i], pieces[i][j] <= 100`
* The integers in `arr` are **distinct**.
* The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
|
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
|
Hash Table,Design,Heap (Priority Queue),Data Stream
|
Medium
|
355
|
509 |
let's do another one its five-year the let's do another one its five-year the let's do another one its five-year the prick is gonna okay for the Fibonacci numbers comedy you know as ever file form the sequence curve not sequence such that each number is sum between two previous numbers given an calculate F a fan okay and n is less than dirty huh so I mean so this is pretty straightforward only thing that's a little tricky is me trying to think is better from Valachi of dirty is fits in double or not double a long or a 64-bit in the Jo Durie to a long or a 64-bit in the Jo Durie to a long or a 64-bit in the Jo Durie to a bit integer but uh but if you remember your math class I think their nth Fibonacci or something like 1.6 to the N Fibonacci or something like 1.6 to the N Fibonacci or something like 1.6 to the N so and that's strictly less than to the end so what that means is that you know what 1.6 to the dirty if it's know what 1.6 to the dirty if it's know what 1.6 to the dirty if it's always going to be less than you know two billion or whatever well to burn is technically two to the 31st not to the dirty too but that's the way I would kind of convince myself that it would fit in a you know 32 and 32 a good end okay so having dad said I guess we're just code it up I prefer see just cuz I don't know this is like four lines of code at max so I think you could do some fancy stuff with like you know keeping it away and look at st. last two items but I think you guys should just okay actually that's what I end up doing I mean I think you could do some fancy stuff of having just two registers and then keep on swapping the back and forth I think especially let's say if I was in an interview what I would try to do is kind of do the thing that minimize typing typos and stuff like that an additional just kind of making sure the code is concise so that's what I'm going to do so oh it's a saucer one okay because Tibet and some people started at one with some Deana yeah and you know you may wonder why disorder blankets you may wonder why I started at 35 it's just because on the problem is that n is less than 30 so I just wanted to get a number that's obviously bigger than joy to you I mean yeah because what you don't want to do is kind of have like an off by one and then you know have to be off by five so just this should be good I mean that's I'm yeah so like I said this should be pretty straightforward I got one Dakota TAS okay I mean I guess I just is too high okay further okay I got more test cases oh let's just see dirty just to make sure yeah so there you go so I mean I think that's enough to for me to be convinced that I finished it Pam okay I mean apart I mean if I use two registers I could probably do this faster but I don't know it's not what I'm not different rising for so that's why oh cool so that's my two easy problems for the day
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
779 |
hey everyone today we are going to solve the Ral equation case symbol in grammar first of all we have rules so if we find a zero then Z creates a 0 one in the next row and if we find one then one creates a one zero in the next row so this is a very important rules okay so question is how can we find the answer so look at this example and uh look at this one so where did this one come from so the answer is one in low two right and how about this one so this one comes from this cell right in low two and look at the Row three the first two numbers I mean these two numbers so these are created by zero in row two right and look at these two numbers so these two numbers are created by one in low two right so uh these are kind of pair and the key point to solve this questions are if we know parent of the pair and if we know um the position in the Target pair we can find the answer okay so first of all how can we find the parent of the target pair so let's focus on row two and Row three so I put a k number in each row so zero is a K1 so k equal one so one is a k equal to and this Z is k1 and K2 K3 K4 so K1 in low two creates K1 and K2 in low three and this K2 in low two creates K3 and K4 in row three so yeah actually we have pattern so pattern is by dividing the value of K in low three by two and then rounding up rounding it up you can obtain the value of K for the parent in low two so let's calculate so let's say uh K2 in low three so K2 is a two right and divide two that is one right so that's why um this K2 comes from K1 in low two and uh let's uh take a look one more example so what if k equal 3 so 3 divide two so that is a 1.5 right 1.5 and as I two so that is a 1.5 right 1.5 and as I two so that is a 1.5 right 1.5 and as I told you we need to rounding it up so that's why in this case two so K3 is actually comes from K2 in low two and uh that's right so this K three comes from this K2 right so looks good so that is how we can find the parent okay next how can we know zero or one in the Target pair so now we can know the parent of the target pair So my answer for this question is very simple so again so we have rules so zero create a 0 one right and one creates one zero so we can say if we find a zero parent then first portion of the target pair is zero if not one on the other hand if we find one parent then the first portion of Target pair is one if not zero so very simple point right okay so next question is how can we calculate the first position or second position in Target pair so this question is actually very easy uh seems like we can use a odd or even of K so look at the this so first two numbers are pairs right and uh these two numbers are pair and look at the first number in each pair so k equal 1 and k equal three so um uh the first position of pairs is all K value right and I look at uh this uh position and this position the second position of each pair is even K value right so we can use a like a OD or even um strategy so and I look at this Sol part of solution code so we calculate a parent before and if parent is one so this case right if um K value is a like a result of calculation with k value and uh if K value is all in the case we should return one right so one right if not the casee return zero and else so that means parent is zero case so this case if um K is old so we should return zero right and if not return one looks good yeah so that's how we can like find the parent and uh the position in Target pair yeah that is 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 if n equal one in that case we can immediately return zero right if not the case um so parent equal so we call case grammar function reiv um so self dot so let me copy this case grammar and uh so we start from so n and K position and uh so this is a calculation of parent so parent is um basically is located at like above row right so that's why uh we subtract minus one from n so n minus one should be above row and uh the position should be as I told you um basically k uh divide two but uh sometimes we have like a 1.5 like a decimal point so have like a 1.5 like a decimal point so have like a 1.5 like a decimal point so in that case we need to round it up so Mass DOT uh C and then kide two so K should be up K and then after that um we calculate the position in Target pair so let's say is all and uh this is a result of calculation with K so k um divide 2 equal one in the case um if this result of this calculation is one so we have true in is OD if not false right and then if parent equal one so in that case um so we should return one if is what is true if not the case return zero so lse so this is a case where parent is zero and this should be actually reverse of this so if is all is true so we should return zero and if not the case we should return one yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of n log K so we Execute Order of log K operation for each row and we have n row so that's why and the space complexity is I think o n so this is for stock space of recursion 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
|
K-th Symbol in Grammar
|
max-chunks-to-make-sorted-ii
|
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`.
* For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`.
Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows.
**Example 1:**
**Input:** n = 1, k = 1
**Output:** 0
**Explanation:** row 1: 0
**Example 2:**
**Input:** n = 2, k = 1
**Output:** 0
**Explanation:**
row 1: 0
row 2: 01
**Example 3:**
**Input:** n = 2, k = 2
**Output:** 1
**Explanation:**
row 1: 0
row 2: 01
**Constraints:**
* `1 <= n <= 30`
* `1 <= k <= 2n - 1`
|
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
|
Array,Stack,Greedy,Sorting,Monotonic Stack
|
Hard
|
780
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.