id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,046 |
hello everyone welcome back today I'm going to be changing it up a little bit and doing the problem of the day on lead code so if you're struggling with that at all hopefully this video's solution will help this one is a Lee code easy it's probably a harderly code easy in my estimation uh let's just jump right into it I plan on doing the liko prom of the day on this channel the foreseeable future the only issues might come up if I'm not home and I can't get to my setup and actually record the solution to the problem then it might take a couple days for me to get back to it and record a solution so in this problem you're given an array of integers Stones where Stone's eye is the weight of the eye stone so pretty straightforward so we have a in this example wait two wait seven wait four wait one wait eight wait one stone we were playing a game with the stones on each turn we choose the heaviest two stones and smash them together suppose the heaviest two stones have weights X and Y with X less than or equal to Y the result of this smash is if x equals y then both stones are destroyed and if X is not equal to Y the stone of weight X is destroyed and the stone of weight y has new weight y minus X at the end of the game there's a most one stone left return the weight of the last remaining Stone if there are no Stones left return zero so in this case we can kind of Step through what they say here we start off with eight seven two four one so you take eight and seven smash them together since they are not equal we now make the weight the larger one minus the smaller of the two so we get a weight of one so two four one we now take two and four the two largest smash them together we get a new stone of weight or minus two since four and two are not equal so two is our new stone and then take two and one from this smash them together they're not equal so now we get a new stone of two minus one which is one and I'll take the two largest here one and one they're equal we smash them so we're left with just one stone which is one so we would return one and then in this case we just have one stone so obviously we're just gonna we're already at the end condition so we can see here the Stone's length is not that long which actually might be why it's considered an easy you can actually kind of see a hint of the way that I want to solve this especially if it was a larger array uh we'll get rid of this for now but essentially the first solution that we could do is simply there's kind of two N squared approaches that I'm thinking of here the first one is to just iterate through the array and find the maximum take it out or I guess what you can do is you can to have a quicker deletion you can swap it with the last element because the order doesn't really matter and then delete that last element and then do the same for the next Stone oh first of all we're doing this all while Len of stones is greater than or equal to two because once we get down to at least at most one stone we're going to stop so essentially what we would do is for I Stone in stones we'll have like a our Max index equal to zero to start we'll say if stone is greater than Stones Max index equals I so we're going to update Maxes and we're gonna have to do this twice so then what we would do is we would say Stones negative one Stones Max index I have to shift over a little bit equals Stones Max Index this is how you swap numbers in Python and then we would simply just uh assign I guess X to be Stones dot pop and then oh sorry this should be here um and then we're going to do this same thing again but for y I know it's bad to copy base code but this isn't the solution that I'm really looking for if I'm an interviewer so I'm going to try to keep this as short as possible but now you check well first let's sort these so we know that X is less than or equal to Y like they say now if x equals y then we're just going to continue we've gotten rid of the stones otherwise y minus equals X and we can append y is we're creating a new stone of Y minus x value and then outside of this while loop we're done with all the stones so we can return Stones zero ifstones else zero because they want us to return zero if there are no Stones remaining now if we run this oh whoops I forgot to enumerate this here so now let's try that again I forgot if I copy paste this is why I don't copy paste code you have to change anything you'll have to change it in multiple places but okay so the very two basic test cases pass this is a fine solution considering we're only dealing with length 30 at most but it is of N squared because it's going to take um well you could have to go through it and over two times because you're smashing two stones every time and then potentially creating a new one so it's O of n um times whatever is within that Loop but within this Loop we have to go through each of the stones and figure out what the maximum element is so that's also going to be that's an old event thing so n times n gives us o of N squared we don't want to do this solution if we're in an interview obviously it's fine to have this as your first solution but when you're constantly having to get the maximum element you might think you want to sort it but you actually want to use something called a deep so uh I'll use uh oh actually import what we need and not everything like I had before with the star but essentially a heap is something where the first element within the Heap will be your minimum element within the Heap and then everything it's designed as like a tree where you have the minimum and then everything below it will now be less than or I guess greater than the minimum element and then in the right subtree you have this node has some value X and then everything below it will ha also have a value greater than or equal to X so it has this nice property where the root of the tree is the absolute minimum in this case we want the maximum python implements it as a minimum Heap so we're gonna have to do a little bit of finagling here where we get the negative or the negation of each Stone and then we can keepify this and now instead of having to do this stuff where we find the maximum there's a nice thing that we can do where we just do actually we don't have to get rid of everything because this stuff should stay we'll say x equals keep up stones and why let's keep up Stones then we still want to sort those two we want to just make it so that X is the smaller one x equals y continue now instead of this we will keep push why so essentially what we're doing is we're getting the two maximum that maximum element and then the after you heat pop the Heap will now rearrange whatever it needs to so that's the new maximum or I guess yeah our new maximum is at the top so we heat pop again so we have the two maximum elements from our stones we now check to see if they're equal if they are then we don't need to do anything else we've already destroyed them otherwise since they're not equal we need to make we need to create a new stone of Y minus x value we now keep push that so that just means put this in our Heap and if it needs usually you put it at the bottom and then if you need to oh sorry I just realized this should be a negative why because we're doing a bunch of negation stuff here and since we've negated everything here we also need these two to be negative that should work now um but yeah essentially the stone that we've created will now bubble to the Top If it is the maximum element or it'll rearrange itself so that it is within or is where it needs to be to maintain the Heap structure that we want the complexity of this is now well we have n iterations here n over two and it doesn't really matter o of n iterations and then this epop I not 100 sure I know it's either login or constant um it's at least at most login so I guess all of log n and then this is constant because there's only two elements this is constant quality check and then this here is definitely over login so we have n Times log n so our complexity of our algorithm is going to be a little bit okay which is as good as you can do because you are trying to get this oh sorry I also have to return negative Stone 0 if Stones also zero but now we can see well you can't really see very well but the test cases passed and if we click submit It All Passes So yeah thank you so much for watching Hopefully this wasn't too difficult to follow I know if you are familiar with the Heap data structure it would be almost impossible to come up with a solution but I will leave a reference down below probably Wikipedia because I find that's the usually the best resource in terms of explaining things concisely and clearly at least I found that with some other things that I've Linked In the description but yeah thanks so much for watching please like And subscribe and I'll see you guys next time
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
1,937 |
everybody this is larry this is me going with q3 of the weekly contest 250 maximum number of points of course hit the like button to subscribe and join me in discord especially if you're doing these contests um a lot of smart people go over the contest right afterwards in my discord so you know you're into that kind of conversation come and join us uh contribute or just listen or whatever you like to do okay so for this one um i think there is a dynamic programming solution and i did it that way and there's um but yeah but i'm gonna go over so the two things i want to say one is that i did this you know in a virtual contest live and i did it this way i'm gonna give a brief explanation i'm gonna go over my explanation here where i actually apparently i actually don't remember this problem to be frank like it felt familiar i didn't remember but i also solved this on this site i'll go with that i'll go with that i'll go with that solution i think it's a slightly more intuitive um and then i'm going to talk about an optimization to kind of get the speed down but the idea here is that the way that i wrote it during the virtual contest and is that um and this is n times m times log m where m is the number of columns um and the idea here is just okay you know for every row you know you have you get a score uh for you to sell right and this is like dynamic programming stuff so if you're struggling dynamic programming i would recommend working on dynamic programming first and then from that for each cell um you just greedily look at the previous cell and then get the max element that you can get um using some kind of criteria which is um this offset thing right this offset thing that you have to do that you subtract offset so then here the way that i did it is i kind of do a sort of kind of like a sliding window if you will um where okay i look at the left you know for each cell i look at the left i look at the right and i'm i combine them in a way such that i get the max from the left i get the max from the right and then i add it to the current score and that's basically the way that i did here and i did it in a sliding window thing where okay you know every number starts on the right side um and then i slowly pop them off to go to the left and then the rest of it's just math and you know you can work out the math um one by just like keeping track of okay every time i move one element from the right uh shift off by one we add one to everything to the right side we uh we subtract one from everything from the left side because they get further away and so forth so uh and then you just do some math to kind of balance that so that's basically the way that i did it during contest um this was messy i did i spent 25 minutes and the wrong answer um i actually apparently did this in as i said this earlier as i said this earlier as i said this earlier i think this solution is more intuitive in that i pre-processed this pre-processed this pre-processed this um in that instead of doing it in a sliding window kind of way at the same time i just basically pre-process the answer i just basically pre-process the answer i just basically pre-process the answer such that um such that uh yeah i pre-processed the answer such yeah i pre-processed the answer such yeah i pre-processed the answer such that you know i have the answer i can do the lookup of the answers really quickly and by that i mean that okay uh the way that i pre-process it is i uh the way that i pre-process it is i uh the way that i pre-process it is i look at the previous row that's one and on the previous row i go okay what's the cost of only caring about one element and it was the cost of adding two elements with the associated costs and then three elements for that cost and then like with that offset right and you do a kind of a prefix min type thing uh or prefix max or sorry you do a prefix max so then here you add things to that things to the right you reverse the left so then you pre-process it so the left so then you pre-process it so the left so then you pre-process it so that as you kind of go from left to right you know what's the offset you know what's the best thing to the right and then you kind of remove them and so forth um that's the idea that i like here and from that you can actually think of this as um a sort of a mono-q type thing where you a sort of a mono-q type thing where you a sort of a mono-q type thing where you always get the max from the right and um and that the answer only change in a certain things um i have a monocute video that uh you can check out i'll put a link somewhere below i recommend going through that and yeah and that should kind of give you the idea of solving it the way i did this again is r times c times log c where c is the row sorry c is the column then while it's the rows um you can actually optimize this to just r times c um definitely recommend going through that solution um but yeah but if you want to see my dot process in more detail um i'll you know you can watch me solve it live during contests right now let's give it a spin okay that's good okay q3 maximum number of points of course your one cell in each row however you lose point with two south and previous world weapon two and jason rose picking cells at what okay so this is three five three and then you must subtract one distance on distance okay uh this is awkward um this is just gonna be i mean this is dp greedy this feels like something i've seen but i uh it's okay so go here okay yeah i know it's d p but i feel like i have to do a transformation somewhere to kind of make the math a lot easier um because of course here now because if you're sloppy you have two rows of 10 to the fifth over two and that's just not quite ideal i must subtract like this is something like weird mono q maybe is it max of that minus like i'm getting some vibes of sliding window and whatever okay slow down larry and then think okay so you do one scan on the first number and then you have zero one and then next you subtract everything on the right by uh on the next one you add it or now you get closer so you get one more benefit and you add everything to the left do i phrase that and then you get the max of those two components right okay so the defective score would be negative one negative two and then we factor that in and then as we move shift then you add everything on this thing to the right okay i think i got it's a little bit awkward to think about though so um okay let's see yeah i feel like there's a lot of potential mistakes but i think this is okay so let's do it roses you got the link for points columns is equal to points of zero maybe yep okay um i'm just looking for zeros um okay maximum points you can achieve because these all are number not odd numbers but positive numbers oh i'm just trying to think whether there could be negative contribution from the previous row and i think that the answer is no because at worst they're all zeros and then if there are zeros they just take the world previous and yeah and then just take that so okay so then now we have um i'm trying to think so what i'm thinking right now is that i think we can use two heap type things or sort of this in my case to be honest but i'm also just trying to think whether it makes i think there is like a mono queue type thing but on a contest and i am on a contest even there's a virtual contest i'm not going to spend time on that so let's do that so okay so let's start off by doing the first row so okay of course you go to times columns for the first row we go for the best score because we don't have any negative score so this is the base case so then the base case is for c in range of cars um row sub zero of c scores oops my s key is weird let's go to okay right and then now we go okay four are in range of one to rows yeah okay i think we're good and then here we want to go new or next score maybe next course is equal to do um i guess we should we could actually just uh why this is not even a frame but okay um but i can actually set this already to just points of zero so i don't even need this um i know that i manipulate the input now but that's fine i'm lazy so then this is points of r and then now we look at the previous row as we said and we want to pre-process it as we said and we want to pre-process it as we said and we want to pre-process it um yeah okay so then now for previous row let's say for c and range sub cos um was it score sub c we want to subtract that by c zero yeah okay and then now we want to do what do we want to do larry um yeah and then now for c and range of columns we do next course of x square sub c this is equal to or this is we add this to the previous best scores on the left and on the right so let's actually set left is equal to sort of this and right is equal to sort of this i hope this is not too slow from the uh input sort of list and then here we want to get the max of so the max of the left and the max of the right oops so this is going to be the max of the i don't know why type this backwards if it's too late um yeah and then at the very ends we just scored is equal to next scores and also let's just do best is equal to zero that's equal to max of scores so i think we don't have to do this on every iteration we're going to return best now we have to do that for everything we have to slide so after we yeah okay so now after this we want to slide how do we want to slide like the electric slide also this is not sufficient um we actually want this to be scores yeah okay and then now we want to do a slide we slide oh and this is actually a little bit wrong no well in the beginning it's right but let's do an offset so the offset is that when we shift when we go one to the right um when we go to the right we actually add c and then as we tier we subtract c because we're moving away from it does that make sense yeah okay no i think this makes sense but then now we have to shift some stuff so now after we did the math here then what is the change the deltas as we go to the right then we take score sub c we take this and we put it into left so left dot add this um you start right is this right anyway and then right we would remove um we would pop off am i doing this right i mean i have all the ideas but i think i'm just handling things a little correct really so we have zero minus one minus two and we shift well so then everything to the right is the same except we want to add a number and then bring to the left just subtract one i guess that's right i think i'm okay with this um i may be off by one but i think this is roughly what i want to do though um okay i'll range where my range of this oh yeah because this might not have an element uh like left doesn't have any element yet because our default is that column sub c is to the right okay so how do i type this in a smarter way okay whatever let's just do the dumb way um score is equal to y minus one plus c if length of left is greater than zero and f of minus one minus c is greater than score is good enough this is a little bit yucky but that's okay right no oh no mexico or scores typo oh no pay to win okay let's see nine and 11 is that right nine and 11. am i confident about this if i mean doing a content oh this is doing honest so you don't get any answer anyway but um what else can i test i guess i could test in one case one column and one row um i think that's a reasonable case to test that's one column one row is so let's kind of make sure those are working um 10. okay so this is quickly not working which is great that we test this but okay so one plus two but that should be ten okay so why is one rule not working oh because we don't do we skip this on um one here so that's okay let's add that here that's why we test things that's why we're still sad because we put the prices equal to zero afterwards okay but i guess we don't even need this so that's it real quick that's why we test code uh let's give it a submit fingers crossed hopefully it's not too slow that's my only concern because these are log n type things it's too slow i'm gonna be a little bit sad maybe a lot sad oh okay wrong answer is even sadder um okay why is this wall i have i put 14 but 15 is the optimal answer why is it 15 that's yikes let's see um okay so i have 14 why that's 14. what's the optimal answer is there greedy let's say 4 5 is already 14 right but here if we have 4 5 3 it should be so this has a contribution of two oh no that's only 13. so that's 15. okay so four five three is the answer but i do what do i get so i have okay skipping the first row left 11 14 is here that's a little bit awkward is that a actual path though previous is 12 what is going on here 7 12. something is really weird because i have a seven here if you know did i really mess up i really messed up didn't i because this is the first world how did i even get a seven so okay something is just really weird yikes okay let's print that out as well for the previous one so this is the previous row right so then sums it up to get here because now this is two so three going to five is seven actually that's correct so three going five to two is that right that is twelve plus three minus one two okay so i could see 14 being a possible answer so we're correct here so why are we wrong under 15 though well let's see the 4 to 5 should be 13 so we should have a 13 on the last second to last well which we do right yeah okay so then why is 13 to 11 really bad don't yeah why is that man maybe i have some weirdness maybe i took some weirdness also i'm being really done with the optimization at least on the left side because the left side doesn't have to be a sorted list you just get the max rate so we can optimize that away though running time is not really the issue um and even on the right maybe right side it's fine but okay yikes so 13 here is right because it's four so this is eight that's good and eight plus is 13 which is good um yeah so then once we're here what does that do this is ten plus four point ten plus three am i driving off by one two three no ten plus three so this is thirteen plus now i think my light just got dimmer no i think i handled the left side incorrectly i think this has to be because i'm adding 10 to the left but it should not be 10 right um am i double subtracting this is that why that's the offset i'm handling the left side a little bit weird i know i think that's why but because i add this here but i think i need to add the left as this put something out someone's messing around the lights for some reason but um because when i add left i'm adding to 10 and then the 10 immediately gets a subtract score because it's on the left so i think i'm handling the left side incorrectly right so okay so i subtract one we want the second number to be subtract two i think i'm just handling the left side really incorrectly um it's part of the shift and why is someone like messing around the lights come on okay so anyway we have this number that's all under if this all begins on the right side and as we see to the left we this one should be plus one i'm only thinking one number uh why is this so weird um okay so we have 12. okay it starts at 12 and then it s it should be 11 after one step and then 2 is 10 9 so that's how i got the number so that part is right but then we have on the second number maybe that's where i fail i mean that's definitely where i feel but i'm really bad at arithmetic so we start at six and then as we get closer we add it we're saying this is just then i already pressed a button i guess i did but that didn't do enough likes let's how do i want to debug it maybe that's another way let's see so okay so yeah this has nothing that's this thing and then now it has 12. yes the second number is six but it really shouldn't be six because it's six and then so it started out six on the right side with an offset of what am i doing poop so then after we shift it back over one this is why does this plus c not fix it so this is 13 but then now everything is on the left minus c because of how we do it because 12 should be minus c but 7 should be this minus so one step away should be minus one i'm not factoring that maybe i don't need this no i'm doing this in a really weird way it's something like this i'm really bad at math right now um i guess this is just like a real contest i'm struggling like painfully okay so 12 goes to the left this should be 11. which is fine because now there's an offset of one right and then the next one that's a two so now 11 should have should be 10. so for that number that's right but it should but i cannot minus 2 on every number that's where i'm wrong this is where i'm wrong how can i fix this padding so the longer you stay i think i definitely need okay but this first c is at the time it is um yeah that is the beginning number but i cannot minus everything by that number because this is minus one um i don't know it is this is minus one this is minus two this is minus three this is minus four but i do minus four and everything that's why this is wrong so then i just have to offset i was thinking about this but i wasn't sure that this would be enough maybe minus one 9 11 10 maybe that's it and i just was i was thinking about this but i was really not confident about this uh where's the six referring to sixes or one two three four five six okay let's give it a go i feel like this is roughly right but i don't know to be honest i'm not confident now let's actually double check real quick because these scores should be the best score on the last one so this is 15 is right 14 it should be right 11. so this is um this is zero so this would be taking this and then minus one to different that's right thirteen is one plus this thirteen so this is right i think this is well it's right for that test case let's give it a submit okay what a sloppiness oh yeah hit the like button to subscribe and join me on discord let me know what you think about this problem explanation whatever you need to do uh i'll see you later stay good stay healthy and i'll see you later bye
|
Maximum Number of Points with Cost
|
maximize-the-beauty-of-the-garden
|
You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix.
To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score.
Return _the **maximum** number of points you can achieve_.
`abs(x)` is defined as:
* `x` for `x >= 0`.
* `-x` for `x < 0`.
**Example 1:**
**Input:** points = \[\[1,2,3\],\[1,5,1\],\[3,1,1\]\]
**Output:** 9
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
**Example 2:**
**Input:** points = \[\[1,5\],\[2,3\],\[4,2\]\]
**Output:** 11
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
**Constraints:**
* `m == points.length`
* `n == points[r].length`
* `1 <= m, n <= 105`
* `1 <= m * n <= 105`
* `0 <= points[r][c] <= 105`
|
Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices.
|
Array,Greedy,Prefix Sum
|
Hard
| null |
441 |
Jhaal Hello everyone welcome to new video in this video by going to discuss and the problems from its core key problem this problem and for 2nd problem statement problem share and subscribe this problem what problem where did it go and we know that we With the help of this number, we will be able to subscribe in this method. If we are simple in our first CD, there will be one element, one point song, we will be positive, but how many will there be in it, another 12 points, village and fixed, subscribe last complete, still people. Appointed doesn't matter then we have to do it and we have to do how many people are appointed subscribe accused subscribe to that if end becomes our four then how many sizes are possible 225 subscribe so we have to do something like this here, by doing something more than our If we see how many are felt in the body then if we see it is felt in our first but how many numbers in Sydney similarly for this we have solved this problem keeping in mind * this problem keeping in mind * this problem keeping in mind * Subscribe that we will do it through binary search Winery Sanskrit form Arrogant will be our solution time will do here at our place we have time come in dance this idiot logged in and here our time complexity will be open let's go and see first of all our sulk is the solution all this we are in root force approach What will we do in the roots approach, first of all we will create a variable which will work for us, what size of stairs will be, then till our boil till our phone number of stairs n order of our Greater ISI this will be our number of video first reaction now Like inside this we will see that first of all in our - - - 1 - 12 that if we see through the example okay if we are given fuel 2525 then first of all we will make our 512 - meaning that if there is a conjunction then again this will be our great What will we do here inside this, with this we again have our animated Yes Brother Tell Am I Greater Than Equal To check because in our Equal To case also stairs will be formed Our animated Daily Want to See the Answer's This - This - This - This was the media. Where it is that when our energy will be 25250, first of all ours will be 15212 - - - - - - - - We do, we do, your favorite daily is only 125, so what will happen to us again here But it will be done and what will be our ghagra of our six here and we do - subscribe appointed to three four subscribe on our before that if we subscribe our for this then if we have time for this that our which this It is above what it depends on us, entry, then its time complexity will become stupid, if you are using us space, no, we should subscribe and do Abhishek, so first of all, what we have to do is, first of all, create a variable. This is in tie a positive they will use our initial here's neck we will use our mobile here till now till our and Gretel decide daily turn and - will do from village to village this is our sample here to check For kit solution, we submit it and see whether the result is correct or not and this is our sample, the result has been passed for the test, Jogi, get 5 tons more, my tab is our simple Bhojpur support, let's see it in the last part of optimization approach. We will do, we will do ours, then finally, last time, our time complexity, this is the last time, our time complexity is but if we subscribe my channel, this is the last time, subscribe skill, if we lie, if we make it, then it means that we have how many 6600 If we want to create a website space from this, if we see, here we can write this formula, N2 i.e. end formula, N2 i.e. end formula, N2 i.e. end square plus two school, subscribe. If we want to create this, then our Android two plus two should be great. Here. But this should be our less or should it be less than this should be our less or should it be equal that one to one what is our one our number of points which is given to us now what will we do here we simply channel Subscribe let's see if subscribe here we will subscribe here click on your star plus two that this number two this eight what will we do we will calculate what is our this which at has come at speaker by two plus two this Our channel is 250, so we calculate it to be 6 to subscribe. In this condition, we know that whatever is ours, let us solve it. It has come on our village - 151 - 110, where has it come on the front, come on our village - 151 - 110, where has it come on the front, come on our village - 151 - 110, where has it come on the front, it has come on our seven. Gaya is this vada, what will happen to us 782 and subscribe to plus two, what is ours, what will we do, it is equal to one, we will do it for the village, now let us do school, our ghagra, subscribe our channel, our education through sex is also gone, now we will calculate again. This square plus if you set it then subscribe this is its result 21 - - - - - - - - - - - - Hamara jo hai woh kahan par ka or again star plus two that a again calculate what should we calculate village care by two get passed 225 Back to that is drinking water and five by two is on, we have come out with our ghaghra, those who are turning off our number are making their star plus one, where is the star plus star and what will happen to us and this to us and the village. Which is our channel subscribe that if we see the code for this, what will we do, here we will point to one simple one, first of all, where will we point to one institute is equal to start, where will we point to one? We will joint what is ours on this here, this is where we will start from zero because our number can be 90 and put it on whatever number you want, so now what we will do is run the file while we start addition equal to two inside this we What will we do if this one of ours is plus two subscribe to The Amazing If this one of ours becomes equal to us whose number will we return to the village Okay if this one of ours * * * * if this one of ours * * * * if this one of ours * * * * is one by two if this one becomes our greater From whom, if it becomes ours, then what will we do in this case, whoever is ours, where will we give it to him - where will we give it to him - where will we give it to him - apart from this, if it is ours, then what will we do with it, I have given the flame of gas here, we have given ourselves here. But as soon as we finish it, we will cover it and it will not be subscribed, so if we want to subscribe to the channel appointed for this, the purpose of this has come, what will we do first on our liter, first of all we will start making this, where is his village ? Whatever our N is, what will happen after that, ? Whatever our N is, what will happen after that, ? Whatever our N is, what will happen after that, this is our wild, how long will it last, until our start pimple to-do until our start pimple to-do until our start pimple to-do list inside, what we will do is gas off that end - start that end - start that end - start is divided into a. Now inside this, let us do our scenes case a. First of all, of gas or of women's function, this is also ours, which one I have taken, which made into it, we will have to find 10 one click, here we will have to make a call that this is ours, if in any condition, we will do it by cutting it. Will give okay 100 if there is a second case and made into a plus one strong our what does it become inches plus one two if this is our ghagra becomes small which if they will make this small open this and subscribe to our channel A is a recent version and what will be there in it which is our and it is absolutely light or - or - or - 1 - 1 - 1 - If even after this it is not found then we are not found in the village, after this our position is subscribed to that our sample solution is submitted for discussion. Let's submit it and pack the result that it is getting deserted that the result of sexy is coming and this is our temple step but it is giving wrong answer for this late, here we have made a mistake, so the issue has come here if we see. This is the value given to us, what is happening to us here, we took a double, so subscribe to this channel of ours, all the appointed people do long to others and what will we do by attacking whatever is here? Let's give and when we turn our balance, subscribe to the village, now we should become one subscribe, this is our subscribe, if we are here online but the solution to this, then if we give our last final which is our solution to that, then let's go. Now looking at that, if we see what will be our final solution, what formula have we seen, whatever can be subscribed to OnePlus from our point, we need time, number and this means divide subscribe, now we subscribe here plus if we want to make it * * plus if we want to make it * * plus if we want to make it * * We do, we do here plus one by two is cut but this one by four -1.2 updates to this - 134 Our by four -1.2 updates to this - 134 Our by four -1.2 updates to this - 134 Our liquid gold should be now this one's point is this our what's this our this channel subscribe if We both subscribe, this is our cancel card, if I create a little space here, these people have converted X plus 0.25 to This converted X plus 0.25 to This should be the square root of 0.5 plus that wax and plus 0.25. This is our channel and mixed. If should be the square root of 0.5 plus that wax and plus 0.25. This is our channel and mixed. If should be the square root of 0.5 plus that wax and plus 0.25. This is our channel and mixed. If I write it well and remove it above, it was fallen like this which is ours, for whom it is fixed, meaning we will definitely get it, appointed here, always. Subscribe to our channel for this is our final if we any person era if we calculate appoint subscribe to our channel if we appoint okay one is our fabric so for episode 215 if we see then any difficulty -0.5 difficulty -0.5 difficulty -0.5 subscribe square Route of 100 33.25 Subscribe Isko Dekhne To Yeh Hamara Ka Yoga Ne Subscribe Our Channel Folk Geet Ek Next Par Dobar Jayenge Is Pratima Jayenge Aa Pa Jayenge Last Wali Kitne Gaon 15 Do n't forget to subscribe our channel for subscribe And we used to fold it ₹ 5 on top of our liter, first of all what we ₹ 5 on top of our liter, first of all what we ₹ 5 on top of our liter, first of all what we will do is here we will see the directly written statement return what we have to do is we have written the scheme of velveting this because here we will take our long and it Let us typecast the village, what will we do, we will add to it, use the party function, subscribe, convert us into long life, then long and what will we do in that, we will add to it and cut it, okay, so this was our formula, let's submit from the bottom. Let's take a sample test and see the result that something has come up here, if we do n't typecast the long in front of the properly, what will we do? We will put the long in its parents and end will be written inside it, then what will happen to us, this is our Or the remains of the pots of these. Now if we submit this should be our successfully typecast on XP. This is our success at that time. Subscribe and for the result and if you did not subscribe then this Vivo of subscribe on this side if If we look at its space complexity, it is like Bigg Boss's butt. If we look carefully, our judge is very less subscribed, so we have to pay attention to the time complexity. Based on the timing of which judge, this process will go to you. Apart from this, if you have anyone else. You can comment in the comment box below. If you want to reply and subscribe, you can join our channel
|
Arranging Coins
|
arranging-coins
|
You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** Because the 3rd row is incomplete, we return 2.
**Example 2:**
**Input:** n = 8
**Output:** 3
**Explanation:** Because the 4th row is incomplete, we return 3.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Binary Search
|
Easy
| null |
1,859 |
foreign problem and the problem's name is sorting the sentence in this question we are given a string array called sentence which contains a list of words separated by a single space and each word consists of lowercase and uppercase English letters and at the end of the word there is a digit appended which is part of the string itself denoting the position it has to be appearing in the output now let's take a look at this example and see how this question can be solved I've taken the same example given to us this is the input string s and this string contains alphanumeric characters the numeric is present at the end of each word representing its position inside a sentence so this is 2 so this should be the second word inside the sentence this is 4 so this should be the fourth word this is one so this will be the first word and this is 3 which will be the third word and after rearranging the sentence this will appear first this will appear second this will appear third and this will appear fourth so let us store this numeric value and its Associated word inside a hash map so let's declare the hashma so we start off by converting this input string into a words array by using the split method on the input string so wherever there is a space we separate the words so the words are even look like this now we iterate through the words array from left to right we start off with the first element and we reach the end of the array so in each iteration we have to access the last character in each word and add it into the key last character insert first word is to the last character is 4 last character is one last character is three so we use a linked hash map to maintain the order of insertion and now we extract its respective word using a substring and in each iteration we also extract its respective substring so second word is fourth word is sentence first word is this and third word is a so now we have the hash map ready so instead of building a string let us build a result array and then we'll convert that array into a string and return it and now we are going to iterate through the entries inside the map using the entry set method and the entry object and we access one entry at a time and now in each entry we are going to check the keys inside the map and add its value at that position inside the result tile so the result R is going to be at the same length as the words array so there are four words which have to be added and the index position starts from 0 until 3 so this is the second word right the second word will be added at the first index so get its respective value respective values is so add it into the result array so is this RZ here now go for the next entry the key is 4 so its respective value will be added at third index so 4 minus 1 is 3 so do key minus 1 the sentence is added at the third index now go for the next entry is one add its respect to value at the zeroth index this is added go for the next entry is 3 minus 1 is 2 so add its respective value into the array so now we have our final answer inside result but we have to convert into a string so I'm going to use a string Builder to form our string so that string Builder will be converted into a string using the two string method so this is our string Builder now we iterate through the result array from left to right we add a space after each entry so we added a space for the next iteration if generation is rsps now go for the next iteration is a add a space so until the last word you add a space and once you reach the last word you only add that word into the string Builder using the print Builder and don't add a space in there and we reach the end of the result array now we have our answer inside a string Builder so convert the string Builder into a string using the two string method so this will be our final output now let's take a look at the Java program to implement these steps coming to the function this is the function name and this is the input string as given to us and we have to return a string as output after shuffling them according to the digits present at end of each word let's start off by creating a words array by splitting the string wherever there is a space and then using a linked hash map I am going to store the position that is the digit at end of each word as the key and its respective word as its value for that I am going to iterate through the words array from left to right and I'm accessing each word at a time and calculating its length now I know the length of each word at a time now I want to extract the digit present at the end of the word for example if this is the word I know the length now I want to extract this part of the world so I am going to store it inside a integer variable num and I'm extracting the last character from that word so the large character will be present at the length minus 1 in that position and then using string dot value of I'm converting this is a character right but this is part of a string so I'm going to convert it into a string so this is going to give me the digit as a string so I have 2 now but this is a string so I'm converting it to an integer using the integer.parcent method so num has the integer.parcent method so num has the integer.parcent method so num has the value 2 inside it now so I'm placing 2 as the key and I'm extracting that word I am using the substring method to extract the word so which will start from 0 until length minus 1 so length is 3 plus minus 1 is 2 so 0 to 2 is 0 2 so this will be extracted and placed inside the value now I have two as its key and its value will be is so that will happen for all the words present inside the words array and we have our final hash map present inside this map first I'm going to build a result using the result array and then from this array I'm going to build the string now I'm using the entry interface and I'm creating object entry to access each entry inside the map so for example this is 2 right so I'm getting 2 and placing its respective word two's respective word is this I am placing it at its respective position index is 2 minus 1 is 1 so 0 1 so inside the result array the second word will be is so the same thing will happen for all the entries inside the map and we have our answer inside result but we have to return a string so I am building the string from this result array so instead of directly appending a result to a string I'm appending it into a string Builder using the append method because the time complexity is better instead of concatenating words into the string now I'm iterating through the result array which has the final answer and one by one I'm appending it inside the string Builder and each time I'm also appending a space because so if we don't place this if statement after sentence also there will be a space this space will be added the space will be added and except after the last word space will not be added and now outside the for Loop we have our result inside the string Builder but we have to return a string so using the two string method I'm converting the string Builder into a string and now we can return it the test cases are running let's submit the code and our solution has been accepted so the time complexity of this question is O of n where n is the number of words present inside the string s and the space complexity is also of n because we are using a space of n words to build our map and solve the question that's it guys that's the end of the video thank you for watching and I'll see you in the next one thank you
|
Sorting the Sentence
|
change-minimum-characters-to-satisfy-one-of-three-conditions
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence.
* For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`.
Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_.
**Example 1:**
**Input:** s = "is2 sentence4 This1 a3 "
**Output:** "This is a sentence "
**Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers.
**Example 2:**
**Input:** s = "Myself2 Me1 I4 and3 "
**Output:** "Me Myself and I "
**Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers.
**Constraints:**
* `2 <= s.length <= 200`
* `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`.
* The number of words in `s` is between `1` and `9`.
* The words in `s` are separated by a single space.
* `s` contains no leading or trailing spaces.
1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
|
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
|
Hash Table,String,Counting,Prefix Sum
|
Medium
| null |
220 |
Hello Everybody Welcome To My Channel Let's All The Problem Contents Duplicate 300 Pages For Your Problem Of Content 1112 Problem Of The Tourist Places Near A Difference Between Us And Subscribe Difference Between Enjoy Decide Most K Example 1231 Spent Show The Difference Between The Like 1230 possible to 10000 possible so we can return fruit so how will solve this problem so let's understand in this problem like him being contemplated from one Thursday example 123 live brave we subscribe solve this problem with check given is the best player sim number like share and SUBSCRIBE PROBLEM SOLVING DIFFERENT PROBLEMS SOLVE THIS PROBLEM I HAVE ONE TO THREE IN ONE AND SAY THE WORST CONDITION HAS BEEN THAT YOU STUD DISTRICT IN G L & T AND DISTRICT IN G L & T AND DISTRICT IN G L & T AND DIFFERENCE AT MOST RELAXING DIFFERENCE SECOND IS THAT MOST CASES AND CO THAT ONE IS CONDITION This and condition is not clearly that I - Name of J's that I - Name of J's that I - Name of J's name is clear J letter difference is loose no request to husband so let's open this inquisitive open this in equity research will be so let me short and comes with the no only so n f i Is - And Chief no only so n f i Is - And Chief no only so n f i Is - And Chief Now Engine Oil Nickel 221 Equity Edison More - Turn Off A J Is - Turn Off A J Is - Turn Off A J Is Crater Daily Owl - Tv Show Crater Daily Owl - Tv Show Crater Daily Owl - Tv Show Episode This In Quality The Are Being A I This Garlic And Request U Turn Off Do A Plus Twenty Seconds From The Situation Will Get Enough Idea Which Will Be Greater Than Or Equal To One Off 8 - Team Sudhir Water Not Solve WhatsApp 8 - Team Sudhir Water Not Solve WhatsApp 8 - Team Sudhir Water Not Solve WhatsApp For Solving They Can Just Simply Need To Look For Listening From 108 Kotlu Will Start From Plus One 100 Subscribe Positive Side Will Be Led The Language of Your Choice Members Code Implementation of This Approach Should You Use That Code Running Run Time Complexity Will Go Live Your Use * Added Use That Code Running Run Time Complexity Will Go Live Your Use * Added Use That Code Running Run Time Complexity Will Go Live Your Use * Added All That President Vikram Ko of Square Candy Father of Deposit So No Life Without You Just Look Every Time's Elements of Obscuritism can be 100 using its approach will use this abe launde structure at least 100 to key entry acid what will happen in this will be to a positive manner and function of number on this number united and will get just floor of the number and Mrs. Low Floor Possible Dangers Will Return Similarly For Ceiling In Ceiling Will Get Departures Badr Number And Null Ignore Badr Number So Let's Also Calling Acidity Threeplex 123 For Flats In That Case Baby Corn Flour For Vivid Cornflour For 60 Will Get Dinner Similarly Civil Work Show will use this approach know how will solve this saw her in this example is 1234 to and her with kids in quality CB minimum cleaning fennel will read for loan from oil to 0 meanwhile a tiffin or every time floor key from 10 to set and Sealing the form of positive case is lead subscribe the amazing will not to check quality of mid and subscribe this channel questions and other important thing in this problem solve the riddles which problems are very bad for not knowing friends not give what is the back To Take Care Over All Subscribe Can We You For Telling Interviews Long Dresses For Its New Research-Ped Has Research-Ped Has Research-Ped Has Na Will Treat The Elements For In Subject Love Is Not A Plus Nor Will Be Ass Long Flash Light Call Floor From This Set Daughters In The Form of a plus TV and a long ago ceiling selected call seal set daughter in ceiling navamsa of I - 31st December will in ceiling navamsa of I - 31st December will in ceiling navamsa of I - 31st December will check the floor and floor that is greater than and equal to numbers of I the hour and a seal this notice Sonal ki and seal is garlic and a volume whitening desist from dedication apps explain you find any of this condition thursday in sohe urban mode important meeting wear look in which both immediately you morning 2000 into rate languages the sense of long into rate languages the sense of long into rate languages the sense of long hair similarly when you Here You All The Best To Convert It Into Good One And You Will Be Id Am Id Multiply Number Long Been Already Subscribe Remove The Element Presented With Differences Between Desi Nuskhe 200 Against Marital Accused The From Schedule Wheel Remove Id Number Of Versus In More Star of I-K services Want and Division for anything when it is I-K services Want and Division for anything when it is I-K services Want and Division for anything when it is not possible in Indian villages and forests Flat Compiled It Difficult Field Umpire Testing Sometime Spending Surya Compiler Truly It Was Written Statements To Please Subscribe A Ye Soch Sexual And Were Getting Correct Answer So Let's Embed Code is 123 No Pending Hai Nishan Running and Tej Dhoop and Obscene Dance of This is Page Number More than 90 This Will Give Wealth Will Convert in to the Live Video Only No Celebs Caught on CCTV That a Main Office Will Pass This time aur yes teri jo compile hair hindi line ok so this will multiply with this set dot follow 100ml unique festivals the new york sea 123 nose singh pending singh to some extent and this time they are getting character so let's submit 2014 time complexity of dissolution of Senior like it more than a hundred subscribe the channel and subscribe the channel thanks for watching a
|
Contains Duplicate III
|
contains-duplicate-iii
|
You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`.
Find a pair of indices `(i, j)` such that:
* `i != j`,
* `abs(i - j) <= indexDiff`.
* `abs(nums[i] - nums[j]) <= valueDiff`, and
Return `true` _if such pair exists or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0
**Output:** true
**Explanation:** We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums\[i\] - nums\[j\]) <= valueDiff --> abs(1 - 1) <= 0
**Example 2:**
**Input:** nums = \[1,5,9,1,5,9\], indexDiff = 2, valueDiff = 3
**Output:** false
**Explanation:** After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.
**Constraints:**
* `2 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `1 <= indexDiff <= nums.length`
* `0 <= valueDiff <= 109`
|
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
|
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
|
Medium
|
217,219
|
152 |
welcome back today the problem we'll be looking at is maximum product sub array given in integer array nums find a contiguous non-empty subarray find a contiguous non-empty subarray find a contiguous non-empty subarray within the array has the largest product and return that the test cases will fit into a 32-bit the test cases will fit into a 32-bit the test cases will fit into a 32-bit integer and the sub-array is a contiguous and the sub-array is a contiguous and the sub-array is a contiguous sub-sequence of the array let's look at example one we have the input two three negative two and four in an array and the output is six this is because two times 3 gives us the largest product as you can see if you multiply 6 by negative 2 it gives us negative 12 and there are no negative numbers on the right to offset that these two numbers are negatives so we simply return zero as if multiply if multiplied by any of those numbers will simply return a zero or if we take these two numbers it'll be a negative number which is less than zero hence we return zero so let's go to the whiteboard and have a detailed discussion about this we have that input 2 3 negative 2 4 as an array and we know that the output should be 6. one obvious brute force solution is to simply find all the sub arrays and find their product once we have all the products we simply return a maximum of them but that would require finding all the sub arrays which will mean of n squared time complexity we don't want that what can we do instead well let's have a third experiment let's say if all these numbers before four are anonymous and we don't know what they are so we will have an array that looks like this there could be many numbers before or it doesn't matter let's say that it already looks like this but i do give you the maximum value so far let's say the maximum value so far is seven and i also gave you the minimum value so far well let's say that's two if i gave you all this information and you arrive at the current element 4 what would be the answer that's obvious right you simply multiply 7 by 4 that gives us 28 however what if instead of 4 we have negative 4. what do we do now well if it is negative 4 we don't want to multiply any of them we don't want to multiply negative 4 by 7 or 2 because these two are positive values so what we do instead is we're simply getting x 7 and again what if instead of a positive minimum value so far we have a negative number and notice how it is the minimum value that is negative because this number cannot be larger than this number it is negative and this is negative we would want to return 8 right we want to return negative 4 times negative 2. instead of seven so as you can see there are a few things that we want to take care of here the first one being the numbers are increasing steadily so if the numbers are increasing steadily we simply multiply the current number by maxwell if there are positives we get 28. however if we have a negative number here we want to see if there are any negatives in here but as you can see instead of checking if each number is negative or not we can simply calculate all three possible solutions and then find a maximum but we do have positive numbers here negative numbers that we have to take care of also we have cases like zero what if this is a zero here if it's a zero we don't want to multiply by anything right return the maximum value g7 we want to keep track of our minimum value is negative two and not negative two times zero which gives us zero that is greater than negative two so what can we do well let's see right as we iterate from the left to the right we have our values so maxwell and minval they will be initialized to some alley which is one because in a multiplicative process we want to have our current we would like to have our variables initialized to one because otherwise if we initialize it to zero multiplication is not going to do anything once we have those values and we want to have a result or output that we want to return we can set this to none organize it to the first element of numps then we iterate over the array for num numps for each of these elements we want to multiply by okay so we want to keep track of all these elements and the convenient way of doing this is to initialize some variable we can call the values because they're it's going to hold multiple values and what this contains is num itself and what do we do here we multiply max well by the current number and then multiply main value by the current number or we just take num itself right so files will hold all three possibilities so this would be num or max value times num and min value times now once we have that we need to update our max and min values so maxwell equals to the maximum of the old value and the maximum matter sorry this would be the maximum of this right because minimum value times num might be a larger number than maximum value times num so once we have all three possibilities we simply want to take the maximum of them and update it similarly the same thing for min val except this time you're taking a min instead and once we have all this we want to keep track of the results the result will be the maximum of our old results and the maximum value here finally we simply return result after the iteration so let me reiterate what this is doing real quick essentially we're trying to keep track of all the possible values at each iteration i try and find maximum value times num that would give us the maximum value if the maximum value so far is positive and the number is positive if minimum value is negative and num is negative then that would get updated as the value of our maxwell here we also want to keep track of num because in cases like zero and four right we would have num before max all and minival would be it would be zero because we multiplied in the first iteration since we want to save num equals to 4 because that would give us a max value of 4 over here let's go to the code walkthrough and see how we can implement this first of all we need to define we need to initialize current min and max so currently we'll see current max equals to one and now we have our result equals to num zero once we have that we simply do poorly and iterate overnights and you want to take care of all the possibilities so we can do that turn them equals to the minimum of about and max equals to the maximum plus then the result that equals to the maximum of all results and current max then in the end here we simply return results try and run this code okay got accepted now okay possible test cases so it returns a success that's it for this video and if you liked it make sure to like comment and subscribe i'll see you next time you
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
1,750 |
hello and welcome to another video in this video we're going to be working on minimum length of a string after deleting similar ends and in the problem you have a string consisting of a b and c you're asked to apply the following operations any number of times pick a non-empty prefix from s where all the non-empty prefix from s where all the non-empty prefix from s where all the characters are equal um pick a non-empty suffix and S equal um pick a non-empty suffix and S equal um pick a non-empty suffix and S where all the characters are equal the prefix and suffix should not intersect at any index and the characters from the prefix and fix must be the same delete both the prefix and the suffix return the minimum length of s after performing the above operation any number of times Poss is zero so in this first one um you can't do anything in the second one you can get rid of the C then you can get rid of the A on both sides then you can get rid of the B on both sides and you can get rid of these A's and then you'll get nothing um in the next example we can get rid of all the A's over here and all A's over here then all the B's and then we have CCA which is three characters so it's a pretty straightforward problem because you're basically deleting um all the characters that are equal and the um the prefix and the suffix have to be like the same characters so in order for all the characters to be equal and they have to be the same character basically your prefix and your suffix has to be like all of one character so let's take a look at this example so basically it's pretty easy like you just have some pointers like this so you have a pointer over here and as long as your characters are equal so like as long as this is equal to this you can just keep deleting as long as you have that character even if you like run over like let's say this whole thing is B's you can just keep deleting and then once this left pointer gets past the right pointer then you can stop so what's going to happen here is you're going to delete like all of these be's you're going to delete all these be's and then update your pointers so this pointer will now point to the a this pointer will point to the a now the A's are the same so we can do this operation again so we can get rid of the A's and update our pointers and then we can get rid of the be's because they're still the same character so we get rid of all of them in just like just in a loop update our pointers then we can get rid of the C's data pointers and then we have a couple more so we get rid of the bees updated pointers and then we can get rid of the C's and update our pointers and now both pointers will point to one character so this is like the edge case in this problem so whenever you have something like um ACA you can get rid of these but then you can't get rid of this last thing because the prefix and the suffix can't share characters and that would be that is the case as long as the thing you're deleting is more than one character so if you have this like one character left in the middle you can't do anything but if you have something like a AA then you can delete the whole thing because then your prefix can be like this and your suffix can be uh these two so as long as basically you don't have like the one character you can get rid of all of it so you just like you just keep checking um you just have two pointers and you just keep checking if all your characters is the same you don't have to like delete anything until you actually get to the end so once you get to the end of where your pointers are you just like return the length between two pointers so you don't actually have to like keep a string and delete or anything that's why it works pretty well um and you do need a linear time solution so you can't like be like remaking a string anyway um so yeah so you basically just keep checking for your characters are they the same if they are you keep deleting and you also make sure that they don't both point to the exact same character and but and by deleting you I just mean keep moving the pointer up so you just say like okay these are the same so while my left pointer is less than my right pointer and this character is B I can just keep moving it up so I'll move it all the way up to here then the same thing here well my right pointer is greater than my left move it all the way down and so on you keep doing this and as soon as the characters aren't equal you're basically done so like let's say this wasn't a let's say this was like G or something you can't do anything afterwards so that it's basically like a greedy solution just delete all of the characters you can and as soon as you hit a mismatch you're done and then you just return whatever the subring is the length of that so let's take a look at the code it's pretty easy so you just have this left and right pointer that right zero and then on the string then you just keep doing this while the left is less than the right the reason I do while left is less than right is because I'll basically have two cases so if at the very end they both point to some like prefix that's more than one character then what's going to happen here is this left will actually end up over here because I say if left is less than or equal to right and the left character is the same keep moving it up so your left will be greater than your right at the very end as long as like the last thing is more than one character if the last thing is one character then um my Loop will break so then left will equal right so depending on the end if my left is less than if my left is greater than right or it's equal to right um if it's equal to right that means I had that one character that I couldn't get rid of so I'm going to return one and if left is greater than right that means the last chunk had more than one character and we can just delete everything so like I said if left is less than or equal to right and the characters the same just keep moving it up same thing for the right um and then otherwise if left is still less than right but the characters are different you're done like you can't do anything else so you just return like the string which is just like a sliding window right same kind of length right minus left plus one um and then this is just like I said just to check if you have that one character left over or not and we can submit it's a pretty easy one um so we can talk about time and space and things so for time it's soent because we just have like a two-pointer and space it's so one like a two-pointer and space it's so one like a two-pointer and space it's so one so like I said you can't do something like rebuild the string and get rid of a character because strings are immutable so that would fail cuz your string is 10 fth characters so like that would be like an N squ solution as well and it would take up space so ideally for almost all problems with strings you want to just use pointers and then get a solution like only make a substring when you need it and the only time we need a substring is when we're actually done actually we don't need substring at all here we just need a number of characters so we don't need it at all but let's say you were asked to return the substring of like what is left over what you don't want to do is like have a string and be manually deleting because then that would be N squared and it would also um be like more space to begin with so make sure you use pointers and then only get a substring like at the very end when you actually need it and that's pretty important for string problems but yeah that's going to be all for this one pretty easy one just greedy um get rid of all the characters you can and yeah like I said the only important thing to recognize is when you do have that extra character left over at the end you can't delete one character but as long as you have more than one you can split into a prefix and suffix so it works fine me yeah and if you did like this video please like it and please subscribe to the channel I think we're almost at a th000 subs and I finally got the um like YouTube monetization thing so that's pretty cool yeah I'll see you the next one thanks for watching
|
Minimum Length of String After Deleting Similar Ends
|
check-if-two-expression-trees-are-equivalent
|
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal.
2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal.
3. The prefix and the suffix should not intersect at any index.
4. The characters from the prefix and suffix must be the same.
5. Delete both the prefix and the suffix.
Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_.
**Example 1:**
**Input:** s = "ca "
**Output:** 2
**Explanation:** You can't remove any characters, so the string stays as is.
**Example 2:**
**Input:** s = "cabaabac "
**Output:** 0
**Explanation:** An optimal sequence of operations is:
- Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ".
- Take prefix = "a " and suffix = "a " and remove them, s = "baab ".
- Take prefix = "b " and suffix = "b " and remove them, s = "aa ".
- Take prefix = "a " and suffix = "a " and remove them, s = " ".
**Example 3:**
**Input:** s = "aabccabba "
**Output:** 3
**Explanation:** An optimal sequence of operations is:
- Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ".
- Take prefix = "b " and suffix = "bb " and remove them, s = "cca ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` only consists of characters `'a'`, `'b'`, and `'c'`.
|
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
1736
|
452 |
hello so there's talk about a minimum number of Arrow to purse balloon so this is definitely straightforward description what you have to do is return the minimum number of error that must be shot to burst all so all those of balloon there must be the case so have to be the minimum so the idea is actually pretty straightforward what you have to do is what you want to sort it show the array based on the second index it's going to be this don't build this don't be less gonna be this and then you want to um you want to know if I shoot one error so if I show one Arrow by this which is the uh which balloon is in the range if the balloon is in a Range you need to burst automatically but doesn't uh does not mean that the blue inside the balloon get burst right so uh what I mean is this one to six imagine this is one through six and then next one is what two to eight and the next one is what 7 2 12. and last but not least 10 to 16. some sandals all right so I'm going to burst my first blue so this is what my first blue Bloom is going to be it's going to be burst right so one two six but between one to six there's two three so you'll press this one automatically but when you burst this one this does not get first right that's not why because you need another balloon to get uh you need to another error to get shoot right so you shoot this one and when you shoot this one there's a balloon inside between this range and you will get uh you'll burst this one as well so and the answer is one two right so the idea is straightforward I sold it based on one the second that's right and then when I uh updating my so when I Traverse the array right basically I keep updating my first position on my first position I will check the original uh the starting balloon and then if this is not in the range I'll update to 12 right and everything else everything before 12 I will get birth and then does not increment my error right that's not increment so I'll increment my error right here after the first error right so I know my first position is six right I does not obtain my arrow to get eight right I was still remaining six until what seven happened I mean the another balloon starting at seven but so I know this is all about right so I need to say okay I need another arrow then I will say I obtain my first position to 12 and I know my next balloon is going to be 10 to 16. this one 10 is less than 12 and I'll give it uh get update automatically all right so I'm gonna just uh write the solution this is all of the idea the algorithm right so if a point does not uh that's not equal to what that's not equal to anything so which is going to be zero I'll return 0 right you can say equal to null or equal or you change it equal to zero still returning zero right and then my return value is going to be sodium at one right and it's now starting at zero right so I'll return the results so the result is actually based on the one it's actually equilibrium to the arrow counter and now app uh I will sort it I will sorted my array in here in here in here based on my value E1 A1 B1 from smooth squared to graders and I also need what the first position to keep record first point equal to what I will make sure I burst my first balloon so I will say my first position should put First Position will be 0.01 so everything before point zero one 0.01 so everything before point zero one 0.01 so everything before point zero one uh will get burst automatic it right away so a starting point uh I equal to zero so I'm gonna say follow I equal to one I less than point the lens and I plus so it's my if my current position I zero points I zero is less than or equal to what the first point I don't need to do anything right I'll just say continue why because just imagine hypers 1 6 right the next array coming out is 2 8. q a right Q is this and then this first point is what six right point zero one six two is less than six I don't need another arrow right I'll just skip 2 8 and now let's jump to 712 does seven the seven let's say equal to six no right so I need another arrow right so I increment my arrow and also update my burst point so when I update my burst point it's going to be what ending position right at the ending position so this is the starting position changing zero to one and that will be the solution so let me run it oh um actually this if points array equal to no then this and what happened to here integer the computer do I have typo give me one second integer points oh yeah I do I forgot to initial a comma uh comma B and then Arrow okay this is like Lambda um typo all right submit all right so let's talk about the time in space uh this is gonna be a time sorting for Loop sorting uh sorry for Loop and sorting right so it's going to be unlocking and represent the end of the points this is all of them and represent the points the length right so this is longer so it's going to be unlocking full time space this is space so it's going to be constant so I'm going to just make a breakpoint starting debugging mode so initially the points are recently right after I sold it I'm going to say hold on all right after I started the points like this dude uh you just do the math you know checking the condition pause the video at any second so feel free to leave a comment below if you still have questions so that will be the video and then I will talk to you soon bye
|
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
|
89 |
Hello everyone welcome back to my channel I am going to list myself for medical, show problem in July challenge, gang rape court, what is this problem, what to do, this problem, we have to read the end with great code sequence, if we want to do an admit card then in this Total tourists will go up and anti okay how like if we have a person a tweet at an angle of degree extracting the juice of a soil means remember hero and chicken and total how many tourists on and here that means a okay that is when our If the sequence is taken out near and with great, then the tour in it is a super and DJ song, then the first entries will be Ramesh strange and those who are grade spread in 35mm by a representation are the same as if we are here, we have to make gravy and set a pin. For example, if we were given the entry here, if the end should be from number 11, then who would be the first two sons, then we vented this question of 10 inches. For citizens zero okay so first 20 after that now next is that can and one okay you will always do on a birthday now see this here see this always said every one here what and this and last two that This record needs to be on the ground securely. How many phones have been made so far? All these more have been made, so now let's see how we will approach this. Let's do one thing. Let's do a vision test for the policy. So, let's find a name for Ad World Free. Now I have generated the cigarette. Let's see how to do the NFC, we had this citizen present that if there is admit card difference in these four, right in this and in this one tweet, after getting admitted in this year, it is okay if I say that I will put And then there are different 20019 here, now we do one thing, campaign zero was put in front of these and so on, if you put that then this and your gray should be there, here I have given the entry i.e. there, here I have given the entry i.e. there, here I have given the entry i.e. what will be the total for the entry. To make it simple. That means one, 4 or that is complete, after terrorism, we can write that this and this, 200 and this, so what will we do here, when we had first put our in front of these people, then they had become Now all these will seem like God, then they will start singing the previous one from the back and then on 0, you stay at the maximum, this one is 0104 level, this vansh u take it, at what time do you go, that is, it will do the cricketer in cotton and when it starts, If it makes any difference then first of all we have so for our pass these went to us first of all we started this again and their and this both will reduce so this and this total become os so this is our such cross It will be said that we will set a record in this, if our team has asked for them, then we will first take out whatever for And Minus One and then the British will come in the sequence of And Minus One, first they will put their Gaya Hero, then they will start from the back and ahead of them. I am my friend, our totals will be made and these are called from returns. If there is a list, then this will be our cruiser that will go to the commission first. Look at the code, if it is B, then first of all we must have been given a function. If there is one more thing, what did we do in it? We made a record A. Function created Generate Chiku Sanam Re in let's pass a story What will be the base in the function that if our environment i.e. a sequence of tweets is our environment i.e. a sequence of tweets is our environment i.e. a sequence of tweets is created then I had discussed this when a break sequence of one minute is created then they will become to rescue Care means you will become two and that's your Okay, so when we have our guess, this will become zero and what will we do with that, we will take out - we will what will we do with that, we will take out - we will what will we do with that, we will take out - we will fold the function again for and I we have like when we had to cook, we have this which is our This is what we will apply on this and its treatment as if we are going on time, every tempting inductive, whatever experiment villages are applying and sugar in the answer, this answer sub-centre is starting from behind sub-centre is starting from behind sub-centre is starting from behind in the tempo and now it Time is this time, this is this temple, in this first we started life from behind you, then we started from the bottom here and friends put in the answer, we have returned the answer and what will be in it, the answer we will get here is only Oil, ghee, this will return to us, this will be sangri string, if you give us two interiors in the question, if this is A, then these will be the points for Enrique Vardo, what will be 0, this is ours and this is ours 132 Here the person has and That all of them were fine while living in the interior and if they return to the ashram, then it would be clear that Afroz would have understood that the code of Titan has the same explanation. At least Kodak is in the description for Pakistan and Africa. If you send it, please help. To like is to commit suicide.
|
Gray Code
|
gray-code
|
An **n-bit gray code sequence** is a sequence of `2n` integers where:
* Every integer is in the **inclusive** range `[0, 2n - 1]`,
* The first integer is `0`,
* An integer appears **no more than once** in the sequence,
* The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and
* The binary representation of the **first** and **last** integers differs by **exactly one bit**.
Given an integer `n`, return _any valid **n-bit gray code sequence**_.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,3,2\]
**Explanation:**
The binary representation of \[0,1,3,2\] is \[00,01,11,10\].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
\[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
**Example 2:**
**Input:** n = 1
**Output:** \[0,1\]
**Constraints:**
* `1 <= n <= 16`
| null |
Math,Backtracking,Bit Manipulation
|
Medium
|
717
|
292 |
all right so let's talk about nip game so is a game that you play in the childhood right so basically like you either remove one or three stone and then you can win basically easily so imagine l equal to one so if you take another one stone and you win so angle two is gonna win three and then you still win but how about four right so input of four you are not winning because whether you take one or three stone out of the end you still you're still losing right there is at least one stone left in the uh in the pile right so basically like when it's not uh one more two more three then you lose right and then you use the same idea but just say if one is actually not four it's not equal to zero then basically you lose so this is how you write it so they mean wrong run it yeah so uh the return value is actually determined by your win or lose so and mod 4 is not equal to 0 then you lose so uh this is pretty much my explanation and if you do want to just follow up the solution and this will be a pretty much the idea and i will see you next time the time space is constant so let's not worry about it and i'll see you next time bye
|
Nim Game
|
nim-game
|
You are playing the following Nim Game with your friend:
* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and **you go first**.
* On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
* The one who removes the last stone is the winner.
Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** n = 4
**Output:** false
**Explanation:** These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.
**Example 2:**
**Input:** n = 1
**Output:** true
**Example 3:**
**Input:** n = 2
**Output:** true
**Constraints:**
* `1 <= n <= 231 - 1`
|
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
|
Math,Brainteaser,Game Theory
|
Easy
|
294
|
1,838 |
hello everyone this is official zendo today i'm going to talk lead code 1838 frequency of the most frequent element if you like my videos please subscribe to my channel and you can find the complete performance leads in video description below which includes all the purpose categories and its rebounding videos let's look at the problem discretion first um if you look at the whole um problems text it's kind of hard to explain um so we let's direct jump to the examples so here we give an array and given a k uh we are asking to doing some operations uh which to make some elements equal to another elements um so we are asked to giving a number uh when how many numbers are unique numbers we can generate after all the operations smaller than five so for the first examples we can try to convert all the elements to four so which means one knee two plus three two four and two need to plus two four and the total operation will be five so which is meter requirements we can down the operation uh smaller or within five operations and we obtain the maximum unique numbers which is 4. so the maximum copy is 3 for this time so for the second examples as an answer mentioned there is a three way to do that we can make first one to four and this requires three operation then we have two uh force in array of the operations we also can make the four two eight it's required for operation so then we got a two of eights uh again we can make a to thirteen so here we have two settings those frequencies are equal so we can pick each one um for the three examples there's no way we can make one element to another so here we can try to make three two six but it's requires 3 operation which is greater than k and also we cannot make 6 to 9 because um we need this at most 3 operations to convert six to nine all right let's look at how we can solve these problems optimally so it turns out these problems can be solved by sliding window also there is a little bit uh grady ideas including that uh i'm going to explain later so um so here we have two steps first we saw the whole array in ascending order and second we maintain two variables one is a calculated target sum and other is for the actual sum and we applying a general signing in the templates which i will explain later combined with examples here are giving examples story 4 13 a and 1 and k equal to 5. so after sorting the array becomes one for a13 so as a uniform sending window template we have a left pointer and right pointer so we initialize left point as zero here we can directly uh initialize red point has one things um the mass frequencies will be one in any of ray which is the size it's not empty array since we were we can make sure we have one element at least right um then how we propagate the left pointed right pointers so the rule is we will increase left pointers when talking some minus actual sum greater than k what that means so talking sound means for any of sliding windows of arrays if we want to convert all the elements to the right most elements what's the target sum what's the total sum of um the whole standing windows so basically for example if we take 4 and 13 so we convert 4 to 13 and the total sum of this sliding window will be 13 multiply 2 right so we have two 13s um and actual sum means we're just directly adding all the elements in the specific assigning windows together so then they're minors means how many operations we need to use to make the target happens uh then if this operation is greater than k which means we need to shrink the sliding windows right so why i'm saying we use some greedy ideas in this um method because we only looking at the uh the closest one um to generate operation this is why we need to do sorting right so because um for example if we need to make all the elements to eight we don't want to start with one we always want to start with four which is closest one right so you probably can feel these points later when i uh go through the slightly window spo so yeah let's dive in example so we initial left point is zero right point of one and uh we're looking for the one and four for these sliding windows so as explained target sum is four multiply two is a actual sum is there actual sum is five so a minus five is smaller than k so we won't increment left pointers we will record the maximum frequency for now and then next we increment the right pointers so next we extend this lining window to eight um then target sum is 24 actual sum is 13 and 24 minus 13 greater than k so we this is not a valid uh sliding window we are looking for so we will increase left pointer to shooting the sliding window so right now it comes as foreign a uh it's toxin 16 actual sum is 20 12 16 -12 16 actual sum is 20 12 16 -12 16 actual sum is 20 12 16 -12 equal to 4 minus f5 so we will recall this frequency is still 2 um then next we move right pointer to extend a slightly window um then target sum is 39 x sum is 25 uh 39 minus 25 greater than k so we will showing left pointers so that point is two and right point three so right now uh we reached the end of slightly window a and 13. then target sign is 22 26 and 21 we obtain another valid slang window which is two so here we don't need to do it anymore right because we want to find the maximum um subsequence so we don't need to shoot shrink the styling window again so eventually we find our answer which is the master frequency all right let's look like how we implement in the code we first on the whole array we initialize markz frequency is one so maybe we can add in a one more initial condition say if the array is empty we return zero right i think this is the one the corner case um and the left pointers we initially say is zero as we explained uh we spend we initialize actual sum um so use the first elements of the array so be careful here things we need to um inversely worst case we need to sum all of the elements in an array so we use a long to make sure it's run out of boundary so we have a four looping iteration for right pointers then here we calculate the target sound which is long as well then here we propagate the actual sum so next we come our left pointer increment rules so when talking sum minus actual sum we increment left pointers uh once we move left pointers we need to do the uh reduce targets on extra sum at same times to maintain these two sounds correctly eventually we will find a valid sliding window after we shrink left pointers right so then here we can update our master frequency once we write pointers reach to the end of array we will return the mass frequency star let's look at other computation complexity and the space complexity is simple because we don't use the actual data structure right so you speak of one so what's the computation complexity here so first step we are doing a sorting which is a unlocking on the next type of sliding windows how we look at the sliding windows complexity uh one way we can look at this is looking back the right point and left pointers right so right pointers um is always from one to the n so it's big of n so here we have no gain plus um bigger of n this is left pointers and also another operation is increment sorry this is right pointers and another operation is we move left pointer right but we can observe that the left pointers also only move from zero to n and worst case right so we are only looking for uh that combinations here and the left pointers will never meet right pointers so here we adding another operation for left pointers so eventually we will only take the maximum of the order plus here in the big o of notation so the computation complexity for this method will be big of n log n eventually so here is the small very small and big over in lobbying in terms of the combination capacity okay that's all for today um i think you like this video please leave the comments and a suggestion um so i can make better videos in the future i'll see you next time
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
442 |
hello today i will do a lead code problem find all duplicates in an array this problem can be a little tricky but i will go through all the steps you could take to arrive at the solution the problem statement is as follows given an array of integers with values greater or equal to 1 and less than or equal to n with n being the size of the array some elements appear twice and others appear once find all the elements that appear twice in the array could you do it without extra space and in o n run time we are given an example where of an array and we're just looking for duplicates so 3 appears twice two appears twice and no other element appears twice so everything else it just appears once so the output would be two and three now i will look at this example more closely i will remove two elements from it for simplicity now if we were to ignore the extra space constraint then we could use a hash map to find all duplicates in the array since the elements in the array are constrained between 1 and n we would be able to use an array as our hash map to store the count of each element i will first populate the hashmap array with zeros to represent that i haven't seen any of elements yet and i will also create my results array so as i go through my input array i see four so i'll command the fourth position by one i see three so i'll commend the third position by one i see two so i'll increment the second position by one and when i see two again instead of incrementing the second position i will simply put two into my results array and then when i go on and i see three and i have seen three before so i'm just going to put three into my results array as well and the last element is one and i'll increment the first element of the hashmap okay and then i can return the result i want to make a small comment here for example suppose each element could appear more than twice say three times if i were to use this strategy i would end up with two appearing twice in the array however this is not something i have to worry about here because the problem states that each element can at most appear twice so i will never run into this issue with duplicates and this is the reason why i'm able to take this approach notice how the hash array is conveniently the same size as the input array and the hash array only needs to store two values zero and one so sort of the boolean values a common trick i've seen in these algorithm problems is to store the boolean values as a sign on the input array so if we wanted to mark something as one we would set that element to the negative value of it so instead of four we'll have minus four and instead of three we'll set it to minus three and notice how conveniently the elements of the input array are all positive so we are free to use this trick let me walk you through how the problem would change if we were to use this trick now we will actually be changing the input array so i will give it a name we would still have our result array and then i will have i representing that we are looping through the for loop so now i will give the steps you would go through in the for loop okay so when indexes i uh we're looking at four so we can say that the value is equal to four now we want to record that we have seen value four well the index of the array that we would need to change would be 4 minus 1 is equal to 3. so we would change the element at index 3 to be negative so it can be said that we're gonna state that numes index multiplied by negative so this will turn it negative and in this case it would be three and i have reflected the changes in our news array so then we will go on to the next element one it will have value three and index that we want to look up whether we have seen this element before would be 3 minus 1 is equal to 2. so we want to see have we seen this element before and we would say gnomes 2 is less than zero and the answer is no well we will make the element at index two be negative okay so then we go on to i equal to two here the value now is minus two so the value stored in the array but the actual value is the absolute value of um of minus 2 which is going to be 2 and the index will be 2 minus 1 which is 1 and then we see is the have we seen this value before so is the element at index one less than zero and the answer is no so we're gonna change that element to be negative then when we go to i equal to three we are again gonna see minus two so taking the absolute value we get that we it's value two seeing what index it corresponds to it's gonna be two minus one equal to one have we seen this element before and the answer is yes we have seen it before instead of turning the value negative we would just want to record it in our results already so we would put 2 in here as we increment i to 4 the next value is 3 so absolute value of three is still three index is going to be three minus one is equal to two have we seen three before and the answer is yes we have seen it so we would put it into our result array and then the last element is going to be 1 and it's going to correspond to index 0. have we seen element 1 before and the answer is no so we can mark that we have seen that element before in our array okay and at the end we just return our result and this is the algorithm now i will write it out we'll have our var result is equal to an empty array and then i'm gonna loop through the input that i is equal to zero where i is equal to zero i less than numbers.length zero i less than numbers.length zero i less than numbers.length i plus so i'm gonna define var value is equal to math.apps names math.apps names math.apps names i are var index is going to be value minus one and then i'll have my if statements if um numes at index is less than zero then i'm gonna put the value into my results array and if not then i'm gonna record that i have seen that value before by saying that numes index multiplied by -1 and at the end i'm multiplied by -1 and at the end i'm multiplied by -1 and at the end i'm gonna return my result array okay now i will run this code and then submit it and it has been accepted and it's faster than 89 of javascript cases um it runs in linear times since we are only looping through all elements once and all of the operations inside our for loop run in constant time i know we are creating the results array but i've seen it before in other lead code problems where they say don't use any extra space but you still have to create the result array and they don't count the result array into using that extra space anyway well thanks for watching and i'll be doing more of these in the future
|
Find All Duplicates in an Array
|
find-all-duplicates-in-an-array
|
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**.
| null |
Array,Hash Table
|
Medium
|
448
|
993 |
hello everyone welcome to quartus camp we are at 18th day of october elite code challenge and the problem we are going to cover in this video is cousins or in a binary tree so before getting into today's problem i did not post the previous day's problem because we have them covered in our channel already so if you're looking for problems and i did not post it recently which means i might have posted it already i did not want to post them again so please do check them so let's get into today's problem which is cousins in binary tree which is again an easy category problem where the input given here is a root of a binary tree and two integer values and we have to written true or false if they are cousins in the binary tree and in the problem statement there is also a definition given for cousins in a binary tree that is two notes of binary to your cousins if they have the same depth with different parents so let's understand this with an example so here is a given example in the problem statement clearly says the root node of the tree starts with the depth zero and then goes the next level to step one and then to next level as step two and so on so now the definition of cousins are just said that two not said to be cousins if they both are in same depth and different parents so the first input given here is x is equal to 4 and y is equal to 3 so let's check where they lie in the binary tree so if you check 4 is in the depth 2 and 3 is in the depth one which is actually a different depth so they cannot be cousins so let's check the next condition as well they both should share a different parent of course the parent of three is one and four is two so they both share different patterns but they are not in the same depth so which means they are not cousins so what could be the possible notes that are cousins in the binary tree so let's check the nodes which are in the same depth so we don't have another node in depth 2 so we cannot find a cousin first node 4. so let's go to one level up in depth one we have two nodes two and three so they can be cousins but it has to satisfy the next condition which is they must have different paths but if you see here both node 2 and 3 share the same parent which means they can't be questions so in this binary tree example you cannot find any cousins so let's add one more node to the binary tree so we have added one more node to the depth 2 and so let's take x is equal to 4 and y is equal to 5 the first condition is to check whether the depth of both the nodes are equal so yes depth of four and five are equal to two so the first condition is satisfied the next condition is they should have different parents so the parent of four is two and five is three they share different parents so the notes four and 5 are cousins so we are going to return true so yes as simple as that as you are understanding this concept how are we going to approach this by the understanding of this concept you must be clear by now which tree traversal technique to use to this problem so we have solved many problems using dfs and bfs since this problem goes level by level you must have figured out by now this problem can be solved by breadth first search so what are we going to do is we are going to check two factors for every node in this binary tree and any of the node satisfies both the condition then we are going to return true if not we are going to return false the first condition is if there is a node then we are going to check the parent of the node and depth of the node so we are going to check both parent and depth of both x and y and the parent of x and y must not be equal and the depth of x and y must be equal so by checking these two conditions we are going to return true or false so yes we have solved enough bfs problems so i am not going to explain how the algorithm is actually going to work we you can use either the iterative bfs technique or a recursive bff's technique to find both parent and depth of given nodes x and y so after finding the values it is easy to compare the pattern should not be equal and the depth should be equal and based on the result we can return true or false so it is again going to use this simple bfs recursive algorithm in this video and we are going to check for every node whether its left child or right child is x or y so that we can identify x or y's parent by checking this if x or y is one of the root notes children or the current nodes children then we declare that current node or root as the parent so we can find easily by this way parent and also as we go every level we are going to put a number or keep track of the depth and assigned it to the x and y step so once it is both the things are found we are going to compare the results and return it so before getting into the code this is going to work in big o of yen time complexity as we are using a basic recursive bfs technique and we go off again space complexity as we are going to make recursive calls for all this so let's go to the code now so as i said we need four factors to be found the first two are parent of the nodes x and y so let me declare them as a global variable and then depth of both the nodes so yes let's write a helper method to find these four values so this is gonna start from zero and keep track or increment every time at each level so first let us check the basic conditions if root is equal to null then simply return if not we are going to check if the current root dot val value is equal to x then we found its parent so because we are passing its parent every time in the recursive call so same goes for y so yes we are updating these four factors every time if we identify the node and if we did not identify then we are going to call the function recursively again and again till we find it so yes our helper method is done so let's go back to the main method to call this helper method as i said the depth is going to start from zero so once we call this helper method all these global variables will be updated so now it's time to compare and return the value so we are going to put a condition class which checks the depth are equal and the patterns are different if both the conditions are satisfied then return true if not return false so yes that's it let's run and try yes so let's submit and try yes our solution is accepted and runs in zero millisecond also if you see this problem has been asked in last year uh july league challenge so these month most of the problems are repetitive so you can find those videos in the channel already so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Cousins in Binary Tree
|
tallest-billboard
|
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree.
| null |
Array,Dynamic Programming
|
Hard
|
2162
|
52 |
hey everybody in this video we want to solve problem 52 on daily code challenge and queens 2. so in this problem uh we are supposed to place n queens in an n by n chessboard table such that no two queens that have each other so this is this problem is a more general version of an eighth uh queen problem uh but such that in this problem m could be variable so uh it would the size of the chessboard could be different so let's first talk about some facts so we know that whenever we place a coin in you know in the table in a board we can no longer place any other queen in the same row or in the same column of that we the coin that we just placed on the board so if we trade from the rows so from row 0 and then go to row 1 2 and 3 in this case we know that if we find a place for a queen on row 0 then we should go to find another one on row 1 and since we are supposed to place n queens in an n by n and we can not put two hands on the same row that means on each row we should be able to find the place to put our queen and then go to the next row so this is how we are uh we are going to use backtracking to solve this problem and we iterate rows by rows so starting from 0 to n minus 1. and then on each row whenever we find a place that uh there is no other queens already threatening or attacking that place we try that or place that and then we go to the next row until eventually we reach to uh we eventually feel all end coins in the table and consider that as a valid uh result so for example whenever we put a coin here we remove these all of these rows columns and then all these four directions that this specific coin attacks and then pass it to the next row using backtracking to find or try other places and eventually you're moving into these three of children's and find all possible answers so before implementing that backtrack i want to implement a board class so that we use for this problem so first of all for initializing these are the boards that we place a queen on and then pass it to the backtrack for the next iteration or for uh next rows that we are eventually trying to see if there are valid solutions but here uh we use it so that we copy the whole table and give pass it to the next one so that we don't change it uh change the because whenever we pass it arrays in python these are being passed by references and then the objects themselves are passed to the next one and but we whenever we try this one we want to also try the next one as well uh without changing uh the previous iterations so for size n and then so we know that the board itself soft board equals let's availability this is the board we just consider two states whether that place is available or not so it's a true also initially all of them are true or i can for easily say true times and here for in range n sometimes without initializing them at the board itself we want to copy from other board so if other board is none we create a new board otherwise we just copied at the other board so self.port equal c for seeing row for row in other word the board so this is the 2d array of other board and then we are just copy that and store it here also we can say selected n equals n so that to keep track of that other useful functions is uh get availables or for each row we get all available options so for example if we place it on the first row so this queen will remove all of these cells that are threatening and then when we move to the first row or starting from zero to here as you can see all of these cells are already taken and get available for row one should only return one option so we can define this function get available and then row number and then you just return j four or this is the columns so for c for event subjects and if self.board of row self.board of row self.board of row and c so if this is true for that a specific role you're iterating through n we could store it uh all available columns as well but since the number of uh the n the maximum value for n is nine in this problem so we can on each availability test we just iterate through at maximum nine iterations so this is not that much so we can use that and if that cell is true we are creating a list of all available options for that specific rule the other useful function for the board is to place a queen in a cell whenever we place it we should update the board such that removing all or changing the state of the all threatening cells from true to false so that in the next iterations uh no one can place a queen in those places so if i define that place in the row one column and then first of all we should remove all cells from the current uh row so self. or i for i or we can say board rule equals or let me change it so for i range n or result and first of all we remove everything from the cell and column so the board row and i becomes false as well as iron column so what we just did is just remove moved horizontally and vertically and removed all options because you're placing that row and column value and with four directions for the intj in what are the four uh directions available so whenever we place a queen so we move directly in a diagonal way southeast uh northeast north uh northwest uh northeast and southeast so these are the four directions minus one and minus four and minus one so we are starting from this and these are the directions and what are the starting point or column so x and y equal to row column while these are valid so while x equals self.n these are valid so while x equals self.n these are valid so while x equals self.n and zero itself that n self report of x and y equals false and then x and y equals x plus d i and y plus dj so we just move in four diagonal directions and then remove them what we could also do with uh replacing this and add these four other four directions as one and zero and so on but uh we already handled the column and row so this is okay so we just placed uh here and that's it for now so it should be fine moving to implement that backtrack itself so that backtrack for each iteration this is a recursive function for each one we are given a board and uh the row number so remember we are starting from zero and then eventually going to one add to m and minus one so as soon as we see that uh rho is greater than or equal to n so we should return one because that means for the very last iterations starting from zero one to 2 n minus 1 as soon as we see this is the end that means all of the previous iterations are handled successfully because if there were no available options for some row before n that means no solutions were found and we just returned zero otherwise as soon as we get to the nth row that means all of the end queens are already placed successfully and this is a valid answer and we are returning one otherwise this is the raw number so for c this is a column number in board dot gets available of that raw number and new board is a board we are just copying from the previous board so this is the pin and the board we are creating a new board from the given port so that we are just making a copy of that board so that we don't change it this board that is stores the all information from the previous information previous iterations and then new board that place this is the row number is the current rule and c or for more rituality i can say for column and then change and then uh valid answers from the current state initially zero and then valley dancers plus equal backtrack we are placing that on all available options for the current role we are placing and then running the back track on the new board and row plus one we are moving to the next row and this backtrack should either return a couple of uh the all possible answers or zeros so we are adding uh the answers storing the current for the current state in this valid answers and then after that just returning valid answers and initially we are researching our backtrack from a brand new board because if other board is not given so it is just initializing that new table with all true values so we just return just put one and the other one by default is none and creating a brand new table from row zero and just like that let me try so invalid syntax let's see oh we i forgot to put an if okay so let's try other test cases the edges one and the rightmost edge is nine okay so it should be fine let me submit that okay we handle to uh run this problem faster than the problem that repeats almost a couple of months ago in 2021 but this time we handled successfully let me see what did i do last time quite the same idea but instead of using a class i used functions but here with the help of implementing old useful functions or needed function in this class so we make our backtrack function more readable and easier to implement so that was everything for today's problem hope you enjoyed it
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
116 |
all right guys welcome back to 14 days sunday plus 2 o'clock i'll go asian day the last problem for today is medium difficulty it's the first medium difficulty question for bfs or devs so population next to rise pointers in each node we are given a perfect spinal degree where all leaves are on the same level and every parent has two children the finality has the following definition one left or right and next populates each next pointer to points to each next right node if there is no next right node the next pointer should be set to null initially all these pointers are set to node okay so for the example one this is our binary tree the nerd one has no right so it's the next one should be none here we have two otherwise e3 and finally now for the next so far is five next is second next is seven and finally the next is none okay if we have an empty lose we transfer to the empty root let's take care about this first so if not let's return the empty rows okay now let's make our query equal to our little let's initialize our degree we will use it to solve this problem this is let's initialize this by our road so while our view is still alive in this case let's calculate the size of our cube which is just the length of the ground now let's look for e in the range of the length of our size let's make our node so equal to dot pop left so in this line we are just okay so we start with the rows by one we are just this node should be equal this one the node one and removing the q from this one from our queue okay now if our a is smaller than length of the size minus one we just make our note next equal to q zero so if let's say that we are in this stage we're starting by four we make four dot pop left so now we pop the four and we save energy in this node in this case should we should be smaller than the length of size minus one and we just adding the next one should be just a q of zero because we are removing the nerd from our cube the q zero should be then the five now let's actually make sure that we are adding the left and right in our queue so if not dot left exist q dot append node left and not detroit i hope this makes sense to you and finally to install our node let's run the code okay all about this because um normally don't choose the size i go to the link of q i just can't wait to okay something wrong let's see what is wrong so i just want to remove this spacer interesting what the hell okay just show the roots sleeping with sex what a day and well i hope this video was useful for you i'll see you soon following
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
91 |
hey everyone welcome back today we are going to solve problem number 91 decode way first we will see the explanation of the problem statement then the logic on the code now let's diab into the solution so in this problem we are given a string which has digits right so we need to decode this string to alphabets right so we know the alphabet starts from A to Z so here a represents 1 and Z represents 26 right so which is nothing but a is the first alphabet Z is the last alphabet in the alphabetical order so we are pointing we are mapping Z as 26 right so we will be mapping each and every alphabet to their particular position in the alphabetical order so we need to figure out how in how many ways I can decode this particular digit in alphabetical order right so for example here we can consider two alone and 26 as one right so here 2 represents B 26 represents Z so this is one way then we can consider 22 as 1 and six as separate one right so here 22 represents V and six represented by F so this is one way so then we can decode this uh digit separately right so here 2 represents b 2 represents B again and six represents F right this is one way so for this particular example we can form three different types of alphabetical decoding right so this is what we need to find so we are going to use dynamic programming approach to solve this problem so now we will see how we are going to do this so initially we are going to create a dynamic programming array for n + 1 dynamic programming array for n + 1 dynamic programming array for n + 1 length right so here we have 3 + 1 will length right so here we have 3 + 1 will length right so here we have 3 + 1 will be 4 so we have four zeros here so now we need to just assume if a string is empty or if we have only one digit the number of ways to decode this one will be one right so we are going to make the first index and zero index as one at the start right so we are going to start the in index iteration from the index 2 till n + 1 so we are going to start from n + 1 so we are going to start from n + 1 so we are going to start from index 2 now so first we are going to check the i-1 digit in the string i-1 digit in the string i-1 digit in the string right so here I is 2 - 1 will be 1 right so here I is 2 - 1 will be 1 right so here I is 2 - 1 will be 1 right so in the first index we have two which means we are just considering the single digit right so we need to check whether this is between 1 and 9 so we need to check whether this particular digit is within 1 and 9 right so this is valid so we go back to the IUS one index that is first Index right in the dynamic programming array we add this to the current index that is I which means we are considering the previously calculated decoded base right so here we are going to get so now we need to check whether we can have two digit can be formed till the current Index right so we need to check that so for that we're going to have i- 2 index so we going to have i- 2 index so we going to have i- 2 index so we going to start from IUS 2 index till the current index if this is valid that we will be getting two digit right so current indexes 2 right so 2 - 2 will be 0 till the 2 right so 2 - 2 will be 0 till the 2 right so 2 - 2 will be 0 till the current index that is 2 I is two right so we need to consider all the string from 0 to two so we won't consider the second index value we only consider till one right so here starting from zero index so here we have two till the first index we have another two so here we have twood digit value when this is valid so we are going to check whether this is a valid one whether it lies between 10 and 26 so here 22 lies between 10 and 26 so we go back to the dynamic programming array so from here we go back two positions back because we are going to consider the decoding ways the number of decoding ways for two digits formed till now right so I - 2 digits formed till now right so I - 2 digits formed till now right so I - 2 will be zero so we go to the zero index and we take this value and add it here so 1 + 1 will be 2 now so now the index so 1 + 1 will be 2 now so now the index so 1 + 1 will be 2 now so now the index going to be three the I is going to be three so now we are going to check the IUS one index that is 2 right so in the second index we have six right so whe now we need to check whether six lies between 1 and 9 or not yes this is valid so we use the current index I so I - 1 so we use the current index I so I - 1 so we use the current index I so I - 1 is 2 right so we go to the second index we take that value and add it to the current index I right so here we are going to get two now we need to check whether two digits can be formed before right so now we need to consider all the double digit characters right so for that we going to start from i- 2 index to current index start from i- 2 index to current index start from i- 2 index to current index that is 3 so i- 2 will be 1 and current that is 3 so i- 2 will be 1 and current that is 3 so i- 2 will be 1 and current index is so starting from first index till second index we won't consider index 3 so we have 26 so yes 26 lies between 10 and 26 so this is valid so we visit the IUS 2 index in the dynamic programming array which will be the first index we need to add this one to the current index value is 2 + 1 we are going to get index value is 2 + 1 we are going to get index value is 2 + 1 we are going to get three so we are going to store this three in the current Index right so now we have done with all the characters in the string and we can just return the last value from the dynamic programming array that is three right that's all the logic is 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 not to check out my previous videos and keep supporting guys so first we have a base condition so if the first character itself is zero if starts with zero then that is not a valid string we return zero directly right so then we create the dynamic programming array for the length of n + programming array for the length of n + programming array for the length of n + 1 then we are initializing the first that is the zeroth index and the first index as one at the start so first we need to check so we are going to start from the second index so we need to check whether that particular digit is within 1 and N or not right so if that is valid we are going to consider the previously calculated decoded values decoded ways and we going to add that to the current index so then we need to check whether we can form two digits in the string from the current Index right so we are going two positions back and we are just checking that if that is valid if we have a two valid digits two valid characters we will go back to positions in the DP array we add that value to the current Index right then finally we will return the last index value where the number of f will be calculated right that's all the Cod is now we will run theod as you guys see it's pretty much efficient so the time complexity will be order of N and space will be order of n as well 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 keep supporting happy learning Che guys
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
70 |
hey guys welcome back to the channel today we're going to be solving these code 70 which is climbing stairs and this box is an easy problem to be honest i want to say it's that easy however i'll say this is one of my favorite problems only code okay so feel free to pause the video just to read through what the problem is asking for okay but i find these examples more descriptive so given a staircase where you can either take one or two steps okay how many distinct ways how many different ways can you make it to the top of the staircase okay so let's explore the different examples so now for the first example in the case where it's two steps okay so let's draw a staircase okay this is step zero this is step one this is step two okay we can only take one or two starting from zero okay if we take one that's one way or we take two so this is obviously the output is obviously two different ways we can take this right okay because i just showed you guys what it was so let's say output okay let's see the second example says three okay we have three stairs okay that's a terrible staircase okay step zero step one step two and step three okay obviously we can take one then we can take one okay that's one way to do it okay let me change colors okay or we can first take one and take two because we're allowed to take two steps okay that's the second way to do it let me change colors or you can take two first then take one that's the third way to do it so in this case output will be equal to three there's three different ways to do three staircases two different ways to do two staircases now let's also try one and zero okay just cause okay so let's say stack is where we had just one step okay this is zero this is one how many different ways can we climb this step okay obviously just one you just take one step right so in this case the output equals one and now let's try zero okay just zero how many ways can you climb zero steps okay i can make the argument okay like i made the argument that you can climb zero step in zero ways okay or you can also say there's only one wave climb zero step to be honest this base case doesn't matter why because we have three base cases we have base case of zero we have base case of one we have base case of two and we have base case of three so this is this problem pretty straightforward and keep in mind one so the trick to this problem is to understand that say you have any staircases it doesn't matter how many going from zero so this is zero one two let's say three it doesn't matter three going from zero to three is the same as going from three back down to zero it's the same so it depends on how you did if you do it if you think of it like you're going from zero to three it's called a bottom-up approach if you think of it like you're starting at three and you're going down it's called it top down approach but you notice something this problem is just simple so say we were given a status of three f of three this problem is just simple in this case because oh let's not use three is actually not as good of an example to be honest let's say we're given a problem f of five okay we can see f of five since there's two choices we can make let me write it in the center says my cleaner f of five there's two choices we can make we could take one step okay and get to f of four or we could take two steps and get to f of three okay now from f of four two choices we could take one step and get to f of three or we take two steps and get to f of two okay now from f of three there's two choices we can make we'll take one step and get to f of two or we can take two steps and get to f of one in this case we can say f of one is our base case or we can even go further from f so we can take one step and get to f of one or we could take two steps and get to f of zero okay and we know f of zero is zero or one it doesn't matter to be honest which one you say it is and you see one second from f of one is our base case so we can only take one step to f of zero or to be honest you can stop here because we know what f of one is we know f of one is one okay so here f of t you have two choices you can take one step and get to f of one or you can take two steps and get to f of zero again we know this guy f of three you can take one step and get to f of two to take two steps let's f of one go from two you can take one or two steps one step and get to f of one two steps and get to f of zero okay this you can only take one step here's our base case we know if n is less than or equal to three there's only n ways we can do it so you see in the case of zero where number of stairs is zero there's only zero ways we can take n equals zero it gives us energy in the case of one okay there's only one way we could do it n of one equals one we need f of n of one equals one in the case of two there's only two ways we could do it f of n of two equals two in the case of three so anytime rather than zero is just n so we know these base cases so we can just go ahead and fill them up f of zero is zero waste f of one is one way f of two is two raised f of three is three ways okay we can just start filling them out one filling out our base cases okay and just go up but to be honest it might be better if we say f of zero equals one to be honest let's take off f of zero equals one so that way it kind of makes sense to us but again like i said it wouldn't matter and you'll see why so when you look at this all you see is just a simple fibonacci problem like i said this is exactly the fibonacci sequence so let's literally code it up right now okay so what we can say is we're coding it recursively right now we can say if n is less than or equal to three okay kind of like we developed on the paper n is less than equal to three we just return n this is our base case okay else that's where the meats and potatoes start okay we're gonna return a recursive call of this function so we're gonna have to call this guy recursively so it's going to be self dot because it's in a class that's why you have to use cell self dot and minus one plus the same self done yeah minus two again it's exactly like this tree because there's two branches we can follow okay so once you do this looks straightforward let's go ahead and submit this and see i think this should be the answer okay good although this is the right answer it timed out okay let's see white time that i come out at 44 because it takes so long to find the 44 number so we have to do something to make it faster and if we go back to this since we know the base case we've written inequality n is less than three we know it's a base case we don't have to calculate it again so pretty much this eliminates anything below three we don't have to calculate it again okay anything below three and also once we calculate something once like here we're having fb2 why do we have to calculate him again here we can just store his value we can just store the value of everyone we've seen create a dictionary so i'll call it memo create a dictionary key value players where when where we meet zero f of zero will start him with his value f of one the moment the first time we made it we started f of two f of three moment we made it with story okay number four again we don't have to do it for three applause because it's pretty straightforward because it's pretty simple but from four onwards we're gonna have to do it okay so let's see that so i'm gonna create a new variable called memo set him to an empty dictionary for now okay so once i have memo the first thing i'm going to do once you come in the function i'm going to say if and in memory okay if n is in that dictionary i just want to return okay it's pretty straightforward okay else okay we can we don't have to create them for this case we could but there's no point okay well actually let's okay let's actually do it just because we're bored let's see name of and it's going to be equal right and we're just going to return more than okay the same thing here i'm going to say memo of n is going to be equal to this guy and we're just going to return here okay so now we're storing those values so now let's try this out and see what happens damn this is correct very fast users may only be very good so now let's we're gonna this is not the end okay but for this video we're gonna stop here okay we're gonna have a second solution where we second video where we see a different way to solve this problem but for now you can hang on to the solution and i hope to see you in the next one
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
1,704 |
hello guys welcome back to my Channel today we're going to solve this leate code question which is uh determine if a string halves are alike uh okay let's solve this question in this question we are given a string s of even length split the string into two halves of equal lengths and let a be the first half and B be the second half two strings are alike if they have same number of WS a IOU or Capital AE IOU not that s contains both uppercase and lowercase letters written true if a and b are alike otherwise written false this question is very easy to understand you know you can look at these four lines and you can easily initially we need to split the string into two halves a is the first half and B is the second half and count the number of ovs in the first half and count the number of WS in the second half and written true if the number of WS in the first half is equals to the number of WS in the second half else WR false that's it if you look at this example in this string you know the first half is B we need to divide the string equally uh you might get a question like what if the uh length of the string is odd but he um in the question they have mentioned that the length of the string is always even so we don't need to worry about that we can uh split the string into two equal halves uh if we split the string into two equal halves it will be B will be b o and okay is an another half right in B there is one W and okay there is another there is one W so since uh both the halves contain one same number of ovs we return true right in this string you know we'll divide the string into two halves uh in the first half we only have one wov that which is e and in the second half we have two ovs since these two are not equal we'll return false that's it uh let's see how we can solve this question uh it's uh very uh easy initial we'll declare in first half initial what we need to do is you know since we are having both upper case and lower case letters what we need to do is uh let's uh convert the string into lower case because you know when we convert the entire string into lower case we can only check for the lowercase uh lower case WS right suppose uh we are given a string like uh A B C and C D A in this question you know if we divide the string into two halves you know uh in the first half we have one OV and in the second half we have one o but in this case we need to check for you know the small a as well as the capital A whether there are you know ovs or not but we try to play it smartly like uh we can convert this into lower case the entire string into lower case then it will become like this uh when you convert this into lower case we can only check for small a right small a being a so that's what we'll do we'll convert s = to S do case after converting this uh this I'm sorry this variable will count the number of oils in the first this variable will count the number ofs in the second half we'll just Traverse through the s dot A+ dot A+ dot A+ if uh I is less than length by 2 then and wait uh let us make sure that the given if is Will of Care at of Y this function will return true or false if the current uh character is a OV or not OV of car c h if c h is equal a or C is b or not a and forse this case you know we need not uh we don't need to check for Capital a capital E because we have converted the string into lower case right we can only uh we can only check for small uh small letter and if the current character is O well and if it belongs to if the length of the string is less than do length by two then it belongs to the OV in first half right so I'll increase that else in second half at the end I just return willon first half equal second half that's it let's try to run this yes uh it's getting accepted let's try to submit it yes uh all right guys that's it for this video thank you
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
70 |
hello everyone in this video i'll be explaining the climax test problem so this is a lead code easy problem and it's asked in interviews of big companies like google and microsoft so let me explain the question to you so you are climbing a staircase it takes n steps to reach the top each time you can either climb one step or you can climb two steps in how many distinct ways can you climb to the top so the input will be given which will be the number of stairs so basically the problem says that you have some steps okay and each time you can just climb it using one step or you can climb two steps at a time okay so then for each step it's only one or two at a time then one or two at a time like this how many ways can you reach the top stair okay this is the problem statement now let me explain it to you this is a dynamic programming problem okay now let's try to solve the problem so let's say we just have one step like this how many ways can we reach the top of this one step there's only one right because you can either climb using one step or two steps at a time so this will be only one way let's say you have two steps now so you can either climb one step and reach the top or you can climb both at once and you can reach the top so number of ways you can reach the top is one and two which is equal to two let's say you had three stairs okay so you can either reach it by going one step at a time or two step in one step or one step and two step which is total number of ways will be three if you had four steps it would be one two like one step at a time or one step and then jump two steps then go one step again or two steps one and one or one and two so the total number of ways will be five fine so in this can you see a repeating pattern the pattern is initially one and two we'll initialize it then one plus 2 will give you 3 and then 2 plus 3 will give you 5 so basically we can reach every step by adding the number of ways in which we can reach the previous two steps so let's write the code number okay so we have a function i'll be writing it in javascript but you can pick whichever language you want so let's have a function climb stairs and n will be given as our input which is number of steps okay and we'll have a which is an array initialize array of one an array of two arrows one and a of two which is equal to one because you can reach first step in just one way and add off 2 if you have 2 steps you can reach it in 2 ways ok so 2 now for the remaining you can just write a for loop so let i equals 3 because we've initialized 1 and 2 we'll start from 3 and then i less than equal to n for the number of steps and i plus and then array of i which is the current step you're at will be equal to array of i minus 1 plus array of i minus 2 this is very similar to the fibonacci series problem and then finally we return array of n is the last step and if we return array of n it will have the number of ways in which we can reach the final step so now i have already typed this code and kept it let's put it in lead code and check if it works okay so here is the code that i've already typed let's just copy it and here is the lead code problem and let's just paste it even okay so it passed and i'll submit it now okay so this has passed and all the test cases has been resolved that's it for this video you guys if you have any doubts you can put it in the comments below and i'll be more than happy to clear them also if you like the video please give this video a like and that'll make me more than happy and also please subscribe to the channel for more videos like this thanks for watching
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
799 |
hey everybody this is larry this is day fourth oh i'm after midnight until march leco daily challenge hit the like button it's a subscriber and driving discord let me know what you think about this prom um yeah there's a lot of things going on in the world right now hope everything's okay i hope everyone's just you know uh um you know take care of yourself first and then if you have a chance take care of others and yeah uh and to that extent maybe today we'll talk about 799 champagne tower a medium problem um okay so yeah first row second one okay so what are we supposed to return i mean i get the simulation but um oh so wait what so we pull uh okay we have to read this a little bit carefully uh okay so the top most glass is full okay obviously okay so the what we pour one cup of champagne to top glass is it infinite or something is that why uh until the hundredth row that's a little bit weird though okay fine let's keep going okay so the top uh champagne okay and then what are we returning this is such a weird problem to read maybe i'm just lazy okay uh okay so you pour one cup of champagne on top glass there'll be no excessive so autographs okay that makes sense just diagrams and i wish they did more diagrams in general so again so you put two cup champagne in the top glass uh one cup of excessive so then okay yeah i mean i think there's a lot of ways you can want to do this um you could do this with um watching my card uh bottoms up or top down uh it's gonna be dynamic programming is the uh idea uh i mean you could construct this recursively right where you just pour you just simulate it in a way you're just trying to figure out um how many how much gets poured into one glass and then keeps going the way i'm going to do it is with bottoms up because i think for me it makes sense to simulate a row at a time right so then now we go with you know let's say row is you go two um yeah let's just say zero or maybe poured i guess in the first row and then now for um okay then next row is going to do say and now for okay yeah so then now that means that for every row something like that right so for every row i hope there's some music in the background when i'm very noisy hot still right now oh i haven't given up there on that one but yeah so if you watch my video from yesterday there is some uh drama with respect to airbnb i think i left out some parts where uh the airbnb host or len person then lady uh was trying to i think extort more money from us and we kind of refused which is what led to an issue but anyway the end result of that one is that now i'm in a hotel slash i think it's more of a hostel than hotel i think i'm in a private room in a hostel which is fine but right now they're playing a little bit music so if it's in the background my apologies i'll be back in new york in a couple of uh days and hopefully that'll be resolved itself but yeah so that's kind of the quick update on that one but okay so then now for each row um i'm just thinking a little bit about the off by oneness um i guess query glass can be zero so if this is zero then we already do this one right so okay so then now we go for um i don't know for i is in range of so each so the i flow um i guess let's just call this i oh well maybe not then uh for eye flow it will have uh i number of cups to uh to fill right meaning the first one will have one cup the second will have two cups the third one three cups and so forth and of course if you really think about it this simulates very closely the binomial distribution or um on that binomial distribution but binomial um was it the pascal's triangle i guess it's maybe a better one to think about it so it's up relating to that and yeah so then now we do this and then we for j is equal to y then next row um so we append because we assume that next row is going to be empty i guess we'll just do it here instead um here we append row of so let's say i is so let's just actually start from one to plus one i think that's a little bit more sensible so then now we look at the previous row right so we're on row one then we is i minus one we look at the j um let's think about this a second right so basically for example we're looking you know i'm just looking at this diagram really um the leftmost one will have no and if you look at the index by the diagonal then the leftmost one would be this um right plus if you have on the other one then you would get contribution from two uh cups right so it's this plus uh something like this but of course you can't just write this because j is um yeah j minus one can be negative right so basically if j is equal to zero then we do something like this uh and this isn't quite right yet so uh so i'm a little bit disorganized today me and i apologize for that but yeah but basically here if j is equal to zero then is this minus one because one is the full cup and then we also want to um delta by two um because you know it goes from the left both left and right so it's this and then here this is this um minus one to fill the cup uh divided by two and then this as well hopefully this makes sense i don't know that i'm saying it in a queen way but basically the idea is that you just take the excessive from the previous row and that's basically the idea and then next then what we go to the next row and then we are good then at the very end we return row of um wall of query glass up glass not class and i think we're good but we'll see this is why we test right um i think we have the right idea uh okay into object not subscribable oh yeah okay so i'm used to writing i minus one but actually this isn't necessary because we're not using the matrix i did it i did a premature optimization to be honest uh or at least an optimization that i didn't talk about uh because n is equal to 100 so that should be good but um with that said i didn't do it um okay so did i mess this up so okay so if i is zero then it's gonna be zero so yeah so i think we need to plus one here so i made a mistake on the next flow maybe uh okay maybe i'm um oh whoops uh that's a little bit awkward uh did i mess this up hmm i think okay let's take a look let me think about this for a second uh hmm did i mess up or is this one indexed no choice glass is zero index so hmm that's a little bit awkward huh why is the answer is just one for example oh no i see uh so even so if it's query row is one we do this once and then yeah uh okay so the query was okay so this should be plus one because on the first one we want to execute it once i think this is i mean we still have an issue but um i think this is more correct and then now we have this row is given an issue um oh i see because uh um how do i say this uh okay so if we're looking at this thingy it looks at negative one but it doesn't look at uh okay so i think i just messed up in the sense that for example in the rightmost row um this thing is out of bounds right so i think that's the thing um how do i write this in a better way okay let's just say uh cone oops current is equal to zero uh if j is not zero that may be current row of j minus one over two always make sure you have to comment uh and then if j is not equal to i because if j is equal to i then the previous rule doesn't exist so then now you have j minus one right uh and then of course we want to append this i think this is maybe a little bit more better though now i'm uh just double check okay so we got the first one the second one but not the last one why is that that seems weird why do i have such a weird answer did i mess it up oh i see i'm just being dumb uh because we append this um as kind of so this contains all the excessive stuff but what we but this contains all the excessive stuff meaning is that um this should have at most one because every class have at most one i just store it with respect to keeping track of um i store it with the accessible as well so that would be the number with the excessive uh liquid um okay so this looks okay let's give it some mid mostly because i'm a little bit tired today hopefully this is good uh maybe i get some oh no oh huh i mean that's correct because uh man i am very sloppy today my apologies um and we'll tell them uh obviously this is only if this is positive so we have mass of this and zero uh very sloppy though basically this is just saying that it only trickles down if the uh the glass that we're looking at um has enough to trickle down but i forgot about it that just made very sloppy on my end all right let's give it a submit again hopefully this is right if not then i'm just gonna be sad um okay so that looks like that's good 703 days um yeah so this is straightforward volume said the guy who got it wrong but it's just about thinking about all the cases and i clearly did not to be honest i watched it a little bit this should have been clear but i think i was focused on the excessive part and not if it had under um and also to be frank if you add more test cases this should have came out very quickly this is probably even a lot of test cases where this would have came out if you don't have enough liquid um for example if you just do this but um but like you do uh which one is it so one uh yeah one three one or something and that would already should have given you a zero and i have it right now obviously but if i didn't have this line it probably should give you the wrong answer um because i didn't have keep track of minimization of zero um but yeah so what is the complexity the complex is gonna be um rho squared where low is the number of uh things you could also make some optimization with coil glass because obviously you don't need stuff to the right of it maybe i'm wrong on that one but maybe you can let me know but yeah but at worst it's going to be 100 square that's why it's fast and that's why i didn't really think about it because it's 100 squared right um in terms of spaces of n where n is the number of rows so yeah i mean of course you can also do n squared in terms of space for um you know it doesn't hurt that much because it's only 100 square um but yeah that's all i have with this one but let's take a look to see how past larry did it um okay um i mean basically this is exactly what i said about n squared time and n square space i'm curious why i don't oh i see if this is great i had this if statement which made it i was wondering why it didn't get to negative stuff i had that if statement and that was all the difference which i didn't do because i was a little bit um i think to be honest that is one thing that i would say is that sometimes you get overconfident and you do a premature optimization and this is what happens i try to write it very short but if i just like rolled out all the cash cases and even say it in english this would have been pretty straightforward um but uh but yeah i mean i'm still in um made it in uh so i'm a little bit iffy for now but hopefully i'll be back in new york soon and we'll do this in a better larry uh i'll see you soon but stay good stay healthy do good mental health and i'll see you later bye-bye
|
Champagne Tower
|
minimum-distance-between-bst-nodes
|
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.)
**Example 1:**
**Input:** poured = 1, query\_row = 1, query\_glass = 1
**Output:** 0.00000
**Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
**Example 2:**
**Input:** poured = 2, query\_row = 1, query\_glass = 1
**Output:** 0.50000
**Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
**Example 3:**
**Input:** poured = 100000009, query\_row = 33, query\_glass = 17
**Output:** 1.00000
**Constraints:**
* `0 <= poured <= 109`
* `0 <= query_glass <= query_row < 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
94
|
343 |
Hi Everyone Welcome Back to Today's Video So our question today is integer break and in this question we are told that we will be given an n value which we have to break into positive integers of the case and that is k. That minimum should be two, okay and we have to choose the values of them in such a way that our choose the values of them in such a way that our choose the values of them in such a way that our product should be the maximum product. Now like here we have been given n e 10, okay so we have an option. It is 9 p 8 p 2, then 7 p 3, but the sum of all these people is 10, okay, but what is the product of these people, their product will be their 16, their 21, if then like here we assume that our 3+ 3 + 4 is also assume that our 3+ 3 + 4 is also assume that our 3+ 3 + 4 is also giving even 10 but what is its product 36 so that is why we will consider this value and return the maximum product. Now if we look at this condition then we are doing this that we We are checking a possible value, isn't that what we are doing? We are exploring all the possible conditions. So when this happens to us, we are not discovering any value or some value. To find out, we check all the possible conditions, then what do we do in that condition, do we use recursion? Okay, so now we know the basic that our recursion is there, now since it is recursion, then we use DP to optimize it. Now we know that the approach will be of Rikers and DP, so in this video I will tell you three approaches in which we will start with Rikers, approach one will be our Rikers, after this we will We will optimize and it will be memoized and after that tub is fine, so now we see first recurs, so for recurs we are taking only example n e 10, so basically what we have to do in recurs. There will be an index in which we will hydrate and here we have a target value, then a target value is given, now when can we add any value to it, like now here we have an index, okay so either We will be able to pick any value or leave it, so we have two conditions, pick or not pick, okay, so one is picked, one is not picked, now here is our outer value, no, it will start with no. And this will be our 10, I started it with nine because the one which is one will be an obvious multiple of any one, like here we have 10, okay then 9 + 1 will become 10 we have 10, okay then 9 + 1 will become 10 we have 10, okay then 9 + 1 will become 10 or if there was seven here then One is a minimum value, that's why what we are doing here is that we are starting from n - 1. Okay, so starting from n - 1. Okay, so starting from n - 1. Okay, so now if we pick this value, then what will happen to us? How will the value of the target be reduced? And how much will it be? We will keep this index value the same because it is possible that if we assume here that if it were 18, then it is okay that n = 18, then we would do 9 x 9. If so, then this n = 18, then we would do 9 x 9. If so, then this n = 18, then we would do 9 x 9. If so, then this same value would come twice. So if we have to find the same value What will be the value if it is reduced then what will happen to us here 10 - 9 then what will happen to us here 10 - 9 then what will happen to us here 10 - 9 then how much is this one. Here we are not picking, meaning we are not using nine, so now we are decreasing the value by one. We will make it eight and our target will remain the same because we did not pick anything. Now we see here that our target here has become one. Okay, now if our target has become one, then it is okay. So we can minus any value only as long as it remains less than the target, that is, if the index remains less than the target, only then we will be able to substack it. Now here, what is our target? It has become one and here we have What is the pass index value? If this condition fails, then what will happen to us? It will stop here. Now what do we do? If we come here in the not-pick category, we will see in the not-pick category. not-pick category, we will see in the not-pick category. not-pick category, we will see in the not-pick category. Now here again. We have two options, pick or not pick. Okay, so if we pick A, what will we have? F off this value, we will keep it like this, after that what will happen here is 10 minus 8, so here it becomes T. Now after this, there will be two options here, now again here, not pick, if we do not pick, it will be sen, right, and after that it will remain the same, 10. Now let's see what we have here. The target is 8 and this is our target and this is the number so now what happened here is the target is our two and what is the index value is 8 so if this condition becomes false then this will not happen now what will we do its not pick If we see, what will happen here, this value, this index value of ours will be reduced to seven and this will become three. Okay, now the same will work like this here. Okay, so now we are seeing that when we are picking. If there is any value then that value is fine, what will be the index value, it will also be multiplied along with it, then what will we do after that, index into target minus index is fine and we will pick this only when our condition is such that Target i is greater than and equal to this iterator value now what we have to do is to return a maximum value not whatever our product is if we write what will happen in pick not pick or not pick It will be A of I AD my target is ok so this target will remain the same, if we erase it then it is ok, this is our bean, now here it is not picked, now there is a condition to pick, in this case this condition is sometimes If it is not true, then if we select maximum of not and pick here, then this variable has never been declared, then it will show an error, that is why what we will do is to initialize the pick with zero, okay, so our Which is the maximum product and will be returned, now let's write it clearly once, okay, so that when we memorize it will be easy, okay, so what is ours, not pick is our function and the index and target index will be minus and here Pick we are initializing from zero then if the value of target is greater than and equal to index then what we will do is pick the value and multiply it or index into F of I nd target and then we return Will give max of pick comma not pick Okay so when we do memorization then we do n't have to do much. Okay now what is here we now yes we had to define a base condition then what will be our base condition we People will see that when the minimum value goes to one, if our value is one, then what do we have to return, it is one, because if we see, then if the value is one then the product will not go. That's why if we remain one, our ID should not be the value but it should be the actual target, then we will not return it. Okay, now it's done, now we memoize it, so when we do memorization, right? So just two statements are added to it, what happens is that first of all we are declaring the DP. Okay, so how will the DP be declared? Now when we declare the DP of our DP, we see how many joes are there in our function. Are the variables changing? Now if we look at them, we should have had minus I AD also, so here we are seeing that the index is changing and the target is also changing, so what about us? As the variable changes, the dimension of the DP remains the same. Now here the function index is also changing and the target is also changing, so our two dimension DP array will be declared. Okay, now the meaning of DP is inner. The outer part will be DP like this, so what will be inside it, we will store the target, okay and the outer part will store our index, so what is our index going on here till n mive, so we will store it. We will keep DP of n length and it will go up to our n p. Okay, now we know the dimension of DP, now how do we insert DP in this code, so when we do memo, what do we do? This is the base condition. Our same remains the same, after the base condition, one more condition is added that if depth of eye AD and target is not equal to minus v then we return depth of eye AD and target. See if there is any complication in this. There was no discussion, what do we have to do, our base condition remained the same, we just had to add one line here and our one more line will be here in the return statement. Okay, so what will we do? Return DP of index target equal to max. Off Pick and Not Pick, our memorization was done very easily, we did not have to think anything extra in this, we just had to add two extra lines, one in the return and one in this condition. Now using this we can also create tabulation. Okay, so our tabulation comes, so if we see, we have a condition, the condition is already defined. Okay, so what is the base condition that we have, if there is one, then we have to return one. Okay, so what will we do first? People will make a loop for I in zero to target, okay, it will run till the target and what will we do, which is our DP is defined, in this it is okay on the first position, or in the first position, one will be assigned in every target, meaning if we have a it And how will our DP be? Its minus and mive kama mive mine, neither this one is the same, meaning it has become zero index, this has become the first index, so what will we do, the first one which is the index, whatever number on it Values are there, we will change them all and make them one, Values are there, we will change them all and make them one, meaning this was our mive, otherwise this will be our deep change and will become something like this, all these values will remain human because all the all these values will remain human because all the values that were there on the first index at the zero index are new one. Okay, values that were there on the first index at the zero index are new one. Okay, values that were there on the first index at the zero index are new one. Okay, so this is ours, now we have completed the base condition, okay, now we move ahead, now the base index base condition has been completed, now we see pick and not pick, now we are here. We are seeing that we have a two dimensional array, so basically we need two loops to add it to it, so the value of our i will be the start, right here we are seeing that our outer loop is going on, it is okay. What we are doing is that the first one is the value, in this we have already assigned one everywhere, then it will start from our two and it will continue till whatever the value of the index is, okay, less than and equal to, now which is our second. There is a loop, okay this is our J, let's assume it will start from zero and it will run till the target, okay this is our two loops, now we have two loops, now what we have to do is pick and not pick, so not pick initial. Let's ease the pick by zero because there is going to be no change in it. Okay, now here what we had was not pick, f of I AD - 1, okay, so the pick, f of I AD - 1, okay, so the pick, f of I AD - 1, okay, so the values like f of AD - 1, values like f of AD - 1, values like f of AD - 1, comma target, right? So, what will we do with the value of not P in this? What is D P of I AD? Here P is A - 1 and AD? Here P is A - 1 and AD? Here P is A - 1 and what is the target in this. If J is then it will be J. Now we will again check the condition here if J is greater. Dan and equal to aa, so if this happens then what we will do is we will pick that value and then multiply that value by multiplying by aa by multiplying k d p off a minus sorry d p off aa. What was our pick? F of I is AD and target is minus ID. So what will happen here is D P of A and J - A. Okay, now D P of A and J - A. Okay, now D P of A and J - A. Okay, now this condition is ours. Okay, now what do we have DP? If we have to store the maximum value also, then DP of I is equal to max of pick and not pick. Now if we look at it, basically this was our recursive code. This was our sequential code. Due to this, we also made memorization. And with this we have now done the tabulation, so now we come outside this and what return will we make outside, return DP of I ND and target, so whatever our time from recurse to tabulation is recurse. I have time complexity, every state is being checked twice for every condition, then this node, which is this, will be checked twice, that is why this is becoming exponential. Okay, now space complexity is being used. Okay, now here in memorization also, our space-time complex is getting reduced from T power A to OFF A, okay and here our stacks pace will be removed, only here we will be left with DP, okay. So now let us try coding this question, right now I am just giving the code of tabulation here, I am coding the rest, then whatever is our memorization and recursion code, I will execute it and upload it on my Git up. You people can refer from there. Okay, so first of all we have to declare a helper function where all our work is done, so we have declared a helper function here, what will we pass? One and one DP will be passed, ours is okay, so we have declared DP here, deep minus and this will be A PSV Multiply, here we will pass A, now we will pass return cell dot helper from here we will pass A and We will pass D. Okay, so now what was the first condition? If we want to use the base condition, then I am in the range of A Psv. This A Psv is in a way our target, that is why we have made everyone one in the first index of DIP. OK, now we will run through two loops from i in range of u, we will run till a mine, ok, so we will write y and j, we will run till the target, till the entire target, so here we will use a, ok. Now one is our not p condition and one is our pick condition so pick will be equal to zero and what will be in not pick is depth of i mive and j. If now the j of ours is greater than or equal to i then we If we can pick or not the value, we will pick the value and here it will be i. Multiply will remain whether we pick or not pick, we will put it in DP of IJ, then max of pick, earn, not p. Now what is the value assigned to us? Done, we will return the value D key P of A MIVE and A Now let's run it and see if it is accepted Now let's submit and see that our value has been accepted
|
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
|
166 |
are you stuck on a coding challenge don't worry we've got your back let's dive in and solve the fraction to recurring decimal problem together this problem statement is asking to take in two integers as input which represent the numerator and denominator of a fraction the goal is to return the fraction in string format including any recurring decimals if the fractional part of the decimal representation is repeating the repeating part should be enclosed in parentheses for example if the input is numerator equals 1 and denominator equals 3 the resulting decimal representation is 0.33333 so the final output should be 0.33333 so the final output should be 0.33333 so the final output should be 0 in parenthesis 3. it is also mentioned that if multiple answers are possible any of them is a valid output it also guarantees that the length of the answer string will always be less than 10 to the power of 4 for all inputs the approach of this code is to convert a given fraction numerator and denominator into its decimal representation the code uses a combination of mathematical operations and a hashmap data structure to achieve this the code starts by initializing a string Builder to store the final result it then determines the sign of the decimal representation by checking if both the numerator and denominator have the same sign or if the numerator is zero next it converts the numerator and denominator to their absolute values and appends the quotient numerator upon denominator to the result it then calculates the remainder numerator modulo denominator and checks if it is zero if it is the result is returned as is if not the code appends a decimal point to the result and starts a loop to calculate the decimal representation the loop uses a hash map to keep track of the remainders and their positions in the result the remainder is calculated by multiplying the previous remainder by 10 and taking the modulus of the result with the denominator the code appends this quotient to the result and continues until it encounters a remainder that has already been seen at this point the code knows that the decimal representation is repeating and inserts an opening parenthesis at the position of the repeating remainder it then appends a closing parenthesis and Returns the final result for example if the input is numerator equals 1 and denominator equals 3 the resulting decimal representation is 0.3333 so the final output will be 0 in 0.3333 so the final output will be 0 in 0.3333 so the final output will be 0 in parenthesis 3. in this way the code uses a combination of mathematical operations and a hash map to convert a fraction into its decimal representation while handling repeating decimals correctly the time complexity of this code is Big O N where n is the number of unique remainders that we encounter before finding the repeating remainder the space complexity of this code is Big O N where n is the number of unique remainders that we encounter before finding the repeating remainder this is because we store all the unique remainders and their positions in a hash map and the maximum number of unique remainders we can encounter is n to understand this let's take the example of numerator equals one denominator equals three in this case the decimal representation of the fraction is 0.33333 which means of the fraction is 0.33333 which means of the fraction is 0.33333 which means that the remainder will always be 1. so the loop will keep running indefinitely and the hash map will keep adding new entries for the same remainder in this case the time and space complexity will be infinite in another example let's say numerator equals 1 and denominator equals 7. in this case the decimal representation of the fraction is 0.142857142857 which means that the 0.142857142857 which means that the 0.142857142857 which means that the remainder will cycle between one four two eight five seven after seven iterations the remainder will repeat so the time and space complexity in this case will be big O7 so the time and space complexity both depend on the number of unique remainders we encounter before finding the repeating remainder since the maximum number of unique remainders we can encounter is n the time and space complexity are both Big O N thanks for following along I appreciate your attention and we hope you found that explanation helpful if you found this video helpful make sure to hit the like button leave a comment and subscribe for more content on this topic
|
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 |
792 |
hey everybody this is larry this is day 20 of the july legal day challenge oh no free points today coins hit the like button hit the subscribe button join me on discord let me know what you think about today's problem number of matching subsequences hopefully today's implementation will be a little bit better than yesterday's i hope everyone's done all right uh tuesday already uh i don't know what that means but let's get uh started but they just not loading okay uh anyway given the string as an array of words return number of words i that is subsequence of s is it just uh i don't get it huh oh sub sequence not a substring okay that's fine um i mean it's still on the easiest side but i was a little bit one thing i do misread a lot is substring and subsequences so i was like substring you just do like a for loop and then in you know the thing is in the other but now it's the same idea it's just that we do a sliding window right um we can do something like we can write a helper function go match subsequence right of an s of a word and then let's put out later but then after that we go forward in words if match subsequence of s and word then count win command and then that's pretty much it right you have to do the match subsequence and here of course you use the two pointers algorithm uh here you want you want all of word to be used and as many as much of s as you need so basically we're gonna look at each word or each character from word one at a time so then here we have four w in word uh we have maybe s sub i is equal to zero right so while s sub uh yeah sub i is less than let's just say length of integrator s and as of uh s i is not equal to w we continue well actually we increment by one um otherwise then that means that when this loop ends if s i is equal to n we return force uh if s i if s of s i is not equal to w for some reason we don't voice i don't think that's possible because of the invariant but i am lazy so if it's equal to w yeah we contain you so we can just skip this i suppose or it goes to next one and the way you end we return true and i think that is good enough so let's kind of do that loop yeah oh uh i messed up here actually um because here that's what i meant to do i was like i feel like i forgot something um so now that it match you want to increment by one so that you use up this current character that's uh cool uh looks good i have to care about empty strings or anything like that probably not so yeah i think we can also do something like maybe just like a small word with a big thingy just to make sure i don't have like weird of it away index or something like that all right let's give it a quick submit is it so slow uh-oh i have time limit exceeded uh-oh i have time limit exceeded uh-oh i have time limit exceeded i now look at the constraints i did not look at the constraints so uh hmm yeah i'm not gonna lie i did not look at the constraints so we can take a look at what the constraints are silly mistake again though so as of length so this is only 50 characters right so why is this it's just 50 times 5 000 right um why is this so slow did i mess up something i mean yeah you can cash it or something but that's just like a really like um what you record like a constant time optimization right i know that they're using the same string oh i see because basically okay i see what happened here i misread this thing it's time limiting out because uh if it's not in the string then yeah i guess i was a little bit lazy this time usually i'm i do uh maybe it wasn't this fun but i do usually write this a different way but i think i just didn't look at the constraints to be honest so that was me being sloppy um i think i saw five thousand times fifty i think i missed this one anyway um i confused clearly i confused the constraints a little bit so i mean even so though wait isn't it 50 did i miss wet oh i still miss red to constrain each i took it with 50 words okay so that's why i was sloppy okay uh so close but basically okay now we have to do the other one but um it's the same ideas before so if before our idea was two pointers now we want to accelerate the two pointers right and what i mean by that is uh wow i missed i totally misread this twice even um and what i mean by that is that you want to be able to skip to the next um you want to be able to skip to the next character immediately instead of here you just do one character one by one okay but the good thing about this abstraction is i don't have to change any of the code there i just have to change it here though i should pre-process so i am going to do that pre-process so i am going to do that pre-process so i am going to do that so i am going to just put it into um uh i want to record it in a way of a way so let's do that let's just call it lookup yes you go to yeah i usually actually do this with like um whatever but yeah um yeah i mean this will be bad uh this will be easier for look up for even though i could have just made in the way of 26 characters but uh yeah so basically what we want to do now is just keep track of their indexes ah man i am sloppy today and this week maybe um basically this is a look up of old so for every character in s we index the um the index of the character and of course this is going to be monotonically increasing so you could kind of keep going that way and then here we can just do how do we want to do it i mean you can do this with either binary search or just walking the tag i think walking the deck is probably a little bit better maybe can that be bad i kind of think whether you could get to a case where it is exactly the same as here but i guess technically definitely not this particular case but it can because you wouldn't no because then you would have like if i was being lazy i can do something like this times i don't know 5 000 or 50 000 and then like a b and then we just do like and then another a and then you could do ba and then now it would try it'll skip here but then you would literally walk to a is going to be just the same right so okay so we'll just do the binary search it's not a big deal i was just thinking whether i needed to do it but yeah okay same idea though so the si we the idea is going to be the same except for instead of here we go use the lookup instead right lookup of w of uh was it bisect left of s i so that basically we look at the first index that is to the right of si inclusive so this is going to be that right um and this is called index for now because i always call it index if index is greater than or equal to lookup of w then we return false that means that we've reached the end of the word so that's sad otherwise this the lookup of w of index is going to contain the index that's here so then we uh to the right of it so by consuming it we add it to one so we just do this and then i think that's good um and because this only has 50 characters we only do 50 binary search for each word should be okay and of course i am thinking of another syntax but uh it should be okay it's just minor change yeah so this is way faster as you can seem mostly for this particular case only because it gets to skip to the end uh let's give it a quick submit real quick hopefully this is a little bit better uh yeah um yeah i if i misread this i granted the constraints and then i misread this as having 50 words each word being or some i don't know what i miss right but i did think that there was only 50 words so i was like oh 50 words is not wrong 5000 is a problem because then it's just this times 5000 in the worst case which is too slow right um but yeah so what's the um what's the complexity here right for these things you know you have to be careful what n means and you have to be careful all these things let's define it i know that use n here but let's redefine it again too so that we can analyze it uh the length of s let's just call it uh o of s say um the length of words is going to be o of n yeah of w that's better and then the max length of word is equal to o of l right put it that way and then what is this complexity right so here i mean there's no going about it we're doing word by word so this is going to be o of w words and then oh here this is just linear time right and by linear i mean o of s why is that this is linear time linear space um because each character will have one entry and lookup which so it's all one space per character and of course we look at each character one so it's gonna be all one uh and each character takes over one time in general so that's gonna be of s time over a space but this function what happens right well for each character in word which is for l um we iterations and then we do a binary search on s so that's going to be log s in the worst case so this is going to be log s um so this is going to be o l log s is the complexity of this time um there's no space we just i mean over one space because we just do a linear thing and then now bringing this back up that mean because this is the w loop so total time will be o of w times l times log s for um plus s for time plus s being here and then for space this is just all of s i believe did i miss something maybe if i left something let me know um but yeah can't even get this one right on the first try really sloppy on the reading i think i was just tired and fast but um all right cool uh let me know what you think that's what i have for today stay good stay healthy to good mental health i'll see you later and take care bye
|
Number of Matching Subsequences
|
binary-search
|
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\]
**Output:** 3
**Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ".
**Example 2:**
**Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\]
**Output:** 2
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `1 <= words.length <= 5000`
* `1 <= words[i].length <= 50`
* `s` and `words[i]` consist of only lowercase English letters.
| null |
Array,Binary Search
|
Easy
|
786
|
1,696 |
hello fairweather friends it is the season christmas coming up on us let's not be naughty let's be good boys and girls and solve some algorithmical problems proceeding with this going to our favorite website favorite website favorite website and opening problem 1696 jump game 6 96 is here you are given zero indexed integer array nums and an integer k you are standing initially at index zero in one move you can jump at most k steps forward without going outside of the boundaries of the array so from i to i plus one up to i plus k your jump can be at least one and at most k steps forward you want to reach the last index of the array and -1 your score is the sum of all and -1 your score is the sum of all and -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 what you do is you start from the first element you need to reach the last element and every element which you step on your way you kind of pick up with you and add to this total sum so what's the maximum score this problem screams like screams really hard this problem screams dynamic programming there is an obvious recursive relationship the current element score i is equal to the best score of the k previous elements plus the current element right this solution would be quadratic here is how it would go you have maybe let's name this score your score at element 0 is element 0. and then you loop through the rest of the elements you start with integer min value which is the minimum possible value and we don't start from 0 let's say because if you notice in the constraints our elements can be negative from -10 to the fourth for negative from -10 to the fourth for negative from -10 to the fourth for every element i we go through the previous k elements j is our variable that goes through them and then we look at the score j plus our current element nums i if that is more than the best score we've found so far then we preserve that result and in the end we return the score of the last element n minus 1. very simple dynamic programming solution quadratic in time which is a bummer because the number of elements in our array is way too high for a quadratic solution to work this problem is really interesting because you can optimize a lot after you come up with the original dynamic programming idea by the way i wouldn't qualify this medium that's definitely a hard problem it would be medium if the simple dynamic programming solution was working and it's not one observation that's really important is you would step on every positive integer in this array you would choose to step on them there is no reason to jump over positive numbers or zeros for that matter they would always improve your score once you know every positive number is valuable and you should go through it you can actually improve on this solution and prune it break early when you reach a previous positive number because for sure you will come from there to your current number you wouldn't need to go further back you would have never skipped that positive number so if nums j is more than zero you can break you've already taken that j score and for sure going further back won't give you a better result this is okay but based on the test cases it's still quadratic in worst case if you have only negative numbers you can improve further if you realize that from all the k previous numbers from which you need to jump to your current number you need the maximum score and how do you keep the maximum score amongst k numbers and you always surface that maximum well the obvious candidate is a heap you can use keep in which you keep the previous k elements and every time you go through a new element you add their score to the hip keeping the maximum on top whenever you need to calculate the score for the current element instead of going through all the k elements in linear time you can in constant time take the top element preserving the invariant of this heap preserving its correct state would require log k time when you're bubbling up and down elements heap is good your total run time becomes now o n by log k however you can improve this even further you can use a monotonously decreasing q mono q to preserve only the elements you're really interested in the asymptotic runtime of this solution will be o of n here's how a solution like that looks and i'll explain why do we use a q when we are at the current element we need to jump back up to k elements now if there is a very big element somewhere in those k elements there is no point to go to the smaller elements before it we would never have to go further back than our biggest element eventually that element will be dropped out it will get out of reach because we'll continue progressing forward and so we only can keep the last k as it goes out we need the next biggest element and so the next biggest and so on and every time we reach a very big element we can get rid of all the smaller elements before that one because we would never have to go further back than our biggest element the idea is preserve the biggest element here and then the next largest and so on until you reach your current element if there is somewhere a dip some smaller element and then a larger than that smaller element we don't need the dip right the element with the small score we will never have to go back to it because we have a better one closer to our current index therefore the monotonously decreasing nature of this cube here is what the code looks like we'll keep the indices and we'll keep the scores we need to keep the indices to be able to calculate when we have proceeded so far that we can drop an element from our queue it's unreachable because our jump is at most k the indices are needed we also need the scores so that our q is ordered by scores in a monotonously decreasing manner we create the q with indices and we push index 0 we also record the score of index 0 which is num0 then on our current move we would look at the first or in other words oldest element in the queue and check if its index is smaller than i minus k that means it's too far back and we can get rid of it we'll remove it if that's the case next we'll calculate the score of our current index which is always with no exceptions the biggest element of our monotonously decreasing q plus our current element and the biggest element of that q obviously is the first element of that q then we go through the queue from our current element back to the first element and until the queue has elements on it and until the next element is smaller than our current score we'll get rid of them we'll remove everything so that when we append our current score it's still a monotonously decreasing queue keep removing the last element until we can insert our current score we'll do that at the end insert it and proceed with the next iteration of our loop once we iterate over all the elements we'll in the end return the score of our last element right here this problem has been asked by aqr capital management llc it's definitely a tricky and thought-provoking question worth and thought-provoking question worth and thought-provoking question worth exploring in depth quite an interesting solution there are some other ways to solve this problem like segment trees and others take a look at the discussion section think about it maybe you'll come up with something even more original and mind blowing alright that was jump game christmas edition i hope you had fun think about it think also about your jump game in life what's your next goal where do you want to jump to let me know and keep coding see ya 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
|
363 |
hey what's up guys this is sean here so today i want to talk about this 363 max um off rectangle no larger than k i think this is a great problem it's a hard one and yeah so you're given like a non-empty 2d matrix 2d non-empty 2d matrix 2d non-empty 2d matrix and an integer k and you need to find the max sum of a rectangle in the matrix such that its sum is no larger than k 2d matrix right so we have a few numbers here so that's a 2d matrix and we have a target k and basically among all those kind of rectangles right you need to find a rectangle whose sum is no larger the maximum sum right as close to 2k as possible but not greater than k i mean so there are some like the notes here you know the rectangle inside the matrix must have a area greater than zero actually i was like struggle i was confused about this part because i was thinking like maybe this one means you can only have like more than two columns or two rows but it turns out this thing doesn't really matter so i mean even this one element can still i mean be counted as a rectangle or yeah because i know i think the uh one of the example is like treating this one this is one number as like a valid not like a valid column or a row so anyway and the second one you know we'll talk about the second one actually the second one is more like a follow-up the second one is more like a follow-up the second one is more like a follow-up question no we'll talk about this one later so let's try to think about this problem right i mean it's kind of so the brutal force weighs what so it's simply just try all the possible rectangles and we get the sum of each rectangles and we compare with k right so what's kind of what's going to be the time complexity for that well so let's see we have a m times n uh matrix here so to loop through all the rectangles so it's going to be what so we have like uh m rows so to get all the combination of the rows we have i mean the range of the rows we have m square right and the same thing for the columns right so for from to loop throughout all the pairs of the columns we also need a like a n square that's basically the time complexity right i mean of course for the uh forget the sum of the forget some of the rectangles because we can easily use like a prism like a 2d prism right then we can simply do a o1 to calculate the sum of this rectangle so the total complexity for this brutal force is like m square times n square i mean it's definitely doable right but we're i think what's make this problem a hard one is that we have to find a better solutions a faster one than this one so the way we're doing it you know if we are still considering a like a 2d like a matrix so any strategy or any technique will be hard to apply on for example the dp or the uh the what the binary search right i think actually for this one the improvements we need to we will be using here is by using a binary search but in order to do that we need to somehow convert this 2d problem into a 1d problem right so basically you know the way we're converting it is we're max sum of rectangles no larger than k so we're basically we're going to convert this one to what to a maximum sum of array to a no larger than k so that's how we convert this what 2d problem into 1d but then how can we convert this problem right to a 1d problem basically you know we have to uh there are two ways we can either compress this 2d matrix horizontally or vertically okay so what does it mean it means that let's say we are we're compressing this 2d array uh 2d matrix up vertically so it means that we okay we loop through on the column pair first so let's say for this one we loop through uh the other column pairs right so it's going to be here let's say for example we have this these two columns we have a column one and we have column two okay and oh by the way so when i'm talking about this improvements here we still need to basically we still need to try all the possible uh matrixes because you know because we have an active values here so i mean even though we can have some early terminations like the uh as long as we get like us a sum equal to k we can simply return k that's the that's already termination but the worst case scenario is always we always need to traverse to try all the possible rectangles so back to our improvements here so assuming we have fixed the these two columns now what's left is in the not what's left is all the columns right starting from this column uh between these two columns right and assuming we have these two columns so what kind of options do we have this one we have this like uh this rectangles director and then we have these rectangles so base and then we have to try all the uh the rows right that we fix columns we try the rows but keep in mind right as you guys can see so no matter how we select the range of rows here since th this is the rectangle so as long as we include a row here we have to include everything all the numbers on this row okay so now you guys can find out right we can simply summarize basically squeeze this these four columns into one column basically for each of the rows here we summarize it so and here now this thing will become to what will become like a single row with a sum 1 sum 2 and sum 3. right so after we have this one now the problem comes down to what so with this given with this like the sum of the rows here what's gonna be the max sum right no larger than k because so if we include this one basically we are we're including this uh rectangles here if i try to look for s1 as two here where as if we are uh looking through uh this rectangles so on and so forth okay so now the question comes down to how can we efficiently do this right i mean if we have to do a search if we have to do a like search uh like the uh try all the possible pairs of the rows here of the of each item so this one will become to like what the uh m square so then the total complexity will not be improved at all so that's how we want to improve this part to what to a better time complexity so the way we're using it is like what let's say we have like uh this one i'm going to have like uh what's going to be the number 2 minus one three minus four six something like this so now we have like a one d array here now we need to find the uh the what the maximum sum of this array that's no larger than k so how can we do that right so the trick here is that we are we maintain like an increase in increasing presump so why is that because let's say you know this is kind of like a dps dp idea here let's say we have we are at we're at it like this uh we're at this d a dpi here so the dpi has a value of water now with a dpi here we know the presump of this ice number okay so basically with this prism and with this k here we have a target we know let's say we have like the dp the presump let's say the pre-sum of this let's say the pre-sum of this let's say the pre-sum of this ice number is 6 okay and the k is equal to two right so what does this one tells us telling us it tells us you know the current pre-sum it tells us you know the current pre-sum it tells us you know the current pre-sum is two is six and the k is two so what we're looking for we are looking for four so our target will be will need like 6 minus 2 which is 4. so it means that ideal ideally we need to find a prism whose prism equals to four because that will give us like the exactly the case we need if we cannot find it then we have to find it since we're looking for like the pre the range right the sum of this range of the sub array whose is smaller than k so it means that if we cannot find 4 we need to find a prism whose value is greater than four so it then it means that we need to find like a dp sorry not i think it's better to call this a pre-sum pre-sum pre-sum pre-sum here so it means that we need to pre-sum here so it means that we need to pre-sum here so it means that we need to find like a presump pre-sum like a presump pre-sum like a presump pre-sum value is equal or greater than four right because if we cannot find it that means that you know there's no sudbury that who's uh whose sum is smaller than k so we have to find one either equal to the target or greater than target then we know okay that's the value that's the uh that's the closest uh sum we can get for the uh to the current look to the current number here and since we'll be looking through this number from start to the end we have to somehow you know to be able to find these numbers right we a better idea is that we need to maintain like a increasing prism here right so and the way we're in because it's not only we have a increasing prism then we can apply a binary search on it so that we don't have to search do a o of m search on this number here we can simply do a binary search to find the location we need for us to get the uh the target presump we can use okay yeah i mean that's i know it's a little bit confusing but that's the uh that idea here you know i think another i was thinking about you know if we if i can use a monotonic cue to solve this problem um because i look at i saw this like minors because i think for i have seen similar problems you know with the minors numbers here they were using like the monotonic queue to find the uh the shortest the length the shortest sub array whose uh was or sub sequence where sub array whose like sum is no long no greater than k so seem like this one but uh it's different so this one is different because you know we uh because here we are fine we are looking for the sum the value the closest value not the length so which means that we have to keep all the previously values we cannot use like the monotonic queue to pop the to pop out the values we don't need because here we might need any value because any value can give us may give us the number that's that will be closer to this k here that's why we have to keep all the presump values and that's why we have to use a binary search plus the uh plus the maintaining like increasing prison okay cool i think i have explained enough so let me start coding here and i will explain more while i'm doing the coding here okay sure so and okay let me try to start from here we have a so the code will be a little bit long here just so just uh stay with me guys so i'll try to code as quickly as i can so now we need the presumps right like i said and even though we're doing like this improvement to fix the two columns right and we still need to cut squeeze the uh the columns into one so that we still need a presump and how to help us to do a 101 summarize right so basically i'm storing each rows pre-sum to the into this pre-sum array pre-sum to the into this pre-sum array pre-sum to the into this pre-sum array here so we have i in range of m here right for each row uh i'm going to have a row pre-sum uh i'm going to have a row pre-sum uh i'm going to have a row pre-sum and then it goes to this so we have a 4j right that's the column in range n here right so i mean for j equals to zero you know so here we have a special case dot append matrix right so the matrix i and j else house row pre sum equals to the i will just copy this one here plus right plus row 3 sum -1 okay i mean you could have used instead of using a array here you could have used like dictionary you know for the dictionary basically we initialize this with zero one with a key is goes to zero one and the value is zero that's how we uh fix this uh this minus one case you know but you know should i use this one no i'll just stick with my original approach here so by using like us another array here so that's how we populate this row here right and then in the end here we do a pre-sums dot append pre-sums dot append pre-sums dot append this row pre-sum okay this row pre-sum okay this row pre-sum okay so that's how we uh calculate this presump and then here we have calculate right three sum each row right so now it's the main logic part so we have answer equals to the minus system dot matrix size right since we're getting the maximum and now for like c2 in range up and now we're here we're looking through the loop odd column pairs right so c1 in the range c2 plus one so here keep in mind here you know since the basically c1 is this we have c1 and c2 that's why in the outer loop i have c2 because i'm looking through the c1 before c2 that's why i call this one c2 and the inner one c1 and here i'm doing a c2 plus one because even this one the column itself will i mean will still be considered as a valid matrix that's why i do a c2 plus one here not c2 because if i do c2 here so the single column will be skipped right so okay so now i have to uh compress right compress the rows okay between c1 and c2 so i'm going to have like current array here right equals to this one and for each row here so for each row we have an m right so for each row here uh i'm going to have like a row sum right so the row sum equals to what that's one that's what we what when we need these presumps here so we're going to have like three sums and uh the end is c2 right so the first one is the ice row and then the c2 here and then we remind us the what the presumps of i and c1 -1 of i and c1 -1 of i and c1 -1 no actually this is the part uh if we have like uh like a rate like the uh a dictionary with the minus one zero here that will help us to save a little bit code here because you know we have a presump one two five and six okay so if you want to get the pre-sum if you want to get the pre-sum if you want to get the pre-sum from this uh to here so how what so what's the total i mean from the beginning to here we need to have like two minus what two minus zero the zero actually there's like a zero here like a dummy zero here the one be before the first element that's what i that's what's this one is being used because i if the c e is equal to zero we have a minus one here so we should have a ideally we should have a zero for minus one index here but that's why i thought i was thinking okay if we use a dictionary with this one we can just uh simply you use this one line of code but since we don't have that it means that we have to take care of this c1 equals to one to zero case separately so which means that i'm going to have like an e-files that i'm going to have like an e-files that i'm going to have like an e-files here so we return this one if the c1 is greater than zero okay else here yeah that's how i handle that and then i have a row sum and then i'm going to append this thing to this sum right okay so now we have after this for loop right we have an array with the value for each row sum now i just need to get the answer equals to the maximum of answer dot i'm assuming we have a get max sum with a 1d array okay and then i can have like a uh early termination like i said if the answer is equal to k we simply return k right because the k is the best answer and there's no need to continue otherwise we return the answer okay so that's the main logic part now we need to implement this part right so we have a d this one here we have a we have array here so to implement this part like i said we need to uh we need to use uh the pre-assorted uh we need to use uh the pre-assorted uh we need to use uh the pre-assorted prism right threesome plus or what plus the uh the binary search okay so this is how we do it and like i said we need a random sum right we need the running sum to get the target so now for a number in the array right we first we update the rendering sum so now we have a running sum okay we have brand new sum here now we do uh do a what we uh with a running sum we need a target so the target is what is the running sum minus k that's the target where we need to search the target sum right now we have an index the index is dual we do a by binary search like bisect left and then we have a sorted presump right and then we do a target sum so you know for the binary search they're like some edge cases you need to be careful here actually i spent a few uh some times to try to fix these edge cases here you know so what's the edge case so the first thing first how this thing works okay so let's say we have like uh we have one three so keep in mind we are we're maintaining like this uh this assorted array so the way i'm maintaining sorted array here i'm in the end here of each photo period i'll do this bisect uh ins insert so in python there's like this bisect insert to maintain us as a sorted array here so we have sorry the presump is the random sum okay so that's how i maintain the sorted uh pre-sum list here so assuming we have pre-sum list here so assuming we have pre-sum list here so assuming we have this one here let's say we have one three five in the sorted presump here now let's say we have a target let's say the target is what let's say the target is four that's the happy path right so when the target is four when we do a by set by select left uh what index will get we'll get one two and three i'm sorry zero one two so the index will becomes to two and two is five and five is exactly the answer we need and by the way why we need a bisect left here this is because you know if we have like uh instead of four here instead of five here let's see we have four right and the four is the same as our target so in this case well which index we need we still need two right because the four is still the ones we need if we do a bisect right so if we have four here we'll get three here okay that will be the wrong answer okay so let's come back to this uh example zero one three five and when the target is equal to four uh we will get five so that's the uh the answer what we need right so basically the answer will become to what to this uh okay i'll write this one first the uh the running sum right miners write sorted pre sum dot index so this is the happy path right so that's how we uh get the uh the best answer so far right because we just raised the running sum and we might we subtract the uh the first presum who's whose value is equal or greater than the target then we got our current back sounds and then we maintain a max value among all of them right and of course we can also do our answer because to k we break okay so but there are like a bunch of edge cases here this is the hyper path you know okay so the next example is like this what if this target is not four what if the target is six so what does six means so six means if we do a by a binary search on this one it will give us instead of 2 it will give us 3 right so what the 3 means we cannot find basically all the numbers in this then this array is smaller than the target so it means that we cannot find a presump whose value is equal as either equal or greater than the target and it means that with the current running sum there's no way we can get a sub array whose sum is no it's no larger than k it so it means that we cannot always do this update we have to somehow find a way to check that right the way i'm the way it checks that you know so how do we check if there's like uh if there's no uh valid candidates right we simply do this right so if the uh the index is smaller than the length of the sorted pre-sum and then we only do this when pre-sum and then we only do this when pre-sum and then we only do this when the index is smaller than this because as you guys can see every time when we couldn't find it so the index will be on the far right most right which will be the same as the length so 3 is the same length of is the same as the length of the ray here that's why every time when the index is the same as the length of the ray here we will skip this part and yeah so that's that and so how will this work right yeah that's how that's we how we take care of the first edge case which is the uh the there's no valid uh candidates for us to uh to update the answer and the second edge case is how about the first one how about the first numbers so when the first numbers comes in how are we going to check these things here right and let's go over our logic one more time here let's say when this thing when this one is empty and the first number is two okay and then we have running sum equals to two here and the binary search since this one is empty we will get what we'll get 0 right the index will be 0 and is 0 smaller than 0 no and it will skip okay right and then it will insert this one to the to this uh sorted presump so which means we didn't compare we for we didn't compare the first number how can we do that how can we fix this issue because we still need to compare the first number right because let's say if the first number is 2 and if the k is equal to three two is smaller than three so it should go inside here i should go inside here to uh to update sensor you know two ways to i mean to fix this we can first we can simply uh do like another if statement to uh to handle when distorted pre sum is empty we can simply check if the first number is smaller than three if it is we simply update the answer right if not we just continue that's the first approach i think that's the like a easier approach right actually the more i thought about it another way is that you know we uh we need to like we initialize a zero inside here so how what how so how will this thing works you know this is a actually this is a tricky fix here so let's say at the beginning we have zero here let's say we have two and the k is equal to three right so the target so what's the target here so the target will become to two minus three will be minus one right and with minus one here right if we do a binary search we'll get zero right so we'll get zero so zero is smaller than one because we already have a zero inside there that's why we're gonna do like what the running sum is like it is two so two minus zero or equals to 2 right that's what that's how this zero will help us fix that so that's the two scenario right that's the valid case scenario and the second scenario case is like what is four let's say the first number is four is greater than three right so which means that the first number cannot be treated as a valid answer and how this thing will let's run our code one more time so with four here right so four minus three is equal to what equals to one so the target sum is one and now let's do a binary search one more time so with this zero in the sorted pre-sum pre-sum pre-sum list we search one the index is what so now the index will be one because one is greater than zero and one is equal than the length which is one that's why it will skip this part okay cool i mean that's how we fix a trick here it's a tricky fix to fix the first number scenario okay cool now finally let's try to run the code here all right run all right cool so this one accept it and submit all right okay one shot cool yeah i know it's a long implementations and they're like a few edge cases we need to be taken care of no taken care of so how about time what's the time complexity for now right so the time complexity is this so we have like the uh n square here right so we have a two for loop here that's going to be n square and here we have another four for the m so we have an m here and here actually you know what that let's this is just m uh m here and this is the more expensive part so for each of the n square we have this get max sum so here we have like uh the number of array here is m right so we have m here and for each amp we have like a binary search that's going to be the log m right yeah so basically you know now the time complexity becomes to the n square times m times log m yeah because here there's a log m binary select and here it's also a log m okay cool so now here's the follow-up basically you here's the follow-up basically you here's the follow-up basically you know if the numbers of rows is know you know if the numbers of rows is much larger than the number of columns what's going to happen but okay i think our problem our solution is exactly the answer for this since the row is much larger than the columns that's why we need to do a log m on the rows here and if the follow-up question is what if the follow-up question is what if the follow-up question is what if the row is small but the columns are large right that means which means that the n is way bigger than m so in this case we will reverse our solution here basically we will fix two rows here we'll fix two rows and we'll compress the column in between in that case our solution will become the time complexity will become to uh to m square times n times log n so basically whichever number is greater we'll put that number into this login here all right i think that's it for this problem uh thank you so much for watching this video guys stay tuned i'll be seeing you guys soon bye
|
Max Sum of Rectangle No Larger Than K
|
max-sum-of-rectangle-no-larger-than-k
|
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).
**Example 2:**
**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-100 <= matrix[i][j] <= 100`
* `-105 <= k <= 105`
**Follow up:** What if the number of rows is much larger than the number of columns?
| null |
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
|
Hard
| null |
399 |
Hello gas welcome to me YouTube channel so today we are going to talk about the problem of leadcoat so this is the problem evaluate division okay this is a medium level problem so let us see how to solve it so I will show a little screen here dear and Variable pairs equation okay this is our equation real number values okay one is arrival where equation values okay one is arrival where equation values okay one is arrival where equation IIT meaning of equations like if i is zero then what is it doing two strings days okay and value i and which This is the zero of the value, it is representing the value of the equation, so suppose this equation, if it is the mother of the value, then what is happening with these two that A / B = 2, it what is happening with these two that A / B = 2, it what is happening with these two that A / B = 2, it is okay, as if A / B questions are created. You will do is okay, as if A / B questions are created. You will do is okay, as if A / B questions are created. You will do like what is the value of A/B, you like what is the value of A/B, you like what is the value of A/B, you are right and the value of B/C is the same, are right and the value of B/C is the same, are right and the value of B/C is the same, if we look at the second one then what is Dino doing, B/C = 3 value, see this, my B is equal to you, the value remains. Like this is our input so I have to find out their value okay so how can we find out so like A/C now we have to how can we find out so like A/C now we have to how can we find out so like A/C now we have to find out the value of A/C now if we find out A/C find out the value of A/C now if we find out A/C find out the value of A/C now if we find out A/C then can we get from A to B You know, so I have walked on it, let me show you once on the white board so that it is a little easier, now see as we have this let me increase the size of it okay it is not responding let me reload okay mean by it is reloading let me show you so match increase its size yes so what are the values we have in front of us given A/B what are the values we have in front of us given A/B what are the values we have in front of us given A/B given hai kitna hai tu hai and B/C given hai kitna hai tu hai and B/C given hai kitna hai tu hai and B/C given hai kitna hai Now we have to find the values of these queries okay So we have to values of these queries okay So we have to values of these queries okay So we have to find A and C. How can we find A? We can do the point like this, first we will multiply A/B can do the point like this, first we will multiply A/B can do the point like this, first we will multiply A/B by B/C, this is by B/C, this is by B/C, this is known in A/B, you are and B/C is known. If there known in A/B, you are and B/C is known. If there known in A/B, you are and B/C is known. If there is three, then what is the answer, then it is 6. Okay, now if B/A is like this, we can write one by A by B. Okay, then what is the answer? Now see, here we have only 3 strings, so here we know this. If it is not there then one more condition is written here return OK then return here Find out the answer to all the queries People will have to apply DFS approach in the graph. Okay, so let us understand in detail how we will create the graph. Then let's move ahead, I have already made a diagram here for you, so now let me expand it to us, okay, I have written this equation on the side here, okay, so now how do we first do the equation? We will make a graph from this equation and we will make a craft from the values. Now there is no less of queries here too, okay, first we will make a graph from the equation, so we have A, so first we inserted it and then where to go like this, okay like this B. But okay, what else do we need? Now look here, what type of days are we doing in the graph, there will be a map, okay, first in the map, where are we going from the starting point, where are we going with the string. Okay, and how much is the value of getting there, okay, what is the value of dividing that by the equation, we will write that here. Okay, so now let's do how to do it, like, first of all, what we have is A and B. So first we put A in the map, okay, now where do we need to go from A to B, so we went from A to B, now what is B, it is a string, meaning, first we will denote where and point means, if we want to go, then we went to B, okay. And secondly, what will be contained in it? How much value is going from A to A by B? How much value is going from A to B? Okay, so this is done with the first equation, now but we also have to find out that let's go from A to B. We got to know you but now we have to find out B bye, now for us we will have to reverse it and write it in the graph because we have to check all the possibilities, otherwise even if we got to know A bye, it happened here just now. No B by A by B by A What can we write about 1/A/B? If we can No B by A by B by A What can we write about 1/A/B? If we can No B by A by B by A What can we write about 1/A/B? If we can write B by A then we will have to tell that in our graph. So, this is the equation of A/B. So, this is the equation of A/B. So, this is the equation of A/B. Now we have the starting note. From B, now for this we will have to create a separate one. Okay, now a separate one, now what will be the starting node for this? B, so B is the starting node. Now where did we go from B, we are going to A. Where is the going from B to A going to A? Okay and how much is it now from B to A? When we know you from A to B then how much will be the value from B to A? 1 / 2 will be correct 1 / how much will be the value from B to A? 1 / 2 will be correct 1 / how much will be the value from B to A? 1 / 2 will be correct 1 / 2 Now this equation has been completed in both ways. B has become A. We will make the graph of the second question like here, now what will be the starting point? What will be B? Okay, so now we will check whether any note has a starting point. Do we have only this much graph? You will ignore this one below also only this much. Now first we will check whether the starting point B is already present in the map. Now this is done. Yes, we have B and where do we have to go from B to C. If we want to go from B to C, then see if here. But we already know that if A had been there, if A had been written here by B to C, then we already had tax in the map, then it would have been nothing, it would not have been added, but now we have to go from B to C, so a A new note will be created from B to C like one in the map and what will be the key in it C and B to B divided by C what is the value of three which is given here ok now this is the situation what to do now c2b C you also have to do B. Now we will check what we have now. Okay, right now we don't have C, we don't have the present, so we will make a new note for C. Okay, we made a new note for C. Now from C, where will we go to B, then from C to B, and to C/B. What C to B, and to C/B. What C to B, and to C/B. What is the value, we know b2c, 3, then what will be C/B? is the value, we know b2c, 3, then what will be C/B? is the value, we know b2c, 3, then what will be C/B? 1/3, so it becomes one by three, so this is how 1/3, so it becomes one by three, so this is how 1/3, so it becomes one by three, so this is how our entire graph has been constructed. Okay, this is our entire graph constructed. Now from this graph, we can now I can also show you how to code this. I have shown the visualization, so now let's make the graph. Okay, so you have the Java code. I am going to write it in Java. Okay, so see this here. So the equation given means A/B whose value we know, we have A/B whose value we know, we have A/B whose value we know, we have given value of all the keys and we have to find out the queries. Okay, so let's start and first make the graph, then we will explain a little more and Then we will do a little more court, give them and donate, then support, I copied the code directly here, I will show it to you in Visual Studio Code because I like it more in comparison, this is okay, so I copied it from User Studio, here I did this I have created the method, okay, this is done, this also needs some return, otherwise I am returning it, okay, now here I have to call this function tomorrow, okay, so the function will ignore this, I will finally paste the sir code there. I am going to run it to show you, I am making it a little for him so that it becomes easier, so now here I have to pass these three things, so I will not go there, I will run all of mine, so for that, I have done it first. So I copy paste it here, this is the thing which is ours earlier, that is given, that is the thing, okay, you will ignore this part, I have done it just to give input, there is nothing else. Here I have pasted the name of the class, I have kept it as Test. Okay, so this whole thing is done and for visualization, now in the second time I am laying out the shell which I have made on the white board. Sorry, I have to keep it on the left side and on the right side. I have copied and laid out the example, it is ok and not in the intelligence, I am showing the white board so that it will be easier for you, this is how I opened the white board, from this I inserted the laptop screen, this is what I opened the intelligent on the right side, okay, so now I had copied that, I am here. But let me paste it first and I can do one think, okay the child is singing, so a little time was wasted but let's do it, now we have to create a graph, the graph, I told that the starting point will be in the first and In the second one where it is going like A/B it is going like A/B it is going like A/B is A B then the second one will be this, now again someone has given A by B so I will again put a little bit here, that is why I have made this map type of it. Which is always there in one map. What is unique, so here it is considered to be only one, so I have taken this map as A/B is so I have taken this map as A/B is so I have taken this map as A/B is given here, now in the next also I have given A by B, so I have given a simple one. And if I make a note and write 'B', it means that it has gone wrong, it is not the write 'B', it means that it has gone wrong, it is not the write 'B', it means that it has gone wrong, it is not the same thing, it means that if you write 'one by tu', then there will be same thing, it means that if you write 'one by tu', then there will be no answer for it, or next time if you write '1.2', then the no answer for it, or next time if you write '1.2', then the no answer for it, or next time if you write '1.2', then the answer will be '0.7', then you must have understood what my ghost is. That's why I kept the map and the starting point is also everyone's map because the starting point is unique for all. Okay, so let's make it in another monastery. Before that, I declare my map here, in which the first thing will be the starting point and the second. What will be the thing, ending, what is its ending, it will also be of a map type and along with the ending, what will be in it, its value will also be that from starting to starting divided by and so what is its value, so what type is it, we have double type. I will name it graph is ok and will create a method create graph ok I have done that we will definitely need equations correct we will definitely need values we will definitely need queries no right values we will definitely need queries no right what queries will we definitely need no right where then queries If we don't need any key, then we just have to pass what equation and values in it, we just have to pass what equation and values in it, we just have to pass what equation and values in it, correct equation and values, then what will it return to us, then I believe that this intelligence is a feature of any ID which we can utilize, why do we use it manually? Waste time by typing, so now we have the equations, the values are done, okay, we have the equations, the values are done, okay, we have the equations, the values are done, okay, so what do we have to do now, okay, so let us first loop over the equations, okay, before that we are not giving ours, I hope. You people must have got the answer, if not then it means I run a loop over the equations, I have to run them, so I start from index 01, how far do I have to go, if I have values in all the equations, then there are only values in all the equations, then there are only values in all the equations, then there are only two values in the equation, so this is You two values in the equation, so this is You two values in the equation, so this is You will run the loop from time to time. Okay, now we all know that I am doing it as follows. This starts, this and this happens. Okay, so now we have started in the first question, so we take the start, meaning this first one is taking this first. Induction So in the first one, now which one is the start one, its first element is its zero, whatever is the first element in the start i, it will be start, this is all string, okay, now I will declare more with the same type and how will I declare it? Let's start putting the equation. Okay, so we'll put the values in the graph. Graph dot. We have to put values in the graph. Okay, so if we start in the graph, then start. Now we guys, as if start is a repeat. Now we guys, so if it's like this we People, you just saw that from A to B, it became this, B to A, it became this, now from B, now we had this next, from B to C, so we will not make a new BC, okay, we will not make a new BC. We will check if B is already present, then we will do the same or point BC in it, then what will we do here, if it is not already present then add this only if we do not have that present, what if it is not present? Now, for the first time, when people run, if it is not already present, then it will add a pulse to the graph, such that what will happen in the start and value, okay, now for the first time, we have done this to take one Hashmat pulse per second, now I have only We have added the start point, okay, we have added the start point, what will we do now we will add more of it, okay, what now the graph dot, now that we have added the object, we can gate it also, so now let's start. Now what to put in it? Once we have gated it, then this object, all these objects have been gated. This map is in our capture. Okay, now what will we do in it? We will gate it. Okay, we will gate it now. What to put now, what comes in the second thing and comes to us, so we have put one more thing and along with it, OK, one more thing, here we will have to gate the value also because I have to put the value in the graph, so I have put the value here. Okay, now we have made it as before A and B, now in the graph there will be A which will be going to B. Okay, but now we will have to insert from B and A, so in the same way we will copy this from this. What will be the starting point this time what will be the starting point and okay and this will be our starting point and then we will gate and send it to the start like we will gate B to A, okay and what will be the value now. The opposite will happen, first one will be one by value because if you have A by B then what will happen to B by A is one by value. Okay, so this is our graph. This graph is completely ready. Now if I If I print it now and show you the graph, I will print it and show it to you. The graph is there tomorrow. I print it. This result is something else now. If you see the graph I have printed, then what will happen now? It's gone before A. What's in the first? Starting point is A. Okay, where is going to? What is the value going to 1/2 date it 0.5 properly A is going to C also A is going to 1/2 date it 0.5 properly A is going to C also A is going to 1/2 date it 0.5 properly A is going to C also C is going to C what will be the value 3 What is the starting point in the last where is C going to B What is the value going on, one by three zero point approach, you can apply whatever you want, okay, so I will apply DFS approach on this, so let's start now, so now on the actual solution, this has become the method of the graph I have created. Now I have graph A. Okay, so now I make it bigger. Okay, now I have graph A. Let me now let me do that a little bit where was date mom or copy it and put it here for you okay. If it will be easy to do, then you will get the graph. Okay, now I have to return this result first, so what will be in the result, the number of queries we have, if we want to value it, then I will have a double name, what will be the result, the number of queries will be the same. The more number of queries, the more will be its size value. Question So we have these queries, now what will be the first thing, what will be the start point, what will be the second thing and if the point is right, then let's take the start and from this onwards there will be other things too, that's it. Which value will be the first value? Okay, so first let's look at the basic condition, right now the top level condition which was earlier like if both of them are equal if start and are equal like this one how If both of them are equal, then we have a simple solution to this question, so first we will catch that one, if we do not get the answer from him, then we will read the next one, if star is equal and if start is equal, then it is okay, then what do we do now? Have to start equal and done ok so now can we directly return one like in A then we will create its value but X is not there song To do this, we cannot directly set the value of its result here. Result is equal to one. We cannot do this because here also we have to impose a condition, so let's see what that condition is. Now see that starting point in our graph. So it should be like ABC, we have starting point but Write it if it is from both, then write anything. If it is containing in the graph, then in the result we will set the value of i. One is fine, then directly minus one will come like this: Okay, we have to do DFS tomorrow. Okay, so now we have DFS, we have to do it tomorrow. Graph start. Now look, here I have to create a set of visited type as well, which note we have visited. If you do not want to visit again, then I will explain to you further what is its meaning, first you declare it here like every time it will be empty as for every query, then with every visit we will make it. We will go to write 'Visited', 'Visited' will make it. We will go to write 'Visited', 'Visited' will make it. We will go to write 'Visited', 'Visited' will come, 'Okay, what come, 'Okay, what come, 'Okay, what type will it be, it will be of string type, okay, this told our widgetized note that we have already visited A, so nothing will be different if we visit again, okay? So this is what we need, the graph should start and our need is now, let us create a method, okay, now we will declare it completely here, okay, so now this is our last thing which we have to make of DFS, okay now see. Now the first thing we will check is whether our start value is as it is here. Let us show you where it went. So first we will check whether it is present or not. If it is not present then that is the answer. Directly mines will be only one, okay, so first we will check whether the start is our present or not. If it is not present, then what is the use of taking it forward, when its answer is only -1, then it is its answer is only -1, then it is its answer is only -1, then it is not start. If it is present then you directly return -1. -1. -1. Okay, if it is not our present, okay, now the second thing is that the graph is straight like start A, you are in B, what is the value in you, so this is the direct one. Now we will check the value that if A to B. If we already have that address then we will directly write the value. Okay, so what do we have to do for that, where did it go? Either we will first check that it went in the first graph. Now It is known that brother has the start, so what will we do? We will find out the value of start. We went to the start, now we will find out the value of his and b. Now what else is there in the graph that came, meaning a2b like A and B is an example. So, A has started, now A has and I have BB. If BB is there, then we will directly return its value. Then there is something wrong in this, no, the graph of the graph which we have started with. What we have done is return the value of 'A', okay return the value of 'A', okay return the value of 'A', okay then return the value of 'Get', it will return the then return the value of 'Get', it will return the then return the value of 'Get', it will return the value because it is a map, ' value because it is a map, ' value because it is a map, ' Map' and 'I' will return the value of 'B', Map' and 'I' will return the value of 'B', Map' and 'I' will return the value of 'B', okay, our second condition is done. Earlier it was I don't like brackets, if it is a statement of only one line then now these two conditions are satisfied, now if both of these are not happening then okay then now we have the concept of widgetized one, okay so now What we will do is, let's take the first visited mother. Now in the visit, we have visited the start one. Now the start one has been visited. Okay, what do we have to do now? Now we have to see all the outcomes of that. Which one we have to do that Okay now like if I go back to this and take the first query like C Okay so first we go to A Okay now the first bar is no more and ours is right So if I make it small and Including intelligence right and no, now see what will be the scene here like first check the condition that the one who is starting, now see the second condition that the one who is started, what else is there and present is there, the second one is here, this is the story. But we don't do it, we have to put it in the right one, what is it right, here I have all the sets inside each one, here there is only one, here there are two sets, so we have to map the whole of it. Now we will traverse the entire map. Okay, so here we will do it by entering the map dot. Okay, now what is the type of map in it? What type of string and double type is this thing of ours? So here we have written string and double, what entry did we make and which entry will we take, we will take the entry set of the graph. Okay, so we have what value is given in the entry. If we have the value in the entry, then now. What we will do is that now we will check whether it is not already visited or not. Now it comes here less. If there was already a status here too, then we will not move it forward, then we will first check whether it is present in the visited list or not. The key that we have is not present in the state, okay, so here we take the mother of this, take the worm in a variable, let's do the get entry dot get and hit the entry dot get key okay Now I want to check whether it is already visited or not. If it is not visited then only we will apply DFS and will do this method again tomorrow. If it has already been visited then this We are again going into an infinite loop, it is okay that we went to A again, then went back to B, that circle will continue to rotate, so these conditions have been imposed for those who have visited, why should they consider it again? Okay, so what do we have now we have this method, in the previous method, B value A is considered as the starting point. Okay, so now we will find out its value. For this, we will do DFS tomorrow. DFS. Okay, now what's in this? -What graph will be DFS. Okay, now what's in this? -What graph will be DFS. Okay, now what's in this? -What graph will be ours? Now what will be the starting point? Now we will check from starting point B that by which type how we have reached C. Okay then what will be our starting point? B will be okay. What is our starting point? It will become B. What is the value of B? Basically, now our A will remain the same because the objective is to reach A and P. We have updated it, so we have to pass Western also. After updating, now we have this value A. Okay. And one more thing I would like to do here, if none of these conditions are satisfied then return -1 satisfied then return -1 satisfied then return -1 if the story is not found. Okay, now what happened here, now we have to check whether the current is minus one or not. If mines is not one then we will return actual value ok what is the start and point we have in actual now what was before was a/a and c now what was before was a/a and c now what was before was a/a and c ok what was before was a and c ok a and Sita but now we have visited okay now what we have is B and C is P and C have now reached here but now we have seen the first condition is that we have so this returns -1 so Not we have so this returns -1 so Not we have so this returns -1 so Not going to do the second condition, is B's ending point C? Is it completely correct here that B's ending point is C? So if B's ending point is C, then directly if B's ending point is C, then directly if B's ending point is C, then directly return this value 3. Okay, then directly return three values. If you do this, then it has returned three values, it is okay here, it has returned three values, it has returned here, now we have three value in current, okay, so what is the value of current now, it has become three and this If the current was not one then this condition was satisfied then the value of current became three and now this was our previous entry, we have to multiply its two values also, our previous entry, we have to multiply its two values also, our previous entry, we have to multiply its two values also, so it returned this six value here and where is the six value actually ours? But it has been stored in the result, so this was the complete explanation of DFS. This is my first video, so it is possible that you people may not have understood a little, but if I keep improving further, then the video may have become a little long, but I have explained it completely. I have tried it, if you liked it then please like, share and subscribe and I will try my best to improve it and yes, sorry, I will just paste this and show you that it is working fine, it is just a fluke, so how is it? The question is here I have to do my result, I have to return the result and here I have already printed it, I print it is 60.5, this is the same old answer, 60.5, this is the same old answer, 60.5, this is the same old answer, it is matching, so now we have to What will have to be done, we will directly copy and paste these 3 methods that we have created, just here I have made it private, you will make it public again, okay, so let's open it like this, go there, I am replacing it. From that and I had declared this as private, I am making it public, OK, I made it public, I ran it, OK, let's accept, how did everything go, I submit, accepted, so this is our code is running, I am in the question, I am in the video in video. I will also give its link in the description, from there you can go to Getup and watch this video and if you liked it, please like the channel and subscribe. Yes, I will try to improve the video a bit for you, till next time thank you. Bye bye please like share and subscribe
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
945 |
hey what's up guys uh this is sean here so today uh let's take a look at number uh lead code number 945 minimum increment to make already unique right so the description is pretty short basically you're given like array of integers and so a move means that you need to basically choose any number and increase increment it by one and your goal is to make the uh the array unique basically each number is unique and you we need to find the least number of move moves to make uh every value in the array unique right so we have example some examples here you know for example one here you know we have input one two right i mean so the output the move is one basically because we only need to change this three uh two to three so that i know we have one two three right and now we have example two here right so let me open the drawing tool here so here we have uh we have this array here you know the output is six because we need uh we need six moves right because we have two ones right so which means two ones you know one of course you know if there's like any duplicate numbers we have to increase right uh sum of uh the other some of the numbers there so we need to increase this one to two and then we have two twos right so which means that you know since we have two here you know from two and two you know we also need to increase this two to three right and this one increases to four right and then we have seven right that's why you know the total increment is what is one plus uh what did that mean a different number here oh we also have a three here okay so we have a three here so with three here you know we since we already have two three four which means that we need to change this three to five and then we have seven right so we have one two and two right that's why the total is six right and the constraint is like uh forty thousand and the number range is also 40 000 right i mean you know burst things we have already like actually find like the first approach which means that you know the first approach is that you know we can simply just sort this array right we store it from the smallest to the biggest you know and every time when we see uh a card numbers you know we compare with the uh with the previously with the biggest number previously set up right which means that you know starting from the second one right and then we have a pre you know this pre means that actually it's the is the biggest number uh we have seen so far right so at the beginning the pre equals to one right and now we have one here you know since the current one is either equal smaller than the previous one which means that we need to increase it right so but how many uh moves we need to make basically we just need to use the previous one right minus current number and plus one that's going to be the total number of inquiries we need and then every time when we uh finish processing a number here we also are going to need to update the pre right to the what to the current biggest number you know it's right that's why you know now we have one here you know the priest also equal to one that's why we need to change this one to two right and after this one you know the pre we become to two and then we have an another two here so which means we need all we also need to change this one to three because two is also smaller or equal to two right that's why we're going to change this one to three right now we see another two you know since two is also smaller than the previous one you know we hope we're gonna change that one to four right and so on so forth and then when we add seven here you know since seven is bigger is greater than the previous one than the previous number which is five that's why we don't need to do anything for the last number right so yeah so that's basically the first approach which means we simply just need to sort the array here and then we also maintain like a previously previous max number right and yeah let's try to code that and all right so we do a dot sort okay oh and notice that you know the length can be zero right which means that you know empty array is also like a valid scenario so that we can simply just uh check that separately you know when this one is not there's nothing we simply return zero right and then we start uh we have a pre is going to be uh a starting with a zero right and then we have n equals the length of a right and then we have the answer equal to zero and like i said we start from the second one right which means it's going to be the one to n right so we have current is going to be the ai right and so if the current one is equal or smaller than the previous one right we uh we do what we need to increase basically we need to increase the current number right by some moves right but how many of those how many increase we need to make here so we need to make the previous one like i said minus current plus one right that's the moves we need to make right if the current one is not greater than the previous one otherwise we don't need to do anything right we can simply just update that previous one right just like how we handle the seven right so after this one right i mean if we still if we're still trying to use the current to update the previous one you know we have to we also need to update the current one because uh the current one also needs to be updated right so the current one gonna become what gonna become the previous one plus one right because you know the current one means that you know since the current one is smaller than the previous one it means that we have to use the previous one as a base to calculate the current one and then we also accumulate the moves we need to do to make this current one a unique number cool and yeah so that's it right i mean we simply just return the uh the answer right in the end because you know so i mean there is like a little bit of greedy idea here you know basically you know we so the way we're trying to use the least number of movements is that you know we only increment it in a way that it can a way that you know we don't need to increase mandate i mean to a very big numbers you know as long as every number is different you know we're fine right that's why you know we're trying to increment it like from the smallest to the biggest so that you know we're not wasting any of the moves here right and yeah so that's it so if i run the code so accept it right and then submit yeah cool so works right how about time complexity right i mean obviously we have a sort here so if the length of a is n so the time complexity is going to be a login right and the space is i would say space is one right so the time complex is unlocked and space is one because we're not using any of the we only use this like pre variable right um yeah so that's the first approach and so can we do a little bit better than log in time complexity here you know since we haven't used the uh the second constraint here which is the range of the numbers you know if we use that one you know basically we can simply loop through all the possible numbers from zero to the end right so which means that you know and so now here you know we do it we also do it from this from a incrementing order here you know so if we know the range right i mean we can do the similar thing and the only thing left is that we just need to know uh how many what's the frequency uh basically what's the count for each number because you know let's say we have uh four ones and then three two and then a fourth through and four three and so on so forth right so let's say we have this kind of uh numbers it doesn't really matter like the sequence because we're not doing the sortings because we use the range to try each of the number and at each of the number you know if we see like uh a count right because you know for each of the count here let's say we have 5 2 here we know for the duplicate numbers here you know we have to increment the remaining ones in a way in an incremental way so that you know at least for this group of numbers they're going to be a distinct number so which means that what does it mean it means that if all the numbers are two right so for the fir for the second one starting from second one this one will become to three right and this one becomes four and this one becomes five the last one is six right that's the so this is the numbers we're going to change to and how about the moves so we have one two three and four right so that's going to be the moves we need to make right uh on the uh to at least to make the current group unique right but you know this is this assuming you know we're not changing the base which means that the base is still two but in for the scenario that you know if with the previous number is also greater than two you know maybe two is not a good number it's not a good example here let's say this one maybe uh maybe we have 8 right of eight so this one will be changed accordingly but you know the moves are the same right so we're still but so this one two three four is based on the baseline we're not changing the base which means the 8 is fine but you know what if the previous one you know the previous biggest number is 10 because which means that we already have some other duplicate numbers be before eight and after that the process you know the biggest number we have is ten which means that you know at the card numbers here you know instead of eight we have to start with what start from with eleven right that's going to be the base for the current one instead of eight so what does it mean it means that you know on top of this one two three four we also need to add another uh some other moves so what are the moves basically how many that's the moves are going to be the number the fruit the number of the current the count for the card number which is five times what times the difference which is the uh the eleven minus eight that's the uh the second part of the movements right and yeah so now we have a formula here and for this one that's the uh basically that's a summary that's the sum from one two to four right so what it is four is a count this is a count minus one right because we have column is five and the biggest number we're trying we're having here is four right so this one is very everyone knows the formula n times n plus one divided by two right yep so that's the basic the two parts of the movements and for the second solution right and yeah so i'm going to do this coding real quick here you know okay cool so um we need to do count right so the count of using counter and so we have answer equals to zero right and what else and we have a pre right pre is going to be uh starting from zero maybe actually the price should be starting from minus one you know because we'll be comparing the current one even because the number is in the big smallest one could be zero you know so that's why we start from minus one here and so the so to loop through the range starting from zero to we can simply do a forty thousand but you know that would be waste of the loop here we can simply do a what we can simply do a max number of a that's gonna be the upper bound of our loop here right we can simply do a phone number in the range of max plus one right and we have current uh we have count so the count will be the count of the current number right and then we check if the count is greater than zero that's when we need to do uh some work otherwise you know if the number doesn't exist we simply skip right and we just uh i'll define like a total moves right for the current a group of numbers right to make the current group of numbers unique okay at the beginning it's going to be zero and the max move right so the max moves what like i said is count minus one right so like i said if we have five eight you know so we need to change so for this one we turn it to one we the move is one the second one we also we need to make two moves and three and four so that's why the max move is what is count minus one which is four right because i'm going to use this one to calculate those total moves so the first part is like i said it's n times is this is the sum rise the total for this part right it's going to be the max move times max move plus 1 and then divided by 2 right and okay so and then we all we are i'm going also need to use this max number because the number plus the max move right so i need to use this max number to get uh to update this is pre because i basically know every for every loop here you know i need to know what was the uh the max number we have seen so far right so that's why you know the max number at the beginning you know just looking at this group of numbers you know the max number is what is the number eight plus the maximum which is four is 12 which means the max number is 12. but this is only considering the this group of number itself right but we also need to consider the base right check the base of the current card number right which means you know we need to compare if the number is either equal or smaller than the pre which means that you know if the pre like i said if the price is equal to 10 right so this is when we need to update both of those total moves and the max number right so first the total moves will be increased by the count times the pre minus uh current number plus one right which means we have five you know five times what the price ten minus current number is 8 plus 1 right that's why we have this formula here and then similarly for the max numbers you know it's going to be uh increased by the pre minus 9 plus 1 because you know the max number in this case instead of 12 it will becomes 2 to what to 15. just because of the previous one is greater than the current number now we can simply we can update the answer right by the total moves and then we also update the pre with the max number right yep so that's it right so now i simply just need to return the answer here update right update the base you know yeah so run the code accept it and oh yeah uh this a corner case here cool yep so this one also works right so i mean as you guys can see here you know so for this second for the second approach here you know the time complexity is simply o of n right because we are not doing the sorting here we simply do a count and the max you know that's a two of n and then the four for loop is also o of n right so in total the time complexity is o of n but space in this case is what is also often because we need this count to store the frequency of region of for each number cool yeah i think that's it you know for this problem and yeah thank you for watching this video guys stay tuned see you guys soon bye
|
Minimum Increment to Make Array Unique
|
snakes-and-ladders
|
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`.
Return _the minimum number of moves to make every value in_ `nums` _**unique**_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Example 1:**
**Input:** nums = \[1,2,2\]
**Output:** 1
**Explanation:** After 1 move, the array could be \[1, 2, 3\].
**Example 2:**
**Input:** nums = \[3,2,1,2,1,7\]
**Output:** 6
**Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 105`
| null |
Array,Breadth-First Search,Matrix
|
Medium
| null |
68 |
hello guys let's discuss a heart problem from google it's known as text justification so we are given an array of string words and the width max width format text such that each line has exactly max width characters and is fully left and right justified so we are given a list of the words for example this is an example of a text justification and we are given some kind of a max width over here we need to format the sentence such that it is left and right justified now what do we mean by this we are going to read this so you should pack your words in a greedy approach that is pack as many words as you can in each line so pad extra spaces when necessary so that each line has exactly max width characters so we need to pad some we need to pack as many words as we can in each line such that we do not exceed the max width and then we for the extra spaces we are going to pad the extra spaces where we cannot add more words okay and we still have some spaces left so each line is 16 characters long okay so we cannot so for example you can see over here that we have this is n and we cannot add the word example because we need to have at least one space between each word right and with that thing if we try to add an example over here then this will exceed the max width of 16. extra spaces between the words should be distributed as evenly as possible if the number of the spaces on the line does not divide evenly between the words the empty slots on the left will assign more spaces than the slots on the right for example you have the second sentence and it has to evenly divide between the empty spaces has to be evenly divided and when they cannot be evenly divided over here then the extra space will go on the left side rather than on the right side right so as you can see that a total number of the spaces for this particular sentence is three so two are here and one is over here right so the extra space was we cannot evenly divide this sentence in terms of the spaces then the extra space goes on this side for the last line of the text it should be left justified and no extra spaces is inserted between the words so it has to be left justified you can see that the word justification is on the left side and then we have the space so note that a word is defined as a character sequence consisting of non-space characters only non-space characters only non-space characters only each word's length is guaranteed to be greater than zero and not exceed the max width right the input array words contains at least one word so now let's try to implement this problem first of all what we can do is that we are going to traverse this words array right so we need to get each word and then we can count the number of the characters on each word and we can store it somewhere right and let's say that we have this sentence in this sentence we can store each of these sentences into a particular list right so what we can do a some kind of a calculation in order to make this word where we have four gaps between these two so this one is evenly justified we have four gaps over here and four gaps over here right this one we have three um we have two gaps over here and one gap over here okay so this is not evenly justified right so in order to make these cases what would be the best approach to do this is that let's keep a list as our container of one particular uh calculation okay so we let's say if i wanted to make the first sentence this is n and we can see that why do we have this why don't we include example in the first sentence the reason behind this is that if you calculate the numbers this is 4 p h i s so one two three four five six seven eight so there are eight of these then we have if we go here we have some spaces as well in between all of these so two spaces will be there or at least three spaces so one space over here and here so 8 plus 3 is now 11 and now it goes 12 13 14 15 16 17 and 18 right so now it's exceeding the 16 that's why we cannot add example in the first sentence right so now i think it's clear so let's try to first so as our first step in the very first step we are going to traverse through uh the words array right so this will be forward or w inwards right okay and then we can have a list over here we can add this sentence and then we can do the calculations for this particular sentence right and we can have another list which will be our resulting list okay in which we have all three of these right we can also say a variable called n we can call it as 0 because n will be the number of the characters let's say okay so now what we're going to do is that we are going to append to the list every word right so first we append this word and then we append the other words and we also calculate the value of the n so the value of the n would be n plus is equals to length of the word right so for the first word one two three four so n is four and then on in the list we have appended up this particular word right now we have to have some conditions over here okay so when are we going to stop appending the elements into the list right and so first we add these three and there has to be a criteria now that when we cannot add any more characters okay so we are going to write this thing in our while loop and we will see that if the length now the fourth word comes and this what is example okay so this is a new word right so we have appended until n over here um to the list and we have also calculated the total length so by this point we have eight as our total length in our variable n right so now we say the fourth word which is an example if this words length plus the number of the characters that we have counted until now okay because now we are trying to add up these two and we will see that if this exceeds the value 16 okay but what we have not counted over here is the gaps okay and if i include this particular word to these three i will have three gaps okay so this will one over here one here and one if the example is added to this sentence then here as well okay so that would be equivalent to basically uh the size of the list okay so by this time the list has this is an n words so we will we can say length of the list and if the sum of these three if that is greater than the max width then we can do some calculations so the example keyword will not be included over here so we need to justify this sentence up till over here okay and we need to convert this sentence into this form with justified spaces right so for that we need to calculate the gaps so how many gaps that we can have so this would be basically the length of the list minus one right this would be length of the list minus one because we have three for three words that we have it in the list we will have two gaps one here another one is over here okay but that's not enough for us because we need to justify these three words to the length of max width right so this means that for the two gaps that we have calculated we need to evenly divide them so in order to evenly divide them what we could do is that we will take out the difference between the max width minus the total number of the characters which are already used right so how many spaces are left so eight characters which is this is an n which is a total number of the characters which we have calculated in our variable n if we subtract this from the max width we have the remaining width that we can fill up with the gaps right and if we divide this difference by the gaps we will have a quotient and a remainder right so if it can be totally completely divided and the remainder is 0 this means it is evenly divided and as it is said in the question over here that extra spaces between the words should be distributed evenly as possible if the number of the spaces on the line does not divide evenly between the words the empty slots on the left will be assigned more spaces than the slots on the right so we'll come to that point but what we can do you could also just divide the element and calculate the remainder by using the mod operator but there is also a very handy function in python which is known as div mod okay you can say comma gaps and if it's going to return two values and that will be quotient and the remainder all right so now we have quotient and remainder and in this case for our first case let's say this would be the value so we have 8 characters over here and 16 minus 8 is now 8 and 8 divided by because we have two gaps between these three words so 8 divided by 2 is 4. so we have 4 the value of the quotient is 4 and the remainder is 0 okay so what we can do now is that we can write a for loop and we can say for i in range of gaps so for each particular gap that we have we need to add four we need to replace this cap with four more and if there is a remainder we will also add a remainder right because if it cannot be evenly divided then we are going to add that extra space to the left side as in the case of here right in the second sentence let's do this like first we can say list i okay so we have in our list three words this is an n right and we can add to each particular word so list i is basically now pointing i is initially zero so it's now pointing to the keyword this right so at this particular point we can say list i plus the gap into quotient right so we have at least one gap and multiply by the quotient which is 4 okay so and i think i'm missing one thing over here we will have a divide by zero error if you only have let's say one element in the list then length of the list minus one would be zero so we can have a divide by zero error over here so in order to avoid that we can say or one okay so whether this one or otherwise we'll take the value 1 okay so now it's it looks good so we were calculating list i plus equals to the spaces the space multiplied by the quotient so we have for the even case we have multiplied by the 4 right and the next time it will come again it will add another 4 after the word is where i is equals to 1 but we still have our case of the non-even case okay the odd case right non-even case okay the odd case right non-even case okay the odd case right when it cannot be evenly divided in that case what we can do is that we can have an extra space to be added on the left side so we can just say if i is less than the remainder else it will be the null space right so when we say i is less than the remainder we will be on the left side over here okay all right so now we come out of it and we can say we still need to add this particular modification so we now have adjusted our list okay so we have adjusted our list after this for loop so we have something like this and now we need to add it to our resulting list so what we can do is now you can say result.append then we can you can say result.append then we can you can say result.append then we can simply join this list then we can say n and the list we can initialize it to the initial value again to the null values so we can calculate for the next one right so we can calculate the next ones i think we still have one more thing over here it says that for the last line of the text it should be left justified and no extra space is inserted between the words right the last line let's say justification i think the total number of the characters with justification is 14 so 14 is less than 16 so it's not going to go over here and then it's going to append it already into this particular list but it will not be added um into our resulting list yet so we will be out of this because there are no more words over here in the end we are going to append this to our resulting list so we are going to add it to our resulting list here it's also saying that it has to be left justified so what we can do here is that we can have the space that has to be joined so what we can do over here is that we can we have a space and then we have a join we join the list and then um we can make it l justified left justified so we have a ljust function in python and we can give the parameter of max width over here and we can say that this would only be the case when we have something over here if there are elements in the list right because we have something in the list right which is less than the max width so in that case we can do this modification because we have something left in the list otherwise we can just return an empty list or add an empty list to the to our resulting list so i think that's it let's try to run this code so it seems to be accepted i will try to submit this code now great so it works now thank you very much for watching
|
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
|
733 |
welcome ladies and gentlemen boys and girls today i'm going to solve another coolest question this is one of the coolest question which is floodplain basically what's the third place now the first question arise in your mind okay so let me explain what it's flat with so basically flood fill is also called seed field okay this is an algorithm which helps to determine the connected area in a given node okay like let's say in the matching in a multi-dimensional array with in a multi-dimensional array with in a multi-dimensional array with matching attributes all right guys so this is just kind of a basic definition let us now talk about actual question how we can understand this thing very beautifully but for the question saying an image is represented by m into n gates integer grade image where image i j represent the pixel values okay so these boxes you see the square boxes this is represent the pixels okay of an image file so you are also given three integers source row source column and new color you should fill you should perform a third fill on the image starting from image source okay so and we have to go before dash direction so it means like we have to check okay let me just tell you a little bit more clearly okay let's say somebody told us like okay dude you have to go on this point okay and you have to change the color of the same connecting nodes to this area let's just say this is one he told me somebody told me to put or go on to the one and you know the uh connected nodes to the one you have to change its color okay so i'm on the one so by the nearby one i will change all the colors so four dimension so this is four dimension okay four direction okay so four direction means like we are going to top this is top left down right we are going to left down right okay we have to check so in this one we see that only top and left was down and right out something else so we will we are not able to change the color you know the box on which we are uh on that is will be change by different because this is the main box which in which they represent us okay but actually in our code we will not change the color we will just simply change their values okay so let me just give you a more clear explanation all right so i hope like you understand like when we are uh like in the early childhood we used to uh we used to play with paint microsoft windows paint okay so what we did we just have we have a basket with us you know filling the basket with the colors so like we drew some pixels and you know when we drove the basket over there all the connected uh connected area will be the same color okay similar things is going over here so let me just show it to you with microsoft windows paint okay so here we are so we are on now microsoft windows pen okay so this is a kind of a simple similar example i draw it okay so now so we have something like uh let me just erase this one let me go with a bigger pencil okay so now let's say we have something like source row and source column okay so somebody told me like okay dude what you have to do you have to go on to the source row uh let's say i will go into the source row number two and my source column will be number one okay so it means like i have to go something over here you know if you look at over here you know it's visible uh let me just make it with a color okay this is like somebody told me like i have to go over here okay so i come over here so this is the same thing these are the same thing okay now what i will do i will check is top left uh top left down right both of them so i will check where the four is coming with similar like you know i come on this one i will take a similar item over here so the similar one is four okay now i go over here because i find the only one because there's all other different one the left down and right are the different one so i just go on the top now i'm on the top now i will check is top left down and right so top left down and right okay so once i check his top i say like yeah i will fill this one it's left i'm not able to film it's down it's already filled and it's right yeah it's similar so i will fill this one as well now what i will do i can go either on this one or i can go either on this one in my choice so let's say i go on this one i will again check his top yes top is go to fill i will fill it because it's not playing is similar to one as well so i will check is now left i will say left is already different down is not similar right is no similar so this is the fill okay now what i will do now i go over here and i will again check its top is not available left is available i will fill it down is not available like it's already filled with is not available right is also we can do anything is already filled okay so that's how it's printed so that's how like we used to paint using like earlier like you know we just grow up bigger boxes in pixels than we just finished so this is the same fuller fill is doing over here okay but let's say now somebody told you like no man you have to uh go on let's say so source column two and uh row columbia as well okay source column two and two okay so what will happen so now i will reach over here on my two okay so what i will do i will just uh let me just do a good color okay so now i will just fill my two over here in this basket i just fill it i just fill my two what will happen now i will fill my two over here as well you know because like these two are similar so i will go on this four direction i have to go on four direction i don't feel so i just similar do the same thing over here okay now you say like this two is there f rather remember this two is not connected to th this one that's what the flood fill is flood wheel is only those areas are connected there are no currents so we will not never touch them okay now you see that like okay now you have to go on this one uh final one so let's say somebody told me like i have to point three so i have to go source column source row three and so forth so what are it means like i will come over here so i will just fill it with this one okay i come over here okay similarly i fill this one not able to this one okay and similar we are not able to fill this one because three is nothing if three is over here if there is over there then i will definitely fit this one okay so i hope question is clear with the question institution like how we have to fill it so like in the actual code we will not fill this one i'm just showing you the representation like in the actual code we will just change its number so let's say instead of green i will just make like previously it is four i will just make it one so that's how we will go in the actual quotient okay so i have so this thing is clear all right so now ladies and gentlemen let's just start moving to our question and let's just look what is saying all right so now we are on the question so now you will say like how we will uh implement our code so don't worry i'll just tell you now first thing is first thing i have to do is i will make one if condition my what my expectation is there my estimation will say if my image which one i am my source row and source column okay they are already similar to my new color let's say i am on a one and now i will change their values to one as well so it's similar to that one so then i don't have to uh change their color again because they already are green okay so what i will do i will just simply print uh print image similarly as people like i don't have to record every time again over here because they are similar because this is the new number generator is random number so it can be anything let's say if it comes similar then i will simply put the same thing over here okay i hope that this thing is clear okay so new color we uh if that's the condition that i will simply return my image all right guys okay now what i will do i will make a call to my function so i'm using dfs so i'll just let's just i will just call it dfs okay so i will just make a dsm image okay what is i have to make a call to a source row and source column and what else i have to make a call to new color okay new color and what else i will make one uh another as well which i call it let's say old color i can call it older why old color because you know like uh let's say i am pointing on one so i will check if the left one is one as well if with the same then only i will change this color otherwise i will not change that for that one i will use old color okay i will not use old typo i will say image source row in the when calling the function then i will uh change its name okay now finally i will just write in my image okay after completing the uh complete function then i will completed my image public void what dfs okay now just let me just initialize them into image and let's say called row for simplicity and let's call it column for simplicity again and let's just call it new color okay because it will change our color oh let me just make it a little bit more big so that you can see okay click new color and int old color okay now what i will do i will just uh change my image row column to new color because you know like if they were similar we already deal with upside now oh if we come over here it means that the new number will be a new number like that random german generating number is a new number so we just put that we just change the value to the new number okay so whatever will be it will be new color all right guys okay now what i'll do i will make uh using my dms function i will go in on my 2d arrays top left down and right okay so i will just do it like this so what i will do i will simply say image okay now what i will do you have to go row plus one means i'm going stop i'm going in stop no pressure column what else new color what else old color all right similarly i will go for his uh what else uh left down and right so let me just uh come in here stop okay stop direction okay uh okay so now in this one i will deal with this left direction i will deal with the left direction over here okay and over here uh i sit down very simply what make the code as simple as possible you know what i mean oh man on the stick okay and uh finally right over here all right guys so now what i will do my final thing is to change their value so row plus it will move from row because we're going left so when we are going left it means we are decreasing our column okay now we are going down so down means we are decreasing our row okay because you know we are going to hear our rho is decreasing and now we are going uh right so it means we are increasing our column okay one last thing i have to handle one base condition in here so for the base condition is let's say if my uh color go out of the box out of the grid so for that i have to handle this one over here as well so i will say if my row is greater than equals to uh image dot length or my column is l greater than equals to image zero total length oh what else can my row can be my row has to be uh less than if my row is less than zero then i will do something if my row is less than zero or my column is less than zero okay and the final condition will be my image row and column my image uh let me just make it a little bit more clear my image row column note equals two not equals to one old color you know i say like i let's say i'm on one and my side one is three so i don't have to change this color you know i just have to change the similar one within matching to my uh above left or side one okay so i hope this thing is clear okay then i if these conditions are uh if we on this condition i will simply return it because like we don't have so we don't have to deal with this condition okay so guys i hope this code is crystic literally like how we are doing it let me just run this code so you will definitely want to understand easily so let me just run it oh it's taking a little time okay we just get okay i think we just write something that's uh probably line seven so in line seven oh i'll write end over here but let me just run it now i hope this thing is this thing will work correctly and here we go guys so it's accepting very well okay so let me just submit here let's see all the test cases are passing on so you see uh just have a look this one on this thing okay so he is going hundred percent okay so now you will ask like what the time compensation we are dealing with over here the time complexity we are dealing is big o of n and the space compressor is because n as well so why the time will be over here because we are just going with n pixels okay n times okay so it does no matter like whether they are similar or not because we have to check now we have to just check like if they are similar or no or they are going n times and the space complexity is because people we are pulling to our stack using our dfl that's fine okay so i hope this code is very clearly like how we are doing it and ladies and gentlemen if you still have any doubt do let me know in the comment section i will definitely gonna list you and thank you very much for watching this video i will see you in the next one till then take care bye i love you guys believe me i love you take care bye
|
Flood Fill
|
flood-fill
|
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n`
|
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
|
Array,Depth-First Search,Breadth-First Search,Matrix
|
Easy
|
463
|
3 |
hello Dean hey Granada is a toleration lake called Asante longest a substring with other repeating characters theologically got the food try ginger root search on the Papa huntin full character dad's truck nah man you know the focaccia you know two pointers like a sliding window Gahanna oh no Aayla your job to go to Shaolin Sutra neva to around a girl children I certainly don't I teach English should have you go dance and the tale of the trunk indeed a sliding window lynnium a otro for the character Doha whoo-hoo otro for the character Doha whoo-hoo otro for the character Doha whoo-hoo agent until I do some illegal carry with her father with a sliding window Lima lie Johannes a consent agenda to go Donatello charm to Aruba more attention the diva character can sliding-window the diva character can sliding-window the diva character can sliding-window Dona moça character your tofu doha that Dante Nevada tranio physicians and Anisha hollow knock is a summation started enjoy casual ChaCha jojoba confidence unfortunate future omen Jahoda Lagos in de Mayo Tom for character that's the trap nature no Cortana children starter hydrogen I toss in termina Kohana tronco la well who said suit on koh trong man you got a pseudo she way either trying a drop had no mental leads usual dante the input of shi jian of our orientation i want attention pienso en Tony Zucco the character de Paoli now subtle Idaho tearaway II saw Toby - aha peel away tearaway II saw Toby - aha peel away tearaway II saw Toby - aha peel away II saw Darcy - oh ho peel away ye not a II saw Darcy - oh ho peel away ye not a II saw Darcy - oh ho peel away ye not a solo - oh ho - actually we're are not solo - oh ho - actually we're are not solo - oh ho - actually we're are not Taunton the took a character to kill me by showing guy character du Chien opportunites it will fan out wrong for Dominic I should hope I don't get a star that I shall I chili Mahalo I start I want a teacher to teach her neighbor huge hog war either to a character in a sliding window Bay Joshua agent Bern fan hawk Johanna who inferred repl may your own footage $18 a lie which may your own footage $18 a lie which may your own footage $18 a lie which should are during a drunken omissions edema shin Turkish our corner case you'll read otherwise when switch harlot Eagle instead see Liu Kang a map in telling her you know her she memorized her trunk with a harsh MapReduce your kick and you should have a character I know she could integer lies when to go make a character doing the pure naturally no immune you got I will do that I saw a figure in turn relied on a map which I'm okay Joanna then hang on trigger Wikipedia to share to you trigger ASCII table that you go gently good sear sure I'm all about the jingle sighs away your body the table chart Enter key answer soon bundle know who extended our yogurt sir for no Megan so for you're doing the to the index you Joshua character psi to the ER political shoe Solomon to in the trigger in text OSHA ban usual for Rugova South America in photo Lumia that you can carry character beam of our to whether P to go to in the way to show you Joseph are doing took a way to cha-cha he now I got doing took a way to cha-cha he now I got doing took a way to cha-cha he now I got on I will who either sliding window of our star so it hasn't returned na hoona children I know unity Siwon Channing attention the don't know PS our job deontology so-called real character the P new so-called real character the P new so-called real character the P new social sliding window linear mayor repeated a character no conjunction the sliding window that you watch on do result bacon Samui is late way to do I am worried too much attention is up entity soccer the character few character the PME no joke I should pursue to the started to turn my chili Mahalo Starla so dr. tuna guy characters and mapped on that ago they children aged over Cheney naturally Peter Shapiro Janey sliding-window the European Janey sliding-window the European Janey sliding-window the European children starvation chainsaw starts without Aruna guy characters and mapped on page 0 develop UAE truly actually a either Shinra beta e sliding window the tour in astonishing chainsaw it's late 2007 chuckles of otra nota cote de año pasado gon universally bein trigger input string bound on America character Cunha Vedado sure I will owe you more colleague outlaw size to your map the merge a dolly cosine longest a substring wizard repeating characters to toe holla
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
383 |
Hello Guys Welcome Back To Tech To Join This Video Will See The Answer Note Problem Wishes From List To Day Three Of Them A Challenge So Let's Look At The Problems The Amazing Notes And Letters From All The Writer Of The Truth Can Be Constructed From The President Can Only Be Used Once Saw You Majumdar String Contents Only They Can Only Be Used As No Example To Support Them Not To Give Money Subscribe Khemraj ATM 100 District Only Given To You Know You Need To Find Hidden Letters For This Channel Latest Be Used Only One Can Stop You Can See Things Subscribe Hero Lead Interver Give You Letter This Is The Present Chief Editor Present President On Tuesday December 8th Setting Show Your Character Invention Note Anil Procession In Every Character In The Magazines String From Left to Right unless you find this current character so you can see that you want this I know you jumped on the same have medium low for 800 to 1000 subscribe Video subscribe Now you want to know from the position this presents subscribe The Channel press The Big Did Not Present In This Present All The Vice President To Remove A Very Simple App Verify Weather By Using The Latest Updates Magazine You Can't Form Difference Not Know What Will Happen If You Are Not Able To Make The Not Able To Make Sure You Will Not Be able to avoid after updating of every character from the distance from the opposition will not be seen after updating from you will not make a very simple and where is the length of this is what can we do to improve this app uses to count quarters To Be Just Simply Counting The Characters You Can Decide While It Is Possible To Make This Revelation String From This Magazine String Note Solitaire From This Post Will Never Rans Bring And FD Account Each And Every Characters And Kids Have You Can See But They Have Only For Distinct Collectors Difficult Forces 12814 BCD Fragments Show A Grade Three Times Every Three Arrested For The BCD Zara Only Want To Cancel The Account Of Every Character Will Give You To Subscribe Characters In The Guardian To The Please 30 Present Indian Magazines Printer Software For The Current Account Cigarette Daily Watching The Magazines For You Can See And Disposed To Think 123 Sudev Satisfying This Is The Only And Only Bandh Thing Great Think Way To The Self Satisfaction For This Chhitu Is Greater Request Oo And Satisfying End User Satisfaction The Point Where Possible To Make The Answer String From This Magazines To Give You Consider Magazines Like This One Under Possible To Monitor Content Every Character And Subscribe Bcd And Subscribe Button In Just 120 Days So Right All The Character Center And Spring So This Will Not Be Able To Make And Sunscreen Swift Cases Return File Fennel You Are Able To Understand This Very Simple And Time Complexity Of When Is The What's The Latest subscribe and subscribe the Channel Please subscribe And subscribe The Amazing Ki Cutting And Unwanted Within 12-12-12 They Will Play Again Do Unwanted Within 12-12-12 They Will Play Again Do Unwanted Within 12-12-12 They Will Play Again Do During Track Pants Will Keep Discriminating The Correspondingly Twelve Years So Whenever He Gives Interview Time Will Check Before Discriminate Validity Current Position Easy And 90 Not Be Possible To Avoid Character 1200 10 Minutes And Is Having More Number Of Characters Which They Are Currently In The Mystery Solved Thursday Subscribe Withdrawal Can Only Be Used For The Very Important 90 Subscribe Uttar Pradesh Friends Now Note E Do Not Find Any Value 2017 Simply Return True Said This Possible To Make The Sentence From Magazines For A Few Verses Solution In Different Languages And Comment Everyone Can Different Languages And Comment Everyone Can Different Languages And Comment Everyone Can Benefit From Like Share and Subscribe
|
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
|
203 |
hi today I will talk about problem number 203 remove linked list elements at each code so the question says remove all elements from a linked list of integers that have value Val so the input example given is 1 2 6 3 4 5 6 and the value is 6 so the question is basically asking to remove the number 6 from this list such that the output will be 1 2 3 4 and then 5 so the first thing we do is let us imagine this so a linked list will look something like this with this pointing to 6 to this point 2 3 and so on and so forth now wouldn't draw the whole thing just to save up space to write the code will also be available in the description area so the first thing we see here is that we want to delete the value 6 from this list and by doing so what we can do is connect the pointer of the second to the third here therefore skipping this zone how can we do this in code so the first way to think about it is we can create a variable called current right and we can start writing down here so let's say the current will be pointing at the head which is in this case here so we can say while current which is basically while the value is true while you haven't reached the end here which is no I want you to check two conditions if the current value actually equals the value which is right here do something else it doesn't equal that value so do something else so the way we would think about it if we want to skip the connection from here to here we need to create a second variable to keep track of the previous value so here we create a one variable called current equal head I'm sorry here is just a little bit of invitation here you got the current equal head we need another one and for this case we're gonna call it privet which is in this case previous but we cannot set the previous two head and that is because if the first node here would be let's say number 6 then you will lose the head forever so the best way to do this is to create a dummy node on the back here and make it point to this so this here will be a dummy node so the way we can do this in Python is we can say dummy equal less note and they define the list and we can just give it none and we can say dummy next which is this right here points to be held so this line of code here basically says that dummy next points to the head here just like when the current equals the end and the previous can equal this dummy value previous is now here so we created a dummy note we point the dummy next to the head we set the previous to the dummy value and we set the current ahead so now we have two pointers one pointing to the dummy and one pointing to the current so again sorry there's a bit of indentation here so while current so while this is valid if this happens to be which in our case so it's gonna go to the first one so let's say the first one will be else so if it didn't equal anything then I would like you to point the previous to the current so if it comes here and it goes like hmm this is not the value I'm looking for color here then I want this one to be previous so this is first iteration this is the second iteration right so previous is now here now we get a move current and basically we do that by saying current equal current next so current next should be the new current so this then well basically move here right so the green is the first step the red is the second step let's now imagine it's one more hair so in the next step again previous is gonna come here on current is gonna go there now perhaps we even can write this with a third color so it's clear for everyone so any third step previous is gonna come here and current gonna go here so here in the third iteration if current don't that equal valve we want to believe this so what we will do is we gonna move current to here and may the next of this point there so encode that would be so the value for previous dot next will now be the current dot next so if we were to imagine this mod of colors now so if we were to imagine this will basically say the current next which is right here will be where previous next point so this is basically can look like this and then since this is looking there this is connection is going to go in this connection is gonna go right and we have to return something at the end of the function so we will return dummy dot next and our dummy is here and dummy dot next is here so we're basically returning everything here thank you for watching if you have any questions please feel free to write them down
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
1,909 |
hey YouTube hey tube welcome back today I have this problem it's called remove one element to make the array strictly increasing that we have given a zero indexed integral array nums called nums return true if it can be made strictly increasing after removing exactly one element or false otherwise in the array is uh if the array is already strictly increasing return true uh the early Norms is strictly increasing if Norms one uh minus I if nums uh I minus 1 is less than numbers of I so let's just take this one as an example we have this one and my thought that the solution for this one is pretty straight for that we will have a count variable okay and this one will equal zero and we'll just try to find that and to satisfy this condition which is nums I minus one is less than five so oh sorry so we start here from index one okay and we see that if this one is if Norms of five minus one is smaller than numbers of I yes okay continue if numbers are five minus one is smaller than numbers of I yes continue if number five minus one is from the numbers of I know so make the count by one and I will do continue so Norms of I will do continue so I will have count one so if I delete 10 this is this one if you delete then the array will be strictly increasing so I will say that if count is less it's bigger than one that means that it's false if it's less than or equals one that means it's true so let's just try to cool this one however there is some cases will fail and we will talk about how we can solve them so say let's count equals zero and I will return count if count is less than or equals one it will be true or false I'll say four uh four let I equals one and I will see um oil less than nums dot length and I plus and I will say okay so I will do if I will put this condition if nums of I is smaller than or equals nums of nums uh oh what's going on nums off I minus one we increase the count by one so count or V plus loss and let's try to see how this will work we have some education that we will fail so okay it works in most cases but we have this problem but I just look about why this didn't work so let's just go back here so why this didn't work so as you can see there we need to remove these two elements at least all these two elements at least but why the code is filled because first of all we're only checking for the only the previous so I'm saying that if this one if um if this current is bigger there if it's previous smaller than it than the current yes okay if the previous smaller than the current yes that's right If the previous is more than the current yes that's right so we're checking if this is If the previous model then the current all the time but however it's not that means they are not they will not be increasing all the time so how can we solve these problems so the thing that okay we will say that okay if we are not in the first index that means if we have flee at least two elements we wanna check for two things if this element is smaller than the previous okay because this is a problem okay I want to make sure that okay if we also smaller than the previous of the previous because if we have this one if this one is a because this one is a smaller so we have only one and we're trying so the count will be only one by the end of the group but it's not increasing in the right way so what we should do is that we compared this one this uh this element by its previous and the previous of the previous and when we find this one in the previous of the previous we will just do something um uh pretty straightforward that we'll try to update it update this one to be the previous so let's just see how we can do this one so I want to say that if I is bigger than one that means that we have at least two elements to Loop through and okay and nums of oil is less than or equals nums of oil minus two what we should do in this case we should say the nums of I will equals nums of I minus one okay so let's just see why we're doing it like and actually this will solve our problem as you can see this solves our problem let's just talk about how this worked so as you can see this is not increasing okay however when we try to do the account where you get only count one because we have the same uh the main uh um the main condition is that if I if the current is bigger than the previous if the current bigger than the previous if it's not let's increase the count by one and continue however we'll discover the even this and this it's not increasing in the right way it's not increasing so why we should do that okay let's say that we are here so the current is not bigger than the field so we increase the count by one and also we should compare this current by this previous if this current is uh if this current is um is uh is also less than or equal the previous of the previous what should we do we should do pretty straightforward that we update the current to be three to be the current will be 3 right now and we'll try to compare when we try to compare this current with the new previous it should be at least bigger than this one if it's not bigger than this one will return false let's try maybe there is other solution for this one let's just think about other solutions to make it way more easier because I guess maybe this description it's not that easy to be understood so I will say that okay if I because then one and nums of oil is uh less than or uh equals nums of I minus two so um what the thing that we could do is that um I guess this is the only mainly solution I don't nothing coming from more so because the thing that we could say that if this one is smaller than the previous two if it's really small okay so let's just update it to be this one because to be um let's update this one to be the previous and try to continue um uh looping because when we update this one so when we try to compare this to with the three it that means it will not um it will not accept it will be false because we have two uh two counts instead of one we have two counts right now and the problem with that first of all I is smaller than the previous two elements Okay so until we reach I if this two was four everything will be fine but however this two is not isn't as is like when we delete this one our application will not be our array will not be increasing because we have two three we don't have four two three we have three so by the linking three and updated with this one three that is bigger than one and we make it sure that it's bigger than one we try to make sure that we are already increasing so this is the way that we could solve this problem it may be sometimes to look at the Investments maybe it sometimes becomes ah this is not reasonable but however uh this solution is it's really um it's really way more easy for us and just try to think about it and I just suggest to you to just to try to type the code that I'm typing one by one and run The Code by itself to make sure that you understand things quite um perfectly and if you didn't like my solution feel free to give me a comment your solution is not that clear and um a lot of you talked about the voice problem I don't know if this voice right now is good or not if the voice is good just give me a thumbs up and tell me yeah the voice is good right now and yeah that's it this video and I hope that and see you in future problems
|
Remove One Element to Make the Array Strictly Increasing
|
buildings-with-an-ocean-view
|
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`.
The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).`
**Example 1:**
**Input:** nums = \[1,2,10,5,7\]
**Output:** true
**Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\].
\[1,2,5,7\] is strictly increasing, so return true.
**Example 2:**
**Input:** nums = \[2,3,1,2\]
**Output:** false
**Explanation:**
\[3,1,2\] is the result of removing the element at index 0.
\[2,1,2\] is the result of removing the element at index 1.
\[2,3,2\] is the result of removing the element at index 2.
\[2,3,1\] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** false
**Explanation:** The result of removing any element is \[1,1\].
\[1,1\] is not strictly increasing, so return false.
**Constraints:**
* `2 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
|
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
|
Array,Stack,Monotonic Stack
|
Medium
|
1305
|
1,460 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go q one make two away is equal by reversing sub-arrays yeah so for this reversing sub-arrays yeah so for this reversing sub-arrays yeah so for this one I'm gonna have a proof later on the explanation but base a what I did was just try to think whether they say I've here you can prove to yourself a little bit that if you could you can always using reversing supper ways sort in a way and once you do that what you realize that you're like okay well if I could sort the first away and the second away and the talkative way and if they you go to each other then that's good and that's pretty much all I have and I did this in 50 seconds and maybe my fastest time but I wasn't even that fast words of Lee so I think I didn't submit here because I just wasn't sure that was correct it's a little bit Yolo I even submit got q1 okay who q1 make two away equal by reversing several ways so the idea behind this plum for me to solving this problem that I did behind it and I wasn't super sure to be honest and during a contest you're not always going to have time to prove yourself what it is and this is a little this is a Yeezy farm so I don't a little bit matter in that sense that I was like okay seize it can't be that hard but I wasn't sure so that's why I hesitate a little bit and the idea here and you could kind of guess by looking at my result is that you can make two away eco or by so basically working supper ways is essentially like using two stacks or something like that and you could do a short idea behind that is that you could convert any way to any other way by using reversing self supper ways because you can imagine just doing a one at a time like bubbles so it kind of or insertion sort of something like that I just get the first digit in the beginning right and when you do it that way you know the easiest thing is just to sort both four ways you think that algorithm and now they have a album you're like okay and let's see if there you go and there you go then here you go so that's pacing in my strategy my idea my album and this is one line I served in 50 seconds because of that but uh oh yeah
|
Make Two Arrays Equal by Reversing Subarrays
|
number-of-substrings-containing-all-three-characters
|
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000`
|
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
|
Hash Table,String,Sliding Window
|
Medium
|
2187
|
858 |
hey everybody this is larry i'm today i'm going to do a little bit differently because um i've already done this problem before i'm going to try to explain the solution really quickly really shortly and then you can watch me try to explain the explanation much slower and doing it live more so if the solution is too fast feel free to fast forward to the second portion and you could see me look at the problem for the first time today anyway and so forth um anyway do take the time to hit the like button hit the subscribe and join me on discord and all that stuff but yeah but for this problem um basically let me get this for a second uh so we have this problem you have p's and q's right and the way that i would think about visualizing this in terms of solving in your head is that you know you instead of doing reflections you have an infinite grid instead where you extend um you extend the lines and now instead of reflection now you get line intersections instead right um oh i have to put this up um and yeah and once you put that um you can also reflect and fill in the numbers that are in the grid um if you wonder why i already have them already because i you know i actually go do this live during the video later on so you know stay tuned for that but basically once you do that once you do those two things where you know you fill in the numbers and the reflections well you know that um not now there's no reflection anymore and it's just intersection with the lattice points and what i mean by lattice points is just the corners of this grid you're trying to find the first intersection right and i also put x for start on this visualization because um but it turns out that it's impossible to get them get to x without hitting one of the zero ones and two corners right and so then the question becomes um how do we you know um how do we figure out which corner it hits right with this visualization well the first thing to notice is that if you look down the columns um because we're just doing like reflection of you know the previous and i say reflection i mean in terms of grid right so like in the second column you'll notice that it begins at zero and then one and then zero and then one and so forth all the way infinity but no the key point is knowing that they're only going to be zeros and ones in this column in the second column you're going to have x which is the starting point that's right called the x you have x 2 and so forth right all the way to infinity and then you have the dirt flow column which is also going to be 0 1 and so forth right and similarly if you look at just the rows going from left to right you can see 2 1 and then on the second row you can see x0 x2 and so forth so then the thing that i reduced this problem to is now um you know you could think about it as well how many intersections with the lines are there right is it on the even row or is it on a even column or so forth and that's the way that i think about it and in terms of the number of total intersections between uh before it hits it's going to be the lcm between the two numbers right because the short hand maybe a little bit i explain a little bit better later or in detail later but basically the lcm gives you the first place in which the ps and the qs hit together and it also will give you maybe the minimum p and the q to get to that lcm which solves the problem because the p the new ps and the new qs in that sense right will give you the number of intersections which is the same as the row number and the column number okay feel free to pause or re-listen to feel free to pause or re-listen to feel free to pause or re-listen to what i said because i know i go really fast sometimes um but make sure you understand that part and then we'll go over the code and then now you know i'll give you a couple of seconds to kind of do that and then after that you know i'll go over the code as to why this is true right so now lcm is you go to the chord um the first corner which it hits right oh yeah first we said we check to the zero cases because then you just have you know horizontal vertical lines and then lcm will give us the corner of which it hits and then now we just check to see um is it in a even uh is it in the even column if so or sorry is it in the even uh row if it's on a given row then give it zero if it's a on a even column give it two you can also rewrite these if statements in different ways i try to make it clear uh but the lcm over p should give you the row number and lcm over q gives you the column number i hope i said that right and anything that doesn't hit those two then it's gonna be one because that means that they're relatively prime with each other um and also that um it's gonna be on the odd column and i uh row right so those are the only cases um i'm gonna to give you back to larry solving it live so yeah let me know what you think though um and let me know what you think about this format and i will see y'all you know later hey everybody this is larry this is day 17 of the league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm mirror image or mirror reflection okay so i think i've seen this problem before on lead code um so i do remember the trick to be honest but i think i uh i'll have a link below so you can watch me solve it live for the first time so i think i'm going to focus this one on explaining as much as i can that said i don't remember all the details so i could be a little bit off but i'm going to just um just talk about the math about how this works for a second and i'm gonna do that by pulling up microsoft paint so give me a second okay hmm let's see okay right so basically you have a room and you know there's some line that goes from left to right and you have to figure out basically let me read the following for a second you have to basically um choose where it meets zero one or two right so there's zero here all right which one is okay one and two and that is a terrible two okay right and now you have some p and q right and now try to figure out which of the lines uh which one it goes to right well so i for me i think i would just break it down to case analysis and the tricky thing is noticing that the p and the q's um let's see it means something right so how do you get to um you can bring it down by case analysis how do you get to the one right well one is if you know it goes directly right so that's one um so if p is equal to q then it goes to one or if it goes to so an odd number of times right um so if there's odd number of bounces it'll go to one uh and for kind of um for uh you know and you can kind of think about this problem in a way such that um it doesn't do that many bounces and what i mean by that is that for every reflection you can think about as an extension into the box right so that would simplify things a little bit more for example instead of having this image now to figure out how to redraw it um like you can think about this as you know instead of do you can think about this as just a straight line that goes to some diagonal off the screen which i you know have to plan a little bit better so maybe i'll rejoin this one right and from that you could it should give you the visualization a little bit better about the geometry of the problem um so let's say this is zero well so groups that is not zero though so you have zero uh one and two and my two is a terrible so you have something like this right and you could kind of think about it in terms of uh just reflecting it and now you have multiple boxes that are and then now this one would be a 2 and this won't be one right so the other way to think about it is that if this goes here which is the same as this going here and here i'm reflecting then that's a two if this goes here which is the same as you know just going here and then here we let me change the colors for a second actually right so this goes here which is the same as this goes here and then here right so by that so basically this visualization is how you get to um a easier way of figuring how to uh set you know figure out from the p's and the q's and kind of and also like in the same way you can also draw this box upwards right oops so that you know you take advantage of the reflection there as well so that you know in this case you can look at um you know this one as zero this one has the starting so you have to keep on going uh yeah you can't really read infinity can you oh no because the only way that you could get to the starting is by bank stop one right because you can kind of and this makes it easier right because if you drew all these boxes out i'm gonna write x for starting then you can see that you can only get back to the starting point like every way to get back to the starting point has to go from one so that means that um you know it makes the problem a lot easier but it also means that you know instead of uh bouncing so this way it's all just the same as going here and then bouncing back right so those are the visualization you would need to kind of figure out this form uh for me and that's how i'm gonna talk about this problem in terms of coding and that's how i'm gonna get started on it and again i did solve this live like maybe a year or two ago uh and i have a video below you can kind of click on the link to see where uh how i thought about it because i'm curious as well i don't remember this farm i am solving this live so i haven't seen this in a number of since that i did that video so you can kind of see how i attacked that problem uh totally fresh and i think i did a different tutorial um into or a different video style back then so you can let me know how that looks but uh it's a little bit outdated but that's okay i hope but yeah so given that okay how do we convert that to code right well if uh let's see so if p and q i mean if we kind of look back at our um our thing maybe i should have kept this up a little bit longer first if we had you know um still have this right well what gives you a one i think this is one of those case where also because you have to end somewhere right because you can't go back to start and there's no infinity eventually you'll hit one of the spots so the way that i would think about it is well which one is easier to code and then the else you do the other two right um or one or whatever so in what cases do you get one only right well you only get one if q is a an odd multiple of um an art multiple of p or the other way around right and you can kind of see that um because you have you know the ones here and i think you could draw it out a little bit more maybe let me move this a little bit itself actually drag this oh there we go um right and you could kind of like if you really want to visualize it you could keep on drawing boxes in a white color so that one's a one um and so forth and you could kind of see how and you could maybe visualize it to prove yourself that the ones will be on the odd multiples um that what that's what it looks like to me right so that one is easy to code i think um and then now you have to figure out which one um which one will happen first to zero or to two and if it's not multiple then it's a even multiple and then you just have to figure out um which one is bigger i think um yeah and let me kind of and to be honest uh my pause is because i'm not super sure for a second uh i think during a contest i might have just kind of i mean i know um and during the interview you should kind of go through it during the contest i probably would have just tried the two cases because it has to be one or the other right like so you could just it's a little bit of a cheat and a hack but uh that's probably what i would have done uh so this is also in this refraction way which allows you to kind of visualize a little bit better notice that obviously um you know like we don't there's no need to go to check the thing on top over here because now in this um in this new world we don't have to worry about it because there are straight lines instead of um instead of doing that right so then that means that in that case if you look at this thing um if you look at if you draw this box all the way out because we're all reflection on the first column or oops all these are going to be zeros right if you look at this column or like this oops look at this column here all these are going to be zeros and ones right so there's no um right so there's no twos in here because that's not how the reflection works and also if you look at here this is also going to be just twos and oh yeah and these are and twos and x's right which uh as we said are all ones so and there's no reflection there right or because there's no way to get zeros into the second row right so then from that i think we can that should be enough for us to tell that um given a p and a q we could figure it out i hope um yeah let me jump to code now let me know if you have any more questions this is the hardest part about this one this problem is obviously the visualization and once you have to visualization tricks then it becomes much easier right um so let's do if let's do the odd multiple thing right so if um okay so equals zero and p this is odd then we return one uh and then you know the inverse case actually we could even now i was going to say we could simplify by swapping the smaller one but maybe that messes up to say when the 2k so maybe not and i also return i'll return one out right and then now i'm just looking at the visualization again all right whoops there sorry friends uh but i mean you didn't miss much it's just i just typed this up um but now let me take a look at the image yeah so now yeah we cannot swap the p and the q's because that means that we kind of if you look at this because then that means that you swap to uh you like do a mirror on the x equals to y axis and that would obviously change the answer so we cannot do that um and now so if p mod q is equal to zero and um is that good enough i'm just looking at the image just to make sure i get which one is p which is q to be honest because i think that one um so if p my q so p is the bigger one do they always have to be multiple uh do they always have to be multiple of each other how do you get to two three two yeah two three is a two for example right so that's definitely not always true so basically we want to see where they intersect and basically okay so i have a couple of cases i think i'm trying to get ahead of myself by trying to reducing it too much um but okay so if p is smaller than q yeah which is however okay so if p is smaller than q then you have to upwork thing and then and if that's the case if i just want to make sure that i'm right that's why i'm taking my time and saying it i don't want to mislead in any way but yeah so as we set everything to x2 um oh okay so i did get confused about the corner reflections that i already met that's why like for example two and a four so that means that every um okay so now what does that mean right so i guess you are seeing me getting to solve this for a little bit more um because now you want to see where they intersect and they intersect on the and we kind of have the visualization here right so i'm just looking at this is what i'm doing um i think so i know what i want to do which is to talk about this odd uh column and even column thing and then i'm trying to represent it mathematically slash encode so that um well so that we could answer the question right so what does it mean for it to be on the odd columns or every other column to be zero um so if this is p draw that click if this is p and this is q right uh what does that mean well and q uh it's not the entire length of the thing so that's why i have to make sure that i get the thing right uh because this cube will be multiplied by um i have to represent this in a slicker way so that okay so we have okay so i think i have to wait to think about it so you can look at looking at this graph uh or picture you could look at the number of uh columns or line intersect or reflections as um you can look at it as you know you flip the q and appear p right um to kind of get the corner that you're getting at and then you could just use the lc uh the least common multiple to get the idea around um you know how many reflections on that edge right so if there if the even number of um uh reflections on the yeah if there are even numbers of reflections on the um left right axis then it's a two and then you've and if there are even numbers of um otherwise it's a zero and that's pretty much all you have to do i think yeah so that's what i'm going to do um and i hope that visualization makes sense in terms of the number of odd bounces or even bounces um and you get that by how do we get the number of bounces right well given p and q you can just get the uh least common multiple and i think that should be sufficient uh and you know uh and now if this um same thing i suppose and uh which one is the p you know that's the part that i have to double check so if p then that's too bad um the p is the bigger one then the q would have more bounces so that should be two maybe i get them confused but that's the general idea um hopefully uh i just try some random numbers also zeros uh yeah lucky i did trust that so if q is zero what does that mean right if q is zero we return zero just looking at the uh the picture up above the pier 0 we return 2 right okay now well one is also we have to get some uh odd numbers in there or whatever yeah so okay so all these are right but um maybe this one's well yeah so i am a little bit off in my logic here this is a tricky one whoops this is not i mean this is never that's why i was like that doesn't make sense uh that was just a typo uh to get make sure that's the number of division that we get uh for the diagonal and whether that's odd or even um will give us the answer um okay i think ideally we do every um every case for small numbers and check them but i'm just providing more random numbers to kind of make sure that we're confident about this a little bit uh so it looks good let's give it a summit and fingers crossed oh no five three uh okay so maybe mine oh i don't have enough one cases um i think i skipped over it too much where in this case i was just focused on the diagonals but i don't focus on say um on say this number oops like i don't focus on this one at all right well okay i do focus on that one but i don't focus on say like the case that i'm missing is i'm just changing colors hang on is like see like this one for example uh because that should be a one in that corner um three and five so basically what does that mean that means so okay i think another way to do this is more like if oh and this is always going to be you still i don't know why i put that because that's the definition of lcm so yeah so lcm we could probably do it this way is a little bit easier um oops that this is two and this is one and why that is that basically we just uh these two cases are very is the same as each other except for that you know the mirror image right so then everything else is going to hit one just by it nine not hitting one of those two um cool um i mean i even though i had the vague idea of using um the visualization okay i had the thing still sorry about that hang on i mean i only um but yeah but the way that i would think about this in terms of this code even though it's so short and fairly understandable is that this lcm gives us the corner of um where they intersect right because the least notebook common multiple is where you know given the peace and accused essentially they bounce around and intersect and then now we kind of talk about it um which is that if um the number what i call the p bounces which is the um the bounces on the horizontal one or maybe the vertical one uh and then the number of bounces are left on going upwards right uh vertical if they're both odd then it's going to be one which is this case and if the number of uh bounces on one dimen on the horizontal plane is even then you're gonna get a zero and otherwise it's a two which is just going up but you can actually uh just if i get away and again i'm gonna pull up this thing um but yeah you can kind of look at it um you know either in columns but you can also look at it in terms of rows and that's how you get the differentiation between so basically uh you can see that the twos are always on odd rows oh sorry the twos are always on even columns um while the zeros are always uneven rows right so that's basically uh and there's even rows means that there's um even number of reflections uh on that either column or row so that's basically how i would um think about this problem and i know this is a little bit tricky and that um i'm about 20 minutes into the pro video before giving you the visualization so i might kind of um redo this part in the beginning but uh but yeah um cool so this is constant time constant space let me know what you think about this problem uh it's really tricky and i will see y'all later bye
|
Mirror Reflection
|
masking-personal-information
|
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`.
The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor.
Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_.
The test cases are guaranteed so that the ray will meet a receptor eventually.
**Example 1:**
**Input:** p = 2, q = 1
**Output:** 2
**Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall.
**Example 2:**
**Input:** p = 3, q = 1
**Output:** 1
**Constraints:**
* `1 <= q <= p <= 1000`
| null |
String
|
Medium
| null |
709 |
in both language has this I think okay well maybe it's a good practice but that's why this is the easy way today did something change did they actually tell you whether the things are the same that's new it haven't done this in like a week and a half so because they used to just feel like now it's completed wherever now that's good doing them to drink that there's a lot of on Tom's terms I'm wondering why that is okay well it's not because the problem is tricky okay I mean I accept is cool I mean this is just implemented lower case I am lazy and I just did to vibrate I would not expect it to be on an interior just seems way too easy you want to do it manually you just have a four loop and then you know convert a character by character I was too lazy to do that okay yes that's it I don't know I don't really expect histamine and Amir so I'm gonna do another one so okay I mean what this even be on the contest I don't even think so or maybe it is I don't know this is way to use it this would be like not tiny points okay
|
To Lower Case
|
to-lower-case
|
Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of printable ASCII characters.
| null | null |
Easy
| null |
1,171 |
Hello everyone I am Ri Sharma and today's our TD is remove zero sum cute note is a medium level problem so first let's see our problem statement then see its problem statement is given the head or you have a question and I have given its head that's it The essence of the song is to repeatedly delete the cut sequence of notes sum to zero. What you have to do with that is to delete the notes whose sum is zero and you have to keep repeating this process until you get such a list in the final. Which does not have a single sequence in which the sum of notes is zero. Okay, let's consider this as an example. What am I trying to say? Suppose you have a list given like this: Su 2 Minus 6 N Na 5 Minus S This is the tap next to this list has been given to you, are you able to find such segments in it which you can say whose sum of nodes is zero, I am able to find it, look at this segment, these three nodes are also continuous and If you look at their sum then zero will be coming 4 P 6 Min 60 Similarly you can see it, what did you do with these three nuts first you got this segment, suppose you said remove this segment then you have List b was something like this, after that one will be coming then man then you will see if there is any such segment in this list whose basically sum of notes is zero then you will get this segment then if you pick this also then at At the end, what will you be left with, there will be three in the list, next to it will be one and next to that there will be null, this will be your final list, is there any segment in it whose sum of notes is zero, it is not at all, now how to do it, the question comes that How will we find out, the main issue is whether to remove it or not, so we will see. The main issue is that how will we find out, there are nodes whose sum is zero continuously. You must have asked such a question in the array that what is like this is the question. Are there any such segments in this array whose sum is zero? If there is a question, then what we used to do in that, I will tell you how you will find out their pre-sum, prefix sum, you will find out their pre-sum, prefix sum, you will find out their pre-sum, prefix sum, what would be the pre-sum from this node, if you had what would be the pre-sum from this node, if you had what would be the pre-sum from this node, if you had taken out the prefix from the starting point. What will be the sum from this note to this note? This is the sum from here to here. How much will be the sum from this note to this note? If you are taking out this prefix sum then it will be from the starting till the sum from the starting till 10 my 6 4 ok now tell me one thing this is what is the starting sum till this node is three till like this from the starting till this What is the sum till the node? If till the fourth node is three then it is three till here too. This means that the middle notes have not contributed anything to everything. Tell me one thing, you are saying starting. From till this note, the sum is three from starting till here, I am even, that too is three, it means that the middle three nodes have not made any contribution, the sum is three, I was getting three in the beginning. The total contribution of these three together will be zero, so if you understand one thing from this, while extracting the question, it is repeating. If the hack has ever come before, then the sum of all the nodes from then onwards will be zero. I was talking about this, I assumed its index is zero from two th four to six, then I saw that the first prefix sum has come at the zero node. And the prefix is also coming on the third node, it prefix is also coming on the third node, it prefix is also coming on the third node, it means that the first second and third nodes have not made any contribution, what is the sum of their total, it is zero, so are we able to find out this thing? We found out from the prefix L that we If it is repeating itself, then we will see that it was doing it for the last time, so for the first time, it was coming here, which means that it was coming here for the first time, all the nodes after this till here, let us assume that I am at this node. Speaking current node, I am on this, I said this is the sum of current, this has come before, then I said which note is after this, no tooth, till this note, the sum of all these is zero, so what kind of segment is this segment. You can see that this segment is the one whose sum is going to be zero. If you want to remove it then it is very easy for you to remove it. If you know this note where I had the sum for the first time, you know this note. If you know the current also, then you just don't have to do anything. What you have to do is remove it for a while. This is what we have created below. If we had removed these, then what you have to do. If you understand one thing, you have to remove this node. You don't have to do anything for this, you have to put this node next to this node, then wo n't the side notes in the middle be removed? If you think and look at this list, you will have this head, next to the head, you are reaching directly here. You, this note is not there, this note has not been removed, okay, so now how will we do this, how did we find out this thing, just now we have said this thought, is it repeating in yours, then can you tell where it was coming last time? After that, what will be the sum of all the notes. If it is zero then we can do it with the help of map. What will I do in the map? I will see whether any sum is existing or not. Suppose I have created a map named MP. I will see if any issue is registering or not. If not then I will store it and respond to it that what was the issue of my first node, was it coming for the first time, I said ok, what is the purpose of it? If there is a node with zero, then zero is the time till the note is reached till the note is zero. Then I looked further, how much is the sum, what is my intake, if the sum has ever come, if it has not come at all, then the sen will go to my map. Which note up to the first note, after that, what is my sum? Naan, I said, my Na sum will go in the map that it has never come and which note is this, till the second note, then I saw, okay, my sum is three. If I am getting three sum again then it means that I have found the segment which I was trying to find and the segment which I have to remove. Okay, then you will say that it is coming from your three sum. You will see where three was coming earlier, you search the map, it exists in the map, then you said that if I saw in the map, then three is equal to zero, the note with zero was coming on it, then you have to remove all the notes after this, then you To remove it, you can do this directly. You have got this address that if zero note is coming then fourth note will be inserted next to the zero note. If you were on third note then fourth note will be inserted and do you need to do anything else? What do you have to do after putting it in the next section? Understand that you have to take the M off of your evenness till the end of the end. Evenness of the end till end. You said that the end of mine has already come before but the end of this till is also an endem. If you do M sum, you will not get N, you will not get this one, in whose next note you have to put Y note, then what will you do in MP presum next, you have to remove the middle note, just don't do anything, you have to put the Y note in MP presum next. You will insert the nest of your current node only then because all the nodes will be removed. What will you put next to it? We will insert the next node of your current node because you have to remove all the nodes after MP presum till the current one. So you have done this. If you do this then the middle side will not be visible. You have removed the nuts but see some of the data of these nuts is still stored in your map, up to which node the intake sum was, what about this nut will not be visible in the new list. Understand how the list is, if you remove this number and put it next to it, then how will the new list look to you? Directly next to Th, there will be one, after one, then this will be one, then F, then six, after that tap this. Will your list not be there? Will it be actively participating in it? Not doing. If you have removed the nodes, then if you are removing these nodes, then you will also remove the ones that are stored in their data map, you will also remove this seven even, you will also remove the nines. Why is it so? It is possible that you may get access later, so you will not say that Sen is already present in the map because you do not have that node. You are understanding the point, so what will you have to do to get that data from the map? If you have to delete, then how will you delete that data from the map? Then you will traverse these notes again. Which notes can you pass before to get this note? You have got this node from the map, this is the node with zero index. So, what will you do on its next node, let's put a pointer, let's say with the name Previous, and to where will we move this pointer, you have to delete it, you don't have to delete it, you do n't have to delete it's still in the list, I have it. See, you don't want to remove the sum from 'th' and you don't want to remove the 'sum', then I will move don't want to remove the sum from 'th' and you don't want to remove the 'sum', then I will move don't want to remove the sum from 'th' and you don't want to remove the 'sum', then I will move this previous until it becomes equal to my current one. Now tell me one thing, if you have to remove any value from the map. Let's do it a little to the side, I am telling you that there are two things in the map, one is the value, what is my prefix sum, what is my key, and what is the address of the node, what is the value. You want to delete any value from the key but you currently have it, do you have that node, you have the node address, or from this point, start deleting me, till you have to delete it, but you don't have access to it yet. If there is no pre sum then can you remove it, if there is a pre sum, then can you find the pre sum, of course you can because look, you know the sum here, what was the sum here, what is the pre sum which basically told you that this sum is the first Also, if you know the pre-sum, then you know the sum till this point. know the pre-sum, then you know the sum till this point. know the pre-sum, then you know the sum till this point. Okay, now which node is the node to be removed. If you want to remove this node, then what is the sum till this point? How would you have got this here? What will you do in this? You will add the value of the previous node, you will say, ok, the sum is sen, remove the sen, then you will carry forward your previous one, you will say, ok, what is the sum of this previous tak, then you will say, before this, the sum was sen, now this How much is the sum till the previous one? If not, then give the value to the non one. If you do this in this way, then you will know the sum till this point. You will add the previous one to it. This is your approach. Okay, now let us write the code for this thing which we discussed. When you write the code, what you had to do first is that first of all you will create a variable in which you can store the prefix, no prefix, yes, okay, you will create a map, what will you do in the map, you will only store the number, you will not store the number, let's say the name of the map. Now what will you do, if you start weaving then you should have a current node, I will create a point named current node, I will store the head in it, I do not want the head, my lens will grow to the node, I have stored it. Now in the variable named current, unless I move the current to the end while current is not equal to null then I will see that okay I am getting segments which I can remove so I will see so now my current is If the head is sitting then I will calculate the prefix sum till that point. How will the prefix sum be calculated? The prefix sum till any note is equal to how much prefix sum was there before me. I will add to it the value of the current value of which note I am on right now. Then I will What was the next step, I have to check whether this prefix is present in my map, so whether this prefix is present in my map, so what can I do with add f find, with f you can check whether this prefix is present in my map, if it is not equal to add a. It means that it is coming, is present in my map, if it is not equal to add a. It means that it is coming, is present in my map, if it is not equal to add a. It means that it is coming, if it is coming, then I know that if it is coming, then I already know that it is coming through it, then I know. I have found such a segment which I have to remove, so I will go to Y. There are some approaches to remove it on Y. The ratio we discussed will be discussed on Y. What will happen in else, will I go to else when my user is not existing? If this node is not present in the map, then I will store it in this map. If this node is coming for the first time, then store it and what will be its cusp, which node is it, store it, who is this cusp? C node is this pre sum cusp, which node is the current node, so you have stored the address of that current, your process will continue and what will you do, keep moving the current forward, current equal to current next, now you have to write its basic logic. That when your presum is coming from it means you are getting the segment then you have to write the process of removing the segment, what will be the process to remove it, so we just saw the process that first of all if you are getting it by segment then its It means where in the map it was corresponding to, it was coming for the first time, its corresponding zero node was coming on this one, which is even three, which is even, but if you have to remove it, then this node is not Sen Nan, if you want to remove it from the map, then what will you do? How to reach the node, do you know zero? If the node next to zero is the node, then you will say, what will I make, I will not make the previous list, node star, when this condition is mine, when my sum is crossed, I will not make the previous one, whose benefit will be my MP pre-sum? Mine is that the be my MP pre-sum? Mine is that the be my MP pre-sum? Mine is that the new one's sum is coming first. I have to remove this thing, see to what extent I have to remove it from the map, till the current is equal, I have to remove it, I don't remove it, I do n't remove it, I don't remove it from the even map, till the current is equal. I will keep removing them until they become equal. While the previous is not equal to the current one, till then I will remove them. Now one more thing and we had just discussed that with whose help should I remove them or with the help of the previous one. Well, what was the sum up to this point, should I remove it from the map, I do n't know the sum up to this point, but I do know the sum up to this point, how much was the sum up to this point, from where I am being removed. What has to be done is that the sum till the note before that was the pre sum, so I store it somewhere, let's say a variable, I create a variable with the name previous sum, this previous sum is equal to the pre sum, it is okay, you will do this outside only, this is what you do. Given, you will say, ok, what is the pre sum till the node where I have to remove, then you will say, what will be my previous sum, it will be updated, what will be the previous sum, brother, what was the sum till that point, add to it that my What is the value of the previous note where I am now, then you will not get the sum till here, see, the sum till here was yours, you first stored it in the previous sum, now you are saying that if you are, then this nut is So we will add this node till the sum is three, what is the value of this node, four, then you add four, then you will understand that if you are the one with seven, then you have got that sum, then you will get the one with the previous sum. If you want to remove the sum, what will you do, you will raise it from the map, add it to the previous sum, you will say, remove the sum from the map, what you will do, you will move the previous one forward, the previous equal to the previous one, next, that's all you have to do, you will be able to remove it. What will you do on this page? We will return it here. Let's run the head and see. Now there is one problem in it. If you can overcome the problem then it will be good. Otherwise you will see. You will submit now, then you will know what we have missed in it. We have missed one thing, I don't know yet, we have missed a lot, it seems that no note is being removed, we are missing something, let's see, ok mp prem equal to current, next current equal to current, next Okay, we forgot to do this work, tell me one thing, if you had to remove all these nodes, then you had to do this also in the next MP Prasam, now you have removed this from the data map but you have not removed these nodes because you are still In this, you are storing its address in the next while you know when the middle note will be removed, what will you store in its next, the next of the current which we had written the condition here, in the beginning by nesting the current in the next of MP of Presum. Two, all these nodes are automatically removed from the middle, so after doing this, after removing those notes from the map, after removing the data of those notes from the map, you will say in MP of Presum, in the next of Presum, I will store the current next. Now let's submit it and understand what we have missed. Look at one thing. In this case, see how much the sum is coming. If it is coming 1 -1 0 then you will how much the sum is coming. If it is coming 1 -1 0 then you will how much the sum is coming. If it is coming 1 -1 0 then you will remove this. It should be given that when you did not remove it, why did you not remove it because what you are saying is that you are seeing which problem is repeating again and again existing, like I write the same test case here. Let's solve this test case, my one is minus one and what is next to it is null. You are saying that okay, you made a map and started storing it in the map, then you got this one sum, how much did you get from here to here. If there is one, you said that we are getting one for the first time, its cusp has been indexed to 0 and index to zero has been addressed and here we do the repaint from the index. Now then you said, how much is the sum till this point? You said zero, does zero exist in the map? You said no, so what did you do? You put zero in the map but did not remove it. When you had to remove it, whenever zero is even, it is 18. Zero does not exist in the sum map. This means that I have to put zero sum in the map in advance, whenever there will be zero sum, what will happen to you, from head to head, this was your head and as far as your zero sum is happening, you have to remove all those nodes, you also have to remove this. This node also has to be removed. It is okay and zero sum does not exist in your map, it means one thing that I understand that you have to put zero sum in the map. Now you said that I have already been put in the zero map. If you want to keep it, then which node is the node, what is its copy node, then you tell one thing, look here, when you were removing, what were you saying that it is repeating something, you were saying that it is repeating, so Okay brother, when did this come last time? Let's go to that node and start deleting all the notes after that. Look at this case, you are saying here that okay, one minus as soon as you got zero, you said repeat this zero. Only here you will be able to remove the zero. This means that you will already put it in the map. First of all, which node cusp will you put, then tell me one thing, where to start the removal. From here, you have to start the removal. You are speaking from the head note. Where the zero sum exists, I will start removing it from the last note after that, this means that zero must have been there before this, there must have been a note named zero and I will start removing it, understand, so you have one thing. Please understand that when you have to handle a case with zero, what will you do? You will add one node extra, what will you keep its value as zero, so that the overall sum is yours, there will be no effect of list, the price sum from here till y is zero only. Neither your zero node will already store its cusp address in the map, that address will now look at the index, understand its index in this way, suppose mine is the minus of zero, then you can reach mine when you will see zero coming from mine. Here you said, where did the pencil go? Okay, look here, you are saying that zero is coming, so zero is here, should it have been present somewhere earlier, then you saw that ok brother, zero should have been present somewhere. Where should it have been done because if you have to start removing it from the head then it should have been done before the head so we will put an extra note before the head of zero value. If you have to do this much then it will become zero. What do you have to do? Gave the name N I New List N its val kya r zero ya baatri na jaagi whose val kya zero you will put it on K and put it before d then you will say in the next of minus n l doin tot ne la di Put it and you will also put it in the map because there should already be an automatic Y in the map, only then you will say that if zero has come through then M P of zero is equal to two, this one should not be yours, you have done this nut. Now tell me, will you make a return in this? In the case of zero, your deposit will be lost. When it is your zero case, then the single will be removed, but you have a rip. Basically, what do I have to return? This note should not be returned, but whatever is next to it will always be the start of my list. This note which I have added as an extra node will have a value of zero. Whatever will be next to it, what will be mine in the actual list? It will start like what is left in this case, the nut with zero at the end is left and the null is left, so see in actual, you had to return null only because your list was so much, the original one, out of which these two things are left. Hmm, so you said, whatever is next to zero, I have to return it. The zero is yours, it is never going away. What will always be next to zero in this list, when a new list starts, I will return it. Next to the new node, this is your code completed. If you can forget this case then yes special, you have to pay attention. Now you will run it and see. Okay, this net is closed, don't wait for a second. Now let's submit and see, this is our acceptance. Hope you must have understood that obviously it was a little difficult problem, it means implementation is difficult, it is not that difficult to understand but it is difficult to implement, so try it once or twice, thank you.
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
16 |
hello everyone let's look at three sum closest the problem statement is we are giving an array of n integers and the target integer and then we need to find three integers in the array such that the sum is closest to target then we return the sum of three integers an example here is the input array is negative one two one negative four target value is one the output is two is because the sum that's closest to the target is 2 that's negative 1 plus 2 plus 1 equals 2. if you happen to watch my earlier video you can find the solution for threesome the problem is really similar as a result we can pretty much use the same idea behind it that is we order the input array we loop through array using two pointers we make the two pointers move towards center to find the closest sum until they meet each other if i have confused you by using only these three body points i can confirm that it will be clear when we look at the code logic first let's reorder the input array by doing this we have sold the input array ascendingly then let's have a variable to save the result so this value we just pick the first three item and then we make it a sample value in our loop we will keep updating this value and make it closer to the target value so let's start our loop here the stop condition is i less than num star less minus two this is because our two pointers they will all leave at the right side of our eye let's claim our start and end variables at the beginning start will just add the start point to the right side of i and will point to the end of our array now let's start moving our start and end based on the sum value then we can do the comparison we compare the sum value and target value and then we can decide to move the star index or n index if some value is greater than target so we want to reduce the sum value then we can reduce the end index otherwise we want to improve the sum value that means we can move the start index to the to its right so we can increase the sum value in the end we always check if the sum value is closer to the target compared with this original value so if this sum value is closer to target value then we replace the sum value to this ends so let's return let's submit it passed also for the previous three sum problem we also checked the duplication for this question you can do the same thing but for me i will just leave it here let's look at complexity for space i think it's constant and for time same like the three sum problem it's all open square because we have this two loop first one is the for loop the second one is while loop if you have any question please leave a comment below thank you
|
3Sum Closest
|
3sum-closest
|
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104`
| null |
Array,Two Pointers,Sorting
|
Medium
|
15,259
|
333 |
Hello friends welcome to my channel let's have a look at problem 333 largest binary search tree surgery in this video we are going to share two treatments for this problem the first one is more robust and with some redundancy and the second one is more succinct first I'll read through the statement to digest the problem requirements and then we do the analysis and finally we share the code and explain the codes are line balance first the statement given the root of a binary tree finds the largest subtree which is also a binary search tree where the largest means subtree has the largest number of nodes so next in the statement it's a definition of binary search tree I will not repeat that so here is a note a subtree must include all of its dissidents so actually this is an important assumption so we are not considering a piece but we consider all the descendants so with that stage let's look at example one so in example one so we have the return should be three so we cannot include a ten for example ten five when it is also a banner search tree if you do not consider fifteen and seven however if we add 7 into the tree so the whole tree is not a binary surgery but the problem requirement is that a subtree must include all of its descendants so the three eruptions by the root 10 is not a minus 33 so the maximum size here is three not five so five means until we can include 10 and 15 right so this is example one so similarly you can analyze example two so with that said let's also look at the constraints first the number of nodes in the tree is in the range between 0 and 10 to the power of 4. so in particular it tells us that so the tree can be a null tree secondly the node value is in between negative 10 to the power 4 and positive 10 to the power of 4. in other words such note value can be zero or can be negative so here is a follow-up can you figure so here is a follow-up can you figure so here is a follow-up can you figure out ways to solve it with on temp complexity all right so with that said let's look at the treatment so here I'm going to share two treatments first I'm going to write a binary search tree Checker so or and also in nodes contour and then we use them to uh to do the job we may Traverse the tree so this actually is meant to help us understand the final details and the overall logic and in the sex treatment we are going to write a compact format of treatment one so actually it can be very short so notice that for binary tree to be a binary search tree so the binary search property should be remain should be valid for recursively in other words for all the sub trees so let me delete this form so with that said we are ready to do the coding so first I'm focusing on treatment one so in other words I'm going to write with some redundancy so right this redundancy but this is important for us to understand the final details so here I'm going to use three steps first so I'm going to write a BST checker so to save us some tapping I'm going to call this function f so the F will accept a root per node three node and the lower bound and upper Bound for the tree binary surgery see I'm going to initialize it using negative infinity and Float on positive Infinity right so let's call this the high right so um with that done so we actually can do the Checker so first if not root so in this case we're going to regard this as an empty menu research tree so we're going to return true so more or less we regard more actually more so we record this as a base case or stop condition so otherwise so then we check if the root value is in between the low and high strictly right so less than high if this is the case and also the left subtree and the rest of the tree are better to trees with proper bounds then we're going to return true so here let's look at the root left so we hope that the low Remains the Same however the high should be less than the root of value so we're going to set this High to the root value right and also we need similar sin for the vegetable tree however for the rest of the tree the low should be larger than the root value and the high Remains the Same as previous so in this case so we're going to return true so notice that here are some two recursive calls so all the other cases we're going to return Force so this function f is a better research tree Checker right it's going to check the if given a tree node which we are going to check if the tree drop into badass node is a binary search tree so this is the first part the second part is a simple one so it's uh I'm going to write a number of nodes node counter the nodes on counter so this can be done also recursively very easy so let's call it G it's just for saving some tapping so given the root so we're going to return a number right so first a stop condition or base case if not root so we're going to return zero right so otherwise so we're going to return one so this will continue the root node itself and then we count the number nodes in the left sub tree and the red sub tree so it's G uh root left and plus J root red so this actually we need a Traverse again so that's why we see that this way of writing the code and do the problem logic as the redundancy but it's good to understand the details as we mentioned so this is the second step the third step is traversal and check right check and accounting cut so for this I'm going to initialize a result variable right so let me first treat a special case if not root so it's possible due to the problem assumption so we're going to return zero and then we are going to consider generic case so we are going to initialize a result variable counting the sides so because the smallest stat is zero right so we initialize it with zero and then we are going to initialize a stack so we're going to do a pre-order so we're going to do a pre-order so we're going to do a pre-order traversal maybe so any traversal will be fine so for this problem so here well s so I'm going to get node equals s pop and then we are going to check if this tree represent by node is a valid balance surgery in other words we need to consider all of its specific names so if this is the case so result is going to be maximum of result and G node right we're going to count the number node so this is the case so this part actually is the problem logic so if we acknowledge this if then we check if node right so we are going to uh put this note right in into stack so if node left so we're going to append this to node left so this is the logic for pre-order traversal so afterwards so for pre-order traversal so afterwards so for pre-order traversal so afterwards so as we finish this well Loop so we can return a result state so this is the van v of doing the code so actually this is very we're both however if we could uh Implement all of this using um from scratch that's also a good thing so with that said let's first do a check yeah it passes the first example so now let's look at the second the generic case yeah it passes all the cases so now we have gained some intuition with the first this version of a code so now let's look at the second version I'm going to copy this function signature and change this one to be rewind and now let's look at here so the short version so for this um again I'm going to write a hyper function and then we're going to get the bonds of the banner Banner search tree corresponding to a node and also we want to count the number of nodes or the size of that Penance surgery so first let's write the hyper function so far this hyper function so I'm going to Define it as DFS maybe so I'm going to call it node so this function is going to return a number of informations three pieces of information first is the maximal BST set so in this in the tree represent band node maybe it's the set of the its submetry but that's that anyway the maximum BST size and another one is that the left bound if we look at this tree for this node and represent by this node and the red bound so similar as above but we need some special treatment to make connections first if not node so in this case so actually we shall return zero in other words there's the zero we regarded this one as a valid Banner surgery but the left bound will be um we're going to set it to be positive infinity and the red Bond the larger one we are going to set it to be negative Infinity so here the reason we set H to be positive infinity and negative Infinity so you can think of this corresponds to an empty set in mathematics then you can understand why we set it to be positive infinity and negative Infinity respectively so this corresponds to mean let's correspond to Max right or left lower bound or upper bounds so this is the case so next we're going to track the information for the left subtree and the rest of the battery so left super tree sides battery few sets and the left mean and the left Max that's going to be DFS note left and similarly we do for the right num number nodes so rich mean and the red Max is going to be DFS node right then we want to make connections for this two so we are going to check if node value is strictly in between the left mean left Max and the Army right so left Max are mean so in other words what we intended to incorporate is that the current node value is larger than the largest value in the leftover tree and less than the smallest value in the rest of the tree right in this case so we're going to get the size of the tree um it's going to be so this tree should be noted at node currently so 1 plus left number plus a red number and then we are going to set the Min and Max but notice that let's not guarantee that this tree whole tree is a binary search tree so we want to set mean to be the left mean and the node value similarly the max will be a red Max and node value so if we look at the else block then we could understand why we write like mean and Max here right so in other words if the tree rooted at node is not a banner search G still we can get the number of better maximum binary search size within this tree represented by the node so in other words the level three may contain valid balance surgery and the red subtree may contain the valid Banner search trick so in this case so we're going to have left number on number so the maximum so then we're going to set float next to infinity and float positive Infinity so notice that so if this true uh components in the return this negative infinity and positive Infinity it indicates that the current tree represented by the node is not a valid Banner search sheet so we write the left bond to be negative infinity and the red bound to be positive Infinity so this is to be distinguished with the first stop condition if we have an empty node a null tree so we regard it as a binary search tree however so here the number node is zero when the float the left bond is positive infinity and the red bond is negative Infinity so this way actually we can make this connected right so the thing is that you know if this condition holds and both the left subtree and the rest of the tree are not blood independent search tree so in this case we're going to have this in the left subtree our red symmetry left symmetry will have is the second component L Min will be negative Infinity so we get a negative Infinity here also and we get Max and positive Infinity here also it indicates that the tree at here is not valid panels to three so this way due to the use of properly setting of positive infinity and negative Infinity so we could mimic the Boolean function here in the first solution so the second solution format is very short so now with that done so we can do the function call and return so we just need to return a DFS root so we're going to return zero right so this second version actually is a compact format of the first version so with that said I guess we can do a check first yeah it passes the first example now let's look at the second example on the generic case it passes out cases so here up to now we finished the sharing of the two formats of a code or the two treatments so here before we end this video Let's Make A extension so in the problem so we are required to consider all of its dissonance in other words so we cannot cause the 10 and 15. so how about be relaxed or remove the assumption that uh we need uh we let's see this one right so uh if we remove this assumption then in example one the output should be five the largest Banner surgery will be uh rooted on 10 and the left subtree is marked by Blue and the rest of the tree will be start ending at 15 right so this is the 5. so can you tune or tweak the code to a red solution for the letter right so with that said I guess that's it about this video thank you
|
Largest BST Subtree
|
largest-bst-subtree
|
Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.
A **Binary Search Tree (BST)** is a tree in which all the nodes follow the below-mentioned properties:
* The left subtree values are less than the value of their parent (root) node's value.
* The right subtree values are greater than the value of their parent (root) node's value.
**Note:** A subtree must include all of its descendants.
**Example 1:**
**Input:** root = \[10,5,15,1,8,null,7\]
**Output:** 3
**Explanation:** The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
**Example 2:**
**Input:** root = \[4,2,7,2,3,5,null,2,null,null,null,null,null,1\]
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-104 <= Node.val <= 104`
**Follow up:** Can you figure out ways to solve it with `O(n)` time complexity?
|
You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
|
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
554 |
welcome to april's leco challenge today's problem is brick wall there is a brick wall in front of you the wall is rectangular and has several rows of bricks the bricks have the same height but different widths you want to draw a vertical line from the top to the bottom and cross the least bricks now the list of the brick walls represented by a list of rows and each row is a list of integers representing the width of each brick in this row from left to right now notice that the sum of the widths are all going to be the same because it's a rectangle now if your line goes through the edge of a brick then the brick is not considered as cross you can see if we have a line that goes through the edge that doesn't count it's only when the line goes in between the brick or through a brick that counts as a brick crossed so one thing is you cannot draw a line just along the vertical edges of the wall because that's obviously going to be zero so uh you know initially this problem is pretty intimidating and i felt rather foolish because my first attempt was to think about cr doing a nested for loop and checking every single line in between the ranges for the width of the column so let's check like here and check here and go just go down the line and each time like subtract see if the edge equals one if it does we can pop it off and just count up how many bricks we can do that but you know that approach this isn't going to work because it's very inefficient now one way to reframe this problem is rather than thinking about how can we minimize the number of bricks that we cross rather how can we maximize the number of edges that we cross or these little parts here and how do we know that well essentially let's say that we had this brick wall one of the ways we can think about this is it's really all these index numbers in between here that really count so since we don't know how far we've crossed so far like let's accumulate these values instead and see what this brings us so we can say one and then three and five six three four six 1 4 6 and just here basically what we're trying to check is these index numbers when it's 3 and this is 3 as well that essentially means that we're not crossing that's an edge and we can see that's true like here at three one two three this is an edge right so what we can do then is just accumulate all these numbers and just go through each row and count up the number of indexes in between from here to here and see which one is the maximum number because we want to find the maximum number of edges that we can get and then all we need to do is subtract the number of rows from the maximum number edges that we can find now hopefully that makes sense let's start off by initializing some variables we'll say m or actually n equals the length of wall and first thing we're going to do is create like a counter object let's create a default stick here now for row and wall we want to accumulate all these widths right and then we're going to add that to our counter object so um you could certainly you know do that in the wall itself but what i'm going to do is just create a previous value and say for brick in row we are going to add to our previous the value of the brick and then add this previous to the counter increase that by one and we'll do that for every single brick in every single row now all we need to do then is return the n which is the number of rows subtracted by the max of c dot values but there are a few edge cases here that's not going to work uh one of the things we realize is like since we're accumulating we're going to have six in each one of these so that's going to think like well we just go all the way to the end so we can't do that we have to skip that last break so to do that i'm just going to create say negative one and one more thing we have to note is if we had something like one like this is going to think um oh three is the next one we can cross here but that's not true it's actually going to be one right so uh basically if we have nothing in our counter object well i'm sorry it's not gonna be one it's gonna be three so we have nothing in our counter object it's actually just gonna be n so that's just kind of in edge case we have think about if not counterobject then return now let's see if this works looks like that's working so submit it there we go so accept it time complexity wise this is going to be well the number of bricks so it's n times m and we do have to use and i guess 10 times in space as well for this counter object now i realize i didn't explain this very well but hopefully this makes sense i would recommend kind of playing around with it uh yeah my first approach was definitely a lot more complicated than this but you know this is a lot simpler it makes a lot more sense so i think you know the big takeaway here is to always try to reframe the problem to simplify it okay thanks for watching my channel remember do not trust me i know nothing
|
Brick Wall
|
brick-wall
|
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_.
**Example 1:**
**Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\]
**Output:** 2
**Example 2:**
**Input:** wall = \[\[1\],\[1\],\[1\]\]
**Output:** 3
**Constraints:**
* `n == wall.length`
* `1 <= n <= 104`
* `1 <= wall[i].length <= 104`
* `1 <= sum(wall[i].length) <= 2 * 104`
* `sum(wall[i])` is the same for each row `i`.
* `1 <= wall[i][j] <= 231 - 1`
| null |
Array,Hash Table
|
Medium
|
2322
|
1,203 |
hey what's up guys chung here so today let's take a look at this hard lead called problem number one thousand two hundred and three stored items by groups respecting dependencies okay i think the name of the problem is a little bit confusing right so let's take a look what's this problem it's about so they're like n items and each items belonging to two m groups zero base m groups uh where group i is the group that ice item belongs to okay and if the item if this item doesn't belong to any group the value in the group array will be minus one okay and okay so both the items and the groups there are they're both zero index they're all zero based and the group can have no item belong belonging to it so and it asks you to return a sorted list of the items such that the items that belong to the same group are next to each other in the sorted list okay it means that even i if there's like there are like four items in the group one so all those four items should be together and not just that there's we also have like a before items list it defines some relationships between those items basically the before item is a list containing all the items that should come before the ice item in the sorted array and yeah and return any solution if there's more than one solution and return an empty list if there's no solution okay i guess this problem is already kind of confusing right because there are many basically there are like four inputs one two three and four and then in the end it asks you it asks us to return uh a single list here uh so first right so first one is this group here let's say for example we have a group here so the index means the group index okay it means that the first node does not belong to any group the second node same thing and the third item belongs to group one and the fourth one belongs to group zero and zero one zero and minus one okay so that's for the group one and this one before items basically the first one so item zero doesn't have any uh i mean dependencies basically right so if we draw like a graph here okay uh so at index one here an index one here so six has to be before the index one a six needs to be exist appear before one so it means that there's like a edge from six to one okay how about this one five needs to come five needs to appear and it needs to appear before two so we have a two to five sorry five to two and same thing six needs to need needs to appear before three so we have a three here okay now four three both three and six needs to uh appear before four so we have a four here and then we have a four and four okay as you can okay as you guys can see here so now we have a like a directed graph or you can call it dag directed acyclist graph okay i mean if it only asks you to find just to output the uh the nodes based on the sequence of the directed based on the dac here it will be a medium problem but what makes this one a hard problem is that on top of this layer here right we have another layer of the graph which is the group and what does it mean is the uh you know we cannot simply just uh do a topological sorting based on the graph here okay you know uh so currently we have a group here right so the group is like uh at so free in this example right the group six is belongs to group uh zero so six belong to group zero and the three is also zero four is also zero one belongs to group uh basically belongs to it to his own group okay and then five belongs to one to group one and two it also belongs to group one okay so that's why i mean the uh basically one of the example will be uh will be four from six three four since all three belongs to this all three belong to the same group that's why we have to output them all together okay and it means that we have to do a do the top logical sorting group by group okay and so in order to do that we have to uh create a hash table to store all the uh all the nodes for each group and within each group we'll do uh we'll basically will create like a helper function to sort do a topological sorting within that group and that's within the group right so but how about the uh then we also need to sort among the groups why is that because uh let's say we have a we have group so now we have a group one so this one here right for example here the one here this one has like let's say it had a group uh eight okay and in other in order to uh to get one basically we have to process uh group zero first so no matter what the group zero has to be processed before group one uh before group eight okay and within the group zero itself the order has to be uh six three and four okay so that's the sorted order in for group zero that's for group zero and for group one it has to be two a 25 okay that's for the group one and so here there's like group uh for example let's say there's a group eight here right so group eight is one and the group zero has to come has to be sorted before one but for the group one sorry the group zero has to be uh processed before group eight but for group one here it doesn't really matter it could be either at the beginning or at the end because group one does not depend on any other groups okay and every time we do a topological sortings right let's say when we sort the uh this group zero it also give us like another example here let's say uh let's say here let's see for example let's say the number three belongs to group not belongs to group zero let's say the number three uh belongs to group one okay then there will be a like a cycle basically why is that now the uh now the group one is depending on group zero but here see but uh here the group zero also depending on group one basically we are we're having like a cycle uh in terms of the group dependencies in that case we need to return the empty array okay cool so let's try to code these things up here okay and that's the first case scenario that will cause like uh a cycle which is the uh a cycle among the groups and the second one is within the group okay so let's say for example we have a i'm going to remove oops i'm going to remove these things here uh three still zero another one is that let if there's like if there's another ad from four to six okay you guys as you guys can see now we have another cycle within the group zero right and this will also be a invalid group so in this case we will also need to uh need to return an empty array okay and how do we check the cycle if the cycle exists in the graph basically we just do a topological sorting and in the end we check the length of our result if the result is the same as the number of the nodes if it is then we know there's like if it's the same then we know okay the valid there's no cycle but if the answer if the return list is smaller it's shorter than the than original list and then we know we have a cycle okay cool so the coding the amount of course will be a little bit more in the in this case uh but just stay with me okay so first like i said since we're going to do a topological sorting for both uh for both the group itself and among the groups and i'm going to create like a utility method just to do a topological sort and i'm going to pass three parameters first one is the nodes okay it's a node we're trying to sort do a topological sorting and the second one is a graph okay and the third one is it's in degree you know if you guys still don't know how to do a top logical sorting i suggest you to look at the wiki page basically the way we're doing the top logical sorting is we uh we're always starting from the zero in degree nodes and every time uh when we find uh i have seen like a zero in degree nodes we'll be re removing the edge from the graph which means it will be further for the neighbor nodes will be a decreasing the in degree for that target nodes by one and every time when we have a new in zero in degree node we add that to our queue we just keep doing that until the queue is empty okay so basically the queue will be the collections.dq uh collections.dq uh collections.dq uh so first i at the starting point the anything that's not in the graph that's any node that's not in the integrate will be the node that have that has the zero in degree okay for node in nodes if node not in degree okay so that's the first uh the starting point and like i said we're gonna have an answer great uh array here and then we just do a while loop here okay and current node equals to what it goes to q dot pop left okay and okay every time we pop a note we append it to the answer okay and then let's do a neighbor like in the graph okay current node and then we just decrease the in degree okay for this neighbors by one okay if the in degree if after decreasing by one if this thing is zero then we just uh append these things append the neighbor to the queue okay in the end we simply return the answer so that's the uh basically the topological sorting the helper functions now uh now let's do this let's try to uh create like a group items uh hash table so that we can group all the items for each group okay so we're gonna have like group items right in uh gonna be a default dictionary a list okay for i in range n okay and oh one more thing so as you guys can see we have we might have some other some items that has its own group yet it has it doesn't belong to any group but you know to help us solve uh solve this problem we're gonna give those items which has a group minus one its own group so uh we can give it any number right um but it cannot be the same but it cannot be duplic the same as the group from zero to m okay since we have uh we have zero to m minus one groups okay uh we can simply uh like group id okay we can do group id starting from m that will be sure uh those minus ones will have its own uh unique group id basically so if the uh the group i right is equal to my minus one then we know okay we need to create a new group for those uh group id um so the group i okay so the group i will be a group id basically where i mean if we don't do this right all those items they will be uh categorized with uh to the minus one group which is wrong that's why for each of them for each of the those separate items we're assigning a new group id to it and then every time we just do a group id plus one okay and then after that right the group ids the group items and then the value will be the group id okay and we do append pen i okay so this is a for loop here so not only we are like uh assigning the item to his group we also create a new group for those uh items that does not belong to any group okay and cool so that's that and now the second one will be we will be building the graph and integrate for the within each group okay graph let's call it item graph okay default list and then the item in degree default integer okay for uh v and u list okay u list in enumerate uh before for items okay so since the okay so the v is the okay so here it's like the edge is from u to v okay u and v right so that's how we uh how we usually define like edge basically you know the index would be the v okay and the value is the list of u right so that's why i mean for u in the u list okay so now here uh be careful here so now we are only trying to build the graph i mean within the group okay so which means let's say if we have a six three and four let's say this six and four belongs to group zero and uh number three belongs to group one then we don't want to like uh build the graph build a graph for the uh across different groups so basically we're building the graph only for the same group so that's why so if the group u is equal to the group v if that's the case we're gonna do a graph okay u dot append v okay so why is that because we only want to uh because later on when we process those nodes here since we since all the alternate items within the same group has to be together that's why we are we will not include this one otherwise it will give us like the wrong answer okay and then the item same thing the item in degree of the v will be increased by one okay cool so now we can process each groups we can do it to the topological sorting for each group so let's see how we can do it and um we have group items yeah so basically the way we're doing it we're gonna do a for phrase group for each group id okay for each group id in the group items right since we already built these group items so we just need to get all the list and sorted we're going to create a store sorted nodes sorted items okay equals to the topological sorting the nodes will be the group items with group id right that's our that's the total nodes we need okay and then the graph is the item graph and the integrate is also the item in degree okay so now we have sorted items here okay so now we can do a simple check here basically if the length of the sorted items it's not it does not equal to this length of the uh of the pass in nodes okay then we know there is a cycle okay we can simply return empty okay otherwise we just need to uh store those items okay yeah in order to store those items uh let's create another hash table here sorted group items okay because later on we'll be using this sorted group item to uh to construct our final answer so sorted group items you know so the key will be the group id the value will be the sorted items okay within each group okay so that's the sort the using each group now we need to sort uh we need to sort the do the sorting among groups so to do that we also need to build a graph okay now we have a group graph same thing for default list and then for group in degree ins so how can we build the group uh the groups right so same thing here we're gonna basically copy most of the things here basically we're gonna also do a v u list enumerate before items okay for you in you list okay if the group u is not the same as a group v okay basically if the edge comes coming from two different groups then we have a dependency right between the groups we what we have is we have the basically the group graph from group u okay to the group v okay and then we have a group in degree here of the group v okay plus one okay that's how we build the group graph and the group in integrate here and we need to do our sorted group here we need to do another topological sorting right uh by calling the topo logical sorting helper function here okay top of sort now the we need all the groups okay uh the groups will be uh okay yeah let's create the groups here so the groups will be what would be a set up the group of the group okay because at this moment right since we have already assigned each of the group here and basically we need the unique group id here right that's why we do a set we convert this group id because as you guys can see there are some like duplicated uh element in this group array here and we once we convert to a set now we have a unique groups here and then we have a group graph okay and the group in degree okay so after calling this here among groups we can do a simple check here right so same thing if we can we just check we just need to check if there's a cycle between the groups length of groups is not equal to the length of the sorted groups right then we also need to return like empty so if all this ta all this check passed now we know okay we can construct our final answer here so the answer will be that and i think we just need to loop through the groups okay for group id in sorted groups okay answer.extend right we groups okay answer.extend right we groups okay answer.extend right we simply extend that we extend what the uh we have a sorted group items because within each group we have already stored the sorted result into this hash table so we just need to get them out right group id and then we append those lists to the final answer and in the end we simply return the answer here yeah uh let's try to run it syntax arrow line 15 oh zero okay neighbor okay a typo here neighbor run default line 51 okay yeah i think because the code is kind of long so i have many uh typos here unharsh untouchable type list 970 solid group this id right sorry the group here and hash that's weird because this sorted group is the uh it's a list right and notes okay let's see so let's see unharshbot type list so it means that we have a list in here what are we returning here answer oh here so we should append the current node not the answer and that's why it instead of a note itself it's returning like a list because we are recursively like appending on this answer okay uh let's try to run this okay uh submit cool so it passed all right um yeah so basically this problem just to recap real quick so this problem is it's a hard problem and it's basically it has two layers two layer of like topological sortings and so first we create like a hyper functions to help us do the topological sortings uh for the given nodes the given graph and the given indegree and it returns the sorting topological sorting for the given for those given three uh inputs and then uh and then the next one basically we are a group items okay we group items into its own group so that we can use those uh the group items to do the topological sorting within the group and while we're doing that we're also like assigning those minus one group with its own group id okay so and then we're building like the graph for the for each group for the same group that's why we're doing this like the if check basically we're only uh we're only building a an edge if the from and the two are within the same group okay and then after that we for each of the group items itself we're doing like a topological sorting and after that we check if there's a cycle within each group if no we simply assign the result into this hash table so that later on we can use this one to build our final answer so that's uh to sort each within each group now the second one is we have to also sort uh among the groups that's why we're building like another set of the graph and in degree hash table and we're doing this we're looking through the before the related dependencies and now this time instead of checking if the group are the same we're checking if the group are different because if the group are different and then we have a dependency among the groups that's why we are adding the groups dependencies into the group graph also into the group integrate hash table and then now we just need to do a topological sorting right for all the groups if and then we just need we just check if there's like a cycle among the groups if everything works fine then we can simply uh construct our final answer based on the sorted groups and then for each of the group id we get the sorted result for this group and then in the end we simply return the answer cool i think that's pretty much it is i want to talk about for this problem yeah it's a good problem it's a good practice uh especially for the graph for building the graph and the first like using uh the topological sortings yeah i hope you guys uh like what like the videos and thank you so much and i'll be seeing you guys soon yeah bye
|
Sort Items by Groups Respecting Dependencies
|
print-in-order
|
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
* The items that belong to the same group are next to each other in the sorted list.
* There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item).
Return any solution if there is more than one solution and return an **empty list** if there is no solution.
**Example 1:**
**Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\]
**Output:** \[6,3,4,1,5,2,0,7\]
**Example 2:**
**Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\]
**Output:** \[\]
**Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
**Constraints:**
* `1 <= m <= n <= 3 * 104`
* `group.length == beforeItems.length == n`
* `-1 <= group[i] <= m - 1`
* `0 <= beforeItems[i].length <= n - 1`
* `0 <= beforeItems[i][j] <= n - 1`
* `i != beforeItems[i][j]`
* `beforeItems[i]` does not contain duplicates elements.
| null |
Concurrency
|
Easy
|
1187
|
746 |
hello everyone welcome to quartus camp we are at 7th day of june lead code challenge and the problem we are going to cover in this video is minimum cost climbing stairs so the input given here is an integer array cost which represents the cost to take each steps and we have to return the minimum cost to reach the top of the flow so now they have given that we can either start from the zeroth index or the zeroth step or from the first index or the first step and every time we can either take one step or two steps so let's understand this problem with an example so here is a given example the first stairs of course 10 let us have this as index 0 and the index 1 stairs is going to cost us 15 and index 2 stays gonna cost us 20 and we need to reach the top that is index 2 now so as per the problem statement we can either start from our index 0 or index 1. so let's consider first we are starting from our index 0. so now we have two options that is if we take 10 and step on to index 0 or we can directly step on to index 1 by taking 10 so consider we are taking 10 and stepping on index 0 so in that case we have to reach index 2 so we have to take if suppose we are taking only one step in that case so far the cost is going to be 10 and we are taking one step at a time and that is going to be 15 if we take 15 we can reach index 1 or index 2 directly so in that case let us consider we are taking two steps so we are taking another 15 which is going to cost us 25 to reach index 2. again if suppose we are going to take two steps at a time then in that case we can directly take 10 and reach to index 1 which is having the past 15 so now we are at index 1 so we need to so far the cost is 10 so we need to reach index 2 so to reach index 2 again we need to take another 20 so that the cost has become 30 now and finally coming to our solution we are not starting from our index 0 instead we are directly starting from our index one by taking 15 and we have two options we either step on index one or step one index two directly so by taking 15 we are going to step on index two directly where we have reached our top and the total cost is going to be 15 which is the minimum order of all so that is going to be your output so what we did here is we explored all possible options of taking either one step or two step also starting from an index 0 or index 1. so here we are doing the exhaustive solution that is trying out all the options available so if we want to perform the exhaustive solution that is considering all possible option and arriving at a solution there are only two ways to approach that either it can be a recursive solution or a dynamic programming so here the first intuitive solution for me was recursive valuation that is if suppose we want to reach our target which is the top of the step so to reach here we would have either used the previous step or last but one step that is consider if you want to reach the nth step that is the last step in the array then we would have reached here starting from n minus two step or n minus one step so we have only two options to reach this particular n if we are choosing either of this option which one would we choose we want to have a minimum cost here then of course we would be choosing whichever is the minimum cost either it is n minus 2 or n minus 1 and if we are stepping on this particular step then in that case we would choose cost of that step as well so overall we are going to pick the minimum of these two step plus the cost of the current step that is what the recurrence relation we are going to use so first let us go to the recursive solution and let's see how we going to further optimize it so before calling the recursive function let us write the function itself so i am first checking the base conditions so here we have checked whether we have only zero steps or only one step in that case we can take that cost alone and return it and we are getting into the recurrence relation where we are going to add the current cost of what has been passed as n plus minimum of min cost of cost comma n minus 1 min cost of n minus 2. so this is nothing but if suppose our n is our target that is the last element in our cast then we would have reached again from n minus 1 or n minus 2 so we are going to take which is the minimum step and add the current cost so once we choose the minimum step how did we reach to that step again it's n minus 1 and it's n minus 2 step would be considered so it is gonna call till we reach either the zeroth step or the first step so once we reach it is anyway gonna return it directly i hope you are understanding this part so from our main method we simply gonna call this recursive function so yes again from our main method we are calling min cost of n minus 1 and n minus 2. so this is going to be the overall code but this is definitely gonna time limit exit so let's run and try so yes as i said this is time limit exceeded because we are doing a repeated number of operations so let us implement a bit of memorization and let's check so to do memorization i'm gonna have a tp array which stores the pre-calculated tp array which stores the pre-calculated tp array which stores the pre-calculated values and whenever the value has been already calculated it is gonna return it simply instead of calling the recursive function so here instead of returning the value i'm gonna save that value in my dp so our computed value will be stored in our dp and finally i'm gonna return my dpa so here it is gonna check the default value of our integer array in java is gonna be zero so if suppose we have updated any value in dp it is not going to be 0. so we are going to check if dp of n is not equal to 0 then return the pre-computed value then return the pre-computed value then return the pre-computed value so yes this is this definitely will reduce our time so let's check so yes this solution is accepted and runs in two millisecond so this is actually the recursive function this is going to run in big o of n time but it is going to take the stack memory for calling a recursive function we can further reduce it by not having the recursive call you can further find a direct dp solution without using recursion just by iterating the given matrix but that is not my actual intuitive solution so this is what i had come up with when i saw this question and i hope this would be the intuitive solution to most of you all in a interview and this is going to work and bego of yen time and space complexity so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
1,870 |
hello everyone here is when Amazon welcome back uh today we have an exciting coding challenge to solve it's all about figuring out the minimum speed you need to reach your office on time given some constraints uh so uh sounds interesting so let's dive in here's the problem statement you have a floating Point number hour representing the amount of time you have to reach your office and together you must take and trains in a sequential order and the distance of each train right is given in an integer all right this so now each train can only depart at a integer hour so you may have to wait between each train ride the challenge is to return the minimum positive integer speed that all the train must travel at for you to reach the office at time or -1 if it's impossible I'm going to or -1 if it's impossible I'm going to or -1 if it's impossible I'm going to solve this problem using python so let's start with our a minimum speed of on time which take two parameter uh dist and hour and the first thing we do is Define a helper function can arrive on time and this function checks uh if we can arrive on time given a certain speed and it calculates the total time uh by adding up the time each train takes to reach the destination for all the trains except the last one and we round up the time taken to the nearest integer signs the train can only depart at integer hour so for the last train we simply divide the Distance by the speed and next we check if the total hour -1 is greater than the availability -1 is greater than the availability -1 is greater than the availability our or if the remaining time after each train right take one hour is less than or equal to zero uh if either of this condition is true it's impossible to reach the office on time so we'll return uh minus one so uh let's implement it we will have also one function helper so Dev can arrive on time of speed so it's return sum math sale D divided by speed for the in distance minus one plus this minus one divided by speed less power and now n will be Len of this and if n minus 1 greater than hour or hour minus n plus 1 Less Than Zero return minus one so we have minus one case and now so Left Right will be 1 and Max dist of math sale test -1 divided by hour minus n plus 1. so -1 divided by hour minus n plus 1. so -1 divided by hour minus n plus 1. so uh we return -1 and if it's possible to reach on time -1 and if it's possible to reach on time -1 and if it's possible to reach on time we perform a binary search to find the minimum speed and the lower bound is 1 and the upper bound is the maximum of the maximum distance and the tailing of the last distance divided by the remaining time so the binary search checks if we can arrive on time with the mid speed if we can we update the right bound to Mid otherwise we update the left one to Mid plus one so this process continue until we find the minimum speed uh yep so let's Implement our binary search so while left less than right meet left plus right divided by two and if can arrive on time meet right else left mid plus one and return left so okay so let's run for test cases to see if it's working yeah it's working and yeah so we use a binary search here for optimization and there you have it that's how we can solve this problem and the key idea here is to use binary search to find the minimum speed and a helper function to check if we can arrive on time with a given speed so it's a combination of much and a classic computer science technique so let's submit it also for and send test cases to verify everything's work okay so everything's work perfect and as you can see our implementation bit 94 with respect to runtime and also 92 with respect to memory so it's quite efficient and yeah also uh better than my first trial so my first code was uh 26 better than yeah bits 26 and 95 percent and I made a slight differences in code to achieve uh yeah better results so yeah first was accepted but it was uh like more uh knife implementation and now we have uh yeah good almost twice as fast implementation between 94 and 92 memory so it's both memory and time efficient so I hope you uh enjoy this video and found it helpful if you did don't forget to hit that like button and subscribe for more coding challenges and tutorials and keep practicing stay motivated happy coding and see you next time
|
Minimum Speed to Arrive on Time
|
minimum-speed-to-arrive-on-time
|
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
* For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark.
Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_.
Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**.
**Example 1:**
**Input:** dist = \[1,3,2\], hour = 6
**Output:** 1
**Explanation:** At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
**Example 2:**
**Input:** dist = \[1,3,2\], hour = 2.7
**Output:** 3
**Explanation:** At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
**Example 3:**
**Input:** dist = \[1,3,2\], hour = 1.9
**Output:** -1
**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 105`
* `1 <= dist[i] <= 105`
* `1 <= hour <= 109`
* There will be at most two digits after the decimal point in `hour`.
| null | null |
Medium
| null |
560 |
Hello guys welcome back to years and this video will see 10 years 12 time course problem wishes from list to day 2250 discarding challenge solve this problem can also be name discount number of marriage religious educational his so let's look at the problem statement latest Cigarette Wear Gravity Elements and Where Required to Find the Number of Various Weights Equal to Two K Values to Sit Equal to Two K Values to Sit Equal to Two K Values to Sit in Water with Answers in subscribe And subscribe The Amazing Just Element Simple Approach to Produce All Possible subscribe Quickly Calculate the Sum Value and Sacrifice Equals Two K Days of Idiots Grace Counter Initial 120 Initially and Keeping Created by One Value When You Find Assam Equals Two K So in This Way the Total Time Will Be Mode of End Cube Vikas Parishad Morning You Have to Find Assam and Saw This Will Also take water and answers-1 Will be thank you know how can we make a solution water and answers-1 Will be thank you know how can we make a solution water and answers-1 Will be thank you know how can we make a solution actually e request ou find some in giving subscribe The Channel Please subscribe and subscribe the Channel subscribe The Amazing Lets you want to know the value of the Jai Hind Desh Ke With Volume That I A Pointer Is Later To Enjoy Pointer 2012 09 May Suggestion Request Ooo Know How Can I Do It Obscene Divine Indicating Song From The 100 subscribe Video को - The From The 100 subscribe Video को - The From The 100 subscribe Video को - The Video then subscribe to the Page if you liked The Video then subscribe to top and assist the representation of algorithm for funding from iTunes j you can tell you something in the cases which will be free from 0 subscribe to come minus one in this way you will get the volume to the subscribe to the Page if you liked The Video then subscribe to The Amazing Calculated for Creating Possible Subscribe Chapter From Zero to 0.85 This At The Last Chapter From Zero to 0.85 This At The Last Chapter From Zero to 0.85 This At The Last Index So After Getting Lost In Thoughts You Have Quite Possible To They Are With Stockings Position 09 Covering All The Elements In This Post Element And You Will Need A To And You Will Keep You In This Way You Will Get All Possible Subscribe All Possible Positions Vibrating To You Can Just Ki Kasam Variable In 10 Inside Every Element Ki Movie The Value Of Solution A The solution is festival bluetooth setting open talk time solid possible to join the solution injustice single traversal so let's see what can we do for single traversal approach service science committee start at any point and at any point butter starting index zinc wishes for this is very obvious No matter what things need not to solve this single traversal so let's see who will start with a statement in more amount don't see the element and will keep updating the first half subscribe this Video Quest to zero and they will update you have increased value Pawan Singh dad veer he samiti ko shant but in this case this is not proven to give vent to the extent of but this element to the subscribe Video Subscribe Now You Can See Some Will Updates And 12210 Subscribe Now To Receive New Updates Subscribe 19 2012 This You Can See That Hui Hai V Savre With Just Single Element Poosam Is Equal To The Value Of Software Not Including This Know How Can We Go This Actually What We Can Do It And Karma Value Current Savya Ko 409 And Systematic Interview - K Time And Patience Systematic Interview - K Time And Patience Systematic Interview - K Time And Patience Subscribe NOW TO THIS CHANNEL SUBSCRIBE ALREADY ELEMENT KARE - To Be SUBSCRIBE ALREADY ELEMENT KARE - To Be SUBSCRIBE ALREADY ELEMENT KARE - To Be Presented Her Feet Swell Or Subscribe And Values In Excel Apna This Is What We Need This Subscribe And Values In Excel Apna This Is What We Need This Subscribe And Values In Excel Apna This Is What We Need This In Order To Make The Value To Current System Software Must Be The Element Or More Than The Element The Teacher morning which have in middle age this value tourist rape which they are now you can see the and do - key value is presents subscribe this one that subscribe now two comedy 2016 9 16th compete with 7 2009 table no will shift Is Present In December 06 2009 2013 - Sid 09 - K Is December 06 2009 2013 - Sid 09 - K Is December 06 2009 2013 - Sid 09 - K Is Presents Subscribe 90 To Subscribe Now To 999 - K - 727 Servi Subscribe And To 999 - K - 727 Servi Subscribe And To 999 - K - 727 Servi Subscribe And Subscribe The Channel Junior Suite Mix It Is From Zero Do E Know When Its Value Should Be In The World From Next Index Stud s Who This Period Cigarettes Illogical If You Think About It For Minute Pathetic Will Understand What Is The Do n't Know Sense Which Have This Will Create Account Value To Three Land Will Want To The Next Day This Will Give You Hundred Plus Points 8083 Is Not Between Equal To 70 1111 More Videos 000 Subscribe - 1111 More Videos 000 Subscribe - 1111 More Videos 000 Subscribe - Value From The Index Hui Hai Wah Savare Which Have Been Kasam Value Request K Sudhir And 2004 Subscribe School Will Update You Will Return Value With No Problem Travel Time Complexity Of Every Element Subscribe - Complexity Of Every Element Subscribe - Complexity Of Every Element Subscribe - S President of maintaining this water in which is the largest fresh water in just want to subscribe 500 will follow the same method I will start with us jor k value united 79 this is not a code to 7 - 09 2012 will just you and its not a code to 7 - 09 2012 will just you and its not a code to 7 - 09 2012 will just you and its account it Is the number of subscribe and subscirbe 9799800 present in and subscribe element which will compete with 6000 subscribe to * no before moving onto the next value will also inside this current * no before moving onto the next value will also inside this current * no before moving onto the next value will also inside this current time which sports in and its content 1512 next value which will compete with 9 2012 6 98100 Shyam Different Villages In This Way You Will Represent Subscribe To This Points Pet 3989 Taste K - K This Points Pet 3989 Taste K - K This Points Pet 3989 Taste K - K Absolutely 1111 Is Not Present In Map Of West In Dishas 80 Account Top 1000 2000 Representatives Trimendous Discount s on nov 10 2012 elements in Just one time Thursday Just once Total time complexity and subscribe Subscribe button is Kushwaha fast Ayo operation this and storing size Most powerful wealth creator map but incomplete subscribe The Channel account of all possible subscribe The Channel Evil returns for this thank you very simple and solution In different languages and share with solution In different languages and share with solution In different languages and share with everyone can benefit from like share and subscribe don't forget to subscribe the channel
|
Subarray Sum Equals K
|
subarray-sum-equals-k
|
Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`.
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 2
**Example 2:**
**Input:** nums = \[1,2,3\], k = 3
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-1000 <= nums[i] <= 1000`
* `-107 <= k <= 107`
|
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.
Can we use this property to optimize it.
|
Array,Hash Table,Prefix Sum
|
Medium
|
1,523,713,724,1016,1776,2211,2369
|
1,679 |
hey everybody this is larry this is day 18 of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom max number of k-sum pairs uh max number of k-sum pairs uh max number of k-sum pairs uh yeah so i usually uh read and try to solve these problems lives uh and explain these lives with my thought process so definitely if it's a little bit slow just fast forward through it uh okay cool so you're given an integer raised numbers and ninja k you can pick two numbers and you go to k n and we move them to wave return the maximum number of operations you can do underway okay so i think this is a little bit weird and a little bit tricky um the thing to notice about this problem and this is something that you're gonna have to um play around with similar problems and just if you're doing the problems you'll pick up on these things uh and it seems like i know it by uh but it's just from practice right and it is just that um if the two numbers that sums to k um you can't do this in a greedy way because um if two number like you know with a plus b is equal to some number c um a is you know a plus another number cannot equal to c right so that means that there is a unique matching between a b you know if you have a plus b he goes to c there's a unique pairing of a plus b for a given target k right um or c or whatever so knowing that's enough for us to do greedy um and as i said these are things that you know when you practice enough you can't notice these kind of i wouldn't say pattern or trick or whatever just observations um and that you know you're able to do that you know in a quicker way uh if not then you have to like convince yourself that this is true you have to play around with the numbers to convince yourself this is true um but this is something that you know if you've done enough problems if you do your homework and you do enough practice uh it is true um and because of that it is easy to come up with greedy because um why is it gritty because the only unique pairing is that you'll remove so that means that there's no real like there's no decision right you try to the only decision is either you remove it or you don't and because you want to remove them as much as possible um well that's greedy because it doesn't make sense to have a pair that you can remove and not remove because you're not saving them for later there's no decision there's no choice so yeah that's basically the idea um yeah and there are a lot of different ways to implement this i think uh you could probably do some sorting uh you could sort and then do like a two-pointed walk two-pointed walk two-pointed walk uh that's going to be analog again because of the sorting if it's already ordered then you can do it in um linear time but i'm going to put in the hash table which let's just say it is uh you know constant thing though i know that is a little bit more nuanced than that so that may be a little bit tricky but yeah so i'm going to just you know so you know in the hash table you could have something like you know that's just groups table which goes higher for um you know x is nums tables something like that right um so you can definitely do something like that uh i'm in python there's actually a little trick so i'm going to do it that way but um but know that you know so this actually puts everything in there for you uh kind of like this code i mean i'm just showing it and in a contest that's what i would do and this is what i would do right um but definitely on an interview just probably be safe and put in a for loop because then now you have to explain what a calendar does then you don't save time if you have to explain it anyway um okay and then now we want to find out the number k so then we just have to do it in a greedy way you could kind of you know you could do it however you like um i'm just gonna go with key by key in a weird way probably but it is just as easy as it goes so for um i was going to write a again okay but for a and table dot keys um so basically what we want to do is we want to find b right so b is equal to k minus a as we talk about because we want to do a plus b is equal to k so then okay and then the answer that we get from oh yeah let's have a um account just this is the answer that we're returning we return count yen and then the number of count we could do it one by one but the idea is that you know if you have multiple pairs then uh in a greedy way you just take the min of those um the two keys right there is one exception which we'll go over in a second right if you already thought about that then you know congrats you're ahead of me but uh you know um oh yeah so count we just it goes to the men of this um we're going to double count if because um you know a and b both appears in table so um so we just have to do something um we could do it in one or two ways we can either um you know we could manipulate the table to um you know like we could keep track of uh pair as you go to this pair table beam pair right uh and that should be good you could also just do another way of like you know if a is greater than b or something like that then you contain you because that means that we've already done it or something like that uh the different ways of doing it then the trick case of course is uh if k is even then you may have duplicate numbers right like for example everything is even in one of the cases yeah if this is six then you have two degrees so we just have to keep track of that so if a is equal to b um then and that means that you know it would only appear once anyway so then we do something like pair is equal to table of a uh mod two or divided by two sorry uh and then we do else this um that's weird uh and yeah and so this should roughly be right uh i hope so if not then i look like an idiot but that's fine uh but yeah now i'm just copying pasting the test case uh and hoping that i don't have a type or anything but oh yeah okay so that was one thing that i worried about um and the short reason is because uh using canvas that whatever uh this may actually create a table of thing um so we can just actually just get the keys uh manually which is fine and then just it'll wait for it oh because this is still an elevator now that we've converted to a list so that would we don't change that elevator as we go um yeah it looks good let's give it a submit hopefully i don't have a weird edge case okay cool uh yeah so what is the complexity of this um well you know we use a hash table and then for each of those key in the hash table which in the worst case could you could have n keys for uh a list of size n um so it's going to be linear times this is all constant um you know cos so given the n keys uh it's going to be linear time and in terms of space again because you have a hash table with n elements that's going to be of n space so linear time linear space um that's all i have for this problem i think it's kind of straightforward once you um practice the problems enough i think the hardest part is probably just coming up with the um you know convincing yourself that greedy is correct and you know i say this a lot on you know some of my other videos or whatever which is that you know with practice you are able to kind of get better at greedy type problems because you have already proved this in the past um like this a plus b k thing like you may you know you're not familiar with it if you didn't practice it earlier you might spend like 10 minutes like proving to yourself that's correct and that's okay because i probably have done it in the past uh and it's just that you know when you've done it a few times you know you remember it a little bit and you're just like okay i knew i know this to be true because i proved it a few times right so anyway uh yeah that's why i have uh me let me know what you think about this problem i will see you tomorrow bye
|
Max Number of K-Sum Pairs
|
shortest-subarray-to-be-removed-to-make-array-sorted
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109`
|
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
|
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
|
Medium
| null |
491 |
Peace be upon you, my dear friend. How are you? Today, God willing, we will solve the problem together. If you have not tried the problem, then you must first go and try to solve it yourself before you see the solution. Give yourself a chance to think about the problem and try it, and then keep returning to the video. The second problem will be solved completely. If You don't know what "tracking" means, If You don't know what "tracking" means, If You don't know what "tracking" means, so I will go and see an explanation of "tracking" and then I will go back to this will go and see an explanation of "tracking" and then I will go back to this will go and see an explanation of "tracking" and then I will go back to this video again so that we can solve the issue together. Okay, if you still know what "tracking" means, let's Okay, if you still know what "tracking" means, let's Okay, if you still know what "tracking" means, let's start. In the name of God, the first thing he tells you is that he will give you a voice called Nams. Okay. You are required to do this. If this condition is dead, there is no number after number that is less than it. It is not useful for this to remain like this. It is not useful for it to remain decrypting. For this reason, we will say that in this view, for example, if you have the number four in your number, it cannot come after five Syrians, it is useful to come after five, it cannot come. Then a number less than it means that five can come, or larger can come as four numbers. What is the matter? What does it mean? If you have an The normal elements are such that if you take four, it is useful to take any number after it, but it is not useful to take any number before it. Okay, so four, six, seven are useful, but six, four, seven, in this view, delete some elements from it that will remain, meaning you deleted this seven, so you will have the result if you delete this seven. It will result in four, six, seven, exactly. If you delete two numbers, you delete the 47, so you are left with six and seven. The six and seven work together, okay, 6 7, so the first six was, and in fact, Wednesday after that is six, and the six is greater six was, and in fact, Wednesday after that is six, and the six is greater six was, and in fact, Wednesday after that is six, and the six is greater than four. The second is four, six, seven, and so on, just fine if you look. For any reason, someone tells me, for example, that it is nice, I will tell him, “Okay, there is no problem.” He told me, “We said nice, I will tell him, “Okay, there is no problem.” He told me, “We said nice, I will tell him, “Okay, there is no problem.” He told me, “We said it means that if I delete any number from the village, or any number more than one number, what will result if we delete this seven?” It will produce four, delete this seven?” It will produce four, delete this seven?” It will produce four, six, seven, and this is Krazy. We have four, six, seven. Okay. I say. When you reach the question, you will find him telling you what, that he wants them to be completely different. He wants them to be folded. Okay, so you must. If you have a good delivery, okay, evening, this one will be like a chick. We will do it in a group. What does it mean? We will make a perfect package and filter it. I mean, we will answer everywhere and we will answer the questions. The question is, okay, what am I going to do? I will take the one as a start for you. Start or leave me empty. There is nothing wrong. After that, I will come and stop at the one that is this and I will say, oh, either I take the one, is it me? Now, ok, I will come at the first. I have two choices. Either I choose, ok, the first choice remains. When he took the one, okay, let's focus. I mean, right now, I was standing outside the village, okay. I came to the Nexus Zero and took it. Either I take the one, they take it. Okay. I come to the Nexus, the one that is this one, and I take his suit, for example, one, two, three. Okay. I now have two things in the first branch, Mum. I take both, oh, the one is done, I have finished working on it, oh, I take both, Eman, take it, okay. If I take both, I will still have one from the past. If we take it will remain the one, but okay. I was when one broke. I will go to the Index by two. Okay, so when I go to the Indian, continue. I had one, but I took the three. I took it, but it was not perfect. I still have something else. No, we still haven't finished working on it. Here I finished here the one, and here I did not take the one with me. Ok, beautiful. Here is the turn for the two. Oh, I took the two. It's fine. You will find that this is every casting of two parts. What can be from our village is one, it will be three, two, and one zero. It will be 30 o'clock. Who is one, two, one model, three, two, three, okay, three. You can get me any other pictures. It is impossible that you can from our village. Okay, and after I do that, what do I do after I get that every day? You will come out with me one, two, three, and I will see if the conditioner will be applied to it. I will see if it is krazing. If other than that, it will remain just like that, and I will also see if our holder is larger than one, not more than one. Okay, nice. Ok, can we do something else? Oh, can we do something else while we are doing something instead? We can continue, can we doubt? I mean, we are now entering the two. I mean, we are here working. As for the two, okay, if we are going to wrap the two, then we do not need to do anything. If we are going to talk about the two, then we can see what this two was before. There was one before it. It is fine. There was one before it. It is okay. If I put the two after it. The one in the patrick is ok. If we assume, for example, if this is a zero, ok, the zero is going to put a one on the one before it. Is there any need for me to continue and come in the end with a check, and in the end here is a check? No, there is no need. You are not here. Zero is ok and before you is a one. So you just spoiled me. The conditioning is perfect, and the generosity, the verse, and the saab will be okay. After that, these are the ones that Global introduced to me, because every time you can send them in the oven, you can take it from a prince’s mobile phone that you like. Make this good, this is good, and after that, the first thing to the last thing. Okay, I am completely wrong in terms of what, in terms of no, and I am the politician. Mine is bigger than this one. This is the second condition so that if I am like this, it is really fine. And after that, well, if I have not reached the last of the Quraish, then I will still have this condition. However, the current capacity of the Sequences is already completely empty. If the Sequences are completely empty, I will immediately enter and inform you of what this number will be. The number on which is the turn in the village is Suf. I mean, for example, I am currently standing at Index One, so I will make a push for Index One, but that's fine. If you know how to write these two lines, it won't take you a minute to understand. Okay, I'm right now. The So long, even though I don't even want, I do n't want the answers, I took a picture of him and he said to you, or the vector came back, tell me the order, okay, I will tell you that I did n't even do it because of the two pictures. I did it because if he remembers when we said we have it in the picture above, he doesn't remember three, six, seven, okay. So we said, if we target this seven, it will be three, six, seven. Well, if we are lucky, this seven will be three, six, seven. Okay, we want one of them, but ok, so I made six so that when I brush this vector on it will say okay, there is no problem. Okay, when I come to look at this vector, you will say, by God. Fine, and after I finish, I will do fine. It will be a Victor of Victor, because I did just that, fine, and I won. There is no problem. I hope you enjoyed and understood, and if there is anything you can write to me in the comments, God willing, I will reply to you. Hello. Peace be upon you.
|
Non-decreasing Subsequences
|
increasing-subsequences
|
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[4,6,7,7\]
**Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\]
**Example 2:**
**Input:** nums = \[4,4,3,2,1\]
**Output:** \[\[4,4\]\]
**Constraints:**
* `1 <= nums.length <= 15`
* `-100 <= nums[i] <= 100`
| null |
Array,Hash Table,Backtracking,Bit Manipulation
|
Medium
|
646
|
766 |
hey yo what's up my little coders let me show you in this tutorial how to solve the little question number 766 dopplex matrix basically we are given an m by n matrix and we need to return if this matrix is stoplets or not and the matrix is stoplets if every diagonal from top left to bottom right has the same elements here's our first example let's check all the diagonals from top left to bottom right in this case we can see that here for example we have one so all the elements are the same another diagonal two another one three and the last one is five and yeah as you can see in each diagonal all the vowels are the same that's why we just returned through in this case and yeah we don't care about these two values because they don't form any diagonals i mean they form some of them but we are interested only in the top left bottom right so we can just ignore them another example in this case we would return false because there is only one diagonal from top left to bottom right and here it is and you may see here that values are not the same and that's how you just return false in this case this is what we need to do guys let me just quickly write the code now and i will go with you through my solution and it will explain you everything just stay with me guys okey dokey my little coders here's our very short and very simple code just two four loops and one if statement this is all what we need to have basically we would iterate through our matrix and would check something right i actually prepared some pictures for you with some examples imagine that this is our input matrix that's the same matrix as from the first example we start at i is equal to zero and j is equal to zero this is our first iteration of this like nested for loop and we would have a check right if matrix at the current index is not equal to value at ios 1 and j plus 1 so in this case if these two values are not the same you just return 4 straight away but in this case these two values are the same this sub diagonal has the values which are the same in this case we just continue and would go on the next iteration of the for loop because j is equal to j plus j one so next iteration we check the next two elements they are the same that's great we don't return false so next iteration j plus and these two elements are also the same that's perfect but now because j is less than the matrix of zero the two x minus one basically this small forward would break and we would go to the next iteration of our bigger for loop and would increment our i volume we check the next two elements they are equal we continue next to elements they're also equal and because on the iteration before like in the beginning we've already checked if these two elements are the same and now we're checking if another two elements from the same diagonal are the same and because are these two are the same you already know that the whole diagonal has the elements which are the same so that's cool and then after that we'll go on the next iteration and we check the last values and because i is less than the matrix of links minus one this is this was our last iteration it would go outside the for loop and just would return true simply as dead guys if it like at any moment you know the two elements which are located in the subdiagonal if any of them would not be the same we just would return false straight away but because we checked all the elements and we identified that every diagonal from top left the bottom right has the same elements we just return true and that's basically it let me just run the code because i don't think that i have anything else to say code works let me submit if i submit i get 100 that's awesome simply as that here if you enjoyed this tutorial guys please give it a like and subscribe this is very important i also challenge your friends to see if they can solve this question or not and i will see you next video guys good luck
|
Toeplitz Matrix
|
flatten-a-multilevel-doubly-linked-list
|
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
"\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ".
In each diagonal all elements are the same, so the answer is True.
**Example 2:**
**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal "\[1, 2\] " has different elements.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 20`
* `0 <= matrix[i][j] <= 99`
**Follow up:**
* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
* What if the `matrix` is so large that you can only load up a partial row into the memory at once?
| null |
Linked List,Depth-First Search,Doubly-Linked List
|
Medium
|
114,1796
|
35 |
binary search is a concept that has a lot of applications one such problem on lead code search insert position explores some of this domain you are given a array of sorted integers and a target element if you can find this target element in the array you need to return its index otherwise you need to return the index where will this element go if you try to insert this element in the sorted array so let us see what we can do about it 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 go over some sample test cases next we will try to look at one of the most straightforward ways how you can approach this problem going forward i will tell you how to think about an optimal solution and then 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 let us try to first make sure that we understand the problem statement correctly so we are given a sorted array and a target element now if this target element is present in the array we need to return its index otherwise we need to return the index where this element would be inserted in the sorted array if you have to insert it so let us quickly look at some test cases to understand what it actually means let us look at our test case number one i have this sample array these are all my elements and these are the indices of the array right so one is at zero index and six is at index number 3 because arrays are 0 based indexing right now the target element given over here is 2. so what you need to do is you need to first search if 2 is present in the array you can't find 2 anywhere in this array right that means you have to insert it and you have to insert it at the correct position in the sorted array so what do you start from the first position c1 1 is smaller than 2 so nothing to do go ahead and you see the element number 3. now 3 is greater that means 2 have to compare between 1 and 3 and if you have to insert this element it will go at index number one right only then it will come after one and hence for test case number one this will be your answer similarly let us now look at test case number two i am taking the same array and this time my target element is one what do you need to do is you need to find this target element in this array you can find this element over here right and what is its index is 0. so for test case number 2 you need to return 0 as your answer because you were able to find this element similarly let us look at our test case number 3. once again our array is same and our target element is 4. if you try to search this element in the array you cannot find it right so what you have to do is you have to insert it at the correct position if you see 4 should come somewhere over here right between 3 and 5. so what is the index after 3 that would be this index right and this will be 2 so if 4 gets inserted between 3 and 5 that means at index 2 then it will be at the correct position so in this case 2 would be your answer now if this problem statement is clear to you feel free to try it out on your own otherwise let me show you what solutions i can offer let us say i have the sample array in front of me and i have a target element 16. now before optimizing the solution let us do a straightforward approach what comes to your mind the first approach that comes to my mind is that since this is a sorted array the smallest number would be on the left side and the largest number would be on the right side correct so if i try to traverse my array from left to right then i should see the elements in that order right smaller to largest so what i can do is i can start from the left most side and compare each element with my target element i see that 2 is smaller than 16 so i will move ahead 5 is smaller than 16 again move ahead 9 is smaller 11 is smaller 15 is smaller and then i see 17. so now you stop over here now think about it if your target element would have been 15 then you would have found 15 while going through the array right and then you can simply return this index as your answer because you need to return the index of the target element correct but you were unable to find 16 in the array right so where do you insert the element 16 it should come right after 15 right so it should come somewhere over here that means after the index 4 and after the index 4 the next index is 5. so in this case 5 will be your answer that means you have to insert the element 16 at position number 5. now this method works and it will give you a correct solution every time in fact it works in an order of n time complexity but according to this problem you need to find a faster approach what can you do about it let us try to see that let's say i have this sample array once again and this time my target element is 9. before trying to think about optimizing a solution think about what you are trying to optimize right now the time complexity that we just had was order of n right to make this program more efficient what could be a time complexity that is smaller than order of n and that would be order of log n correct and whenever you see a time complexity of log n the first thing that should come to your mind is the binary search algorithm because a binary first algorithm works on the divide and conquer strategy correct it will divide the problem into two halves at every step and then you can arrive at a solution this dividing will give you a log in time complexity so let us try to apply the binary search algorithm in this question itself for a binary search algorithm what do you have you will have three values right a high low and a mid so currently when you start performing binary search on this array the value of high would be 7 that is the last index and the value of low would be 0 that is the first index and to proceed with binary search what will you do you will find the middle value right now the middle value let's say is three so mid is three what do you do then you look at this middle value i find the value 11 and compare this value 11 with the target element since the target element is smaller than 11 that means that you can discard this part of the array correct so this will narrow down your search range now you only have to search in this half of the array what does that mean it means that you can change the value of high and the new value of high would be 3 that means we are looking in this sub array now once again perform a binary search your low is at 0 and your high is at 3. once you find out the middle value that would be 1 correct now look at this middle value it's 5 and compare it with the target element 9 is greater than 5 correct so once again you can narrow down your search and only look in the right sub array that means the value of low will change from 0 to 2. that means you are only looking in this sub array and if you perform binary search on this array once again you will be able to find out the target element and it will match so you can simply return the index 2 as your answer right now think about if your target element was 10 instead of 9 what would you have done then when you were iterating through this array and when you were performing a binary search you always found out two boundaries correct initially it was zero and the last element then you shortened it then it was zero and element number three and then going ahead you even shortened it to these two indices right so this way you are shortening your array and this will give you a login complexity if you cannot find the element let's say in this case you couldn't find the element number 10 then you have to insert this element somewhere right now the value of low is 2 and the value of high is 3 you know that 10 will come between 9 and 11. so what you can do is you can simply return low plus 1 as your answer because this way you can be sure that the element that you're trying to insert will be in that range now let us quickly see how you can do a dry run of this code on the left side of your screen you have the actual code to implement this solution and on the right i have this sample array and this target element which i will pass in as an input parameter to my function oh and by the way the complete code and its test cases are available on my github profile the link is in the description below so to start of binary search what do we initialize the low and high parameters correct so low gets initialized to 0 and high gets initialized to 4. then it's a very basic binary search algorithm so you will start a while loop and then you calculate the middle value your middle value will come out to be 2 then you compare this middle value to your target element if this matches well and good you simply return this index and this will be a case when you are returning the index of the target value if not what do you need to update your boundaries correct right now the middle value is 5 and your target element is 4 so you need to search in the left sub array right you will need to search in this part that means you are updating the value of hi to b2 now this while loop will run once again and it will try to search for the target element in this sub array moving on it will again find the middle value and that will change to 1. once again you will see if mid equals to target it does not match right so once again you will try to update the boundaries once again this loop will run and you will be unable to find the target value so this time again you will update the low boundary to mid plus 1 and this changes your value to 2 and you come out of the loop as soon as you come out you return the value low and this will be your answer so you are inserting the element at position number 2o the time complexity of this solution would be order of log n and the space complexity of this solution is order of 1 because we are not using any extra space i hope i was able to simplify the problem and its solution for you as per my final thoughts take a moment to realize how we took advantage of the binary search algorithm that is why i always say that whenever you are learning a new concept let us say you are learning about the counting fort algorithm it doesn't necessarily mean that this algorithm will only be used to sort some elements in an array similarly when you are learning about the binary search algorithm it is not necessary that you will get a straightforward question that hey solve this question using binary search or can you find an element using binary search you need to understand the concepts you need to see what elements are being used in this question for example we took advantage of the high and low pointers right you got a range and using that range you could narrow out your first target correct similarly try to understand these fundamental concepts they will surely help you out what other methods did you think of what problems did you face tell me everything in the comment 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 to help your video programming needs i am including a link in the description below in case you want to check it out 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 you want to learn next or rather what problem do you want me to solve next i'll certainly try to help you out until then see ya
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,187 |
Hai Gas Welcome To Me Youtube Channel Today We Are Going To Solve Date Daily Need Code Challenge And Today's Problem Name Is Make It Exactly Increasing Life You Add Integers And Errors To Written Minimum Number Of Operations Needed You Make Erawan Strictly Impressing In One Operation You can choose you in this is one is in this i in me are one and no date is k and this is k in me write 2 and do d assignment made d element of i = strictly increasing return -1 if you strictly increasing return -1 if you strictly increasing return -1 if you consider first example vich This is actually this and third value d number of operation on this how one example increasing what they can do is they can assign this second value on second value of are you tu d on second value are one and they can assign d on first value added you tu d third value and they can c d answer it because you perform tu operation tu make it display increase of d third example so in third example there is no way you make d arrival including let c replace d third value on are you d On second value are you give wood Wickham one three six seven and they are having you three and it is not strictly increasing it is also increasing but not strictly increasing and its replace five with one it bill it is not strictly increasing because they are having You once therefor there is no wait you make d example three are one also written by this so here they can actually solve this problem using d concept of dynamic programming but before d solution they have replaced d and remove duplicate elements in between There would be thoughts that it should be given more strictly, the value of K should be written more strictly, we should not iterate whatever duplicate value was there or whatever was the smallest, but if we had you present in this salted order, then I would just I could have said that if I had K plus, then J plus M is D, the size of error is M - 1, this is the M is D, the size of error is M - 1, this is the M is D, the size of error is M - 1, this is the index. I can assign any value here. If I had the right, then we would have had to completely complete the find. What are the possible value but if it we can get it just in cost and I bill which is well it which is right side of other tu object you have to just make d just find d possible number of elements from are at D Upcoming operations in a small time So we have been sorting it, now let's see removing it is duplicate like I have area and k plus one is also four on this so if I came here I assigned it to the index. So can I do whatever industrial on the left and right side is against it the day after tomorrow I cannot do that date same I have you remove duplicates advised I must be thinking that S plus index means positive values are also kept index means positive values are also kept index means positive values are also kept but actually all greater values It is kept but equity waali is also had a power due to which if by mistake I had assigned again to any further index which would be I Tu Late Se there then 4 and 4 Bear having tu times four it is not increasing. IT bill note remember so we will read to remove duplicates also so lineage also no and new additive would be what no but after removing after sorting and removing duplicates we will get that we have in new and remove duplicates no way can actually that dynamic programming solve this problem so Basically we have to create d piece state with d smallest state after sorting and removing duplicate dp tu edit size nothing index i bill b having number of rows what does it do d number of minimum number of operations required tu make me area let me repeat Which DP is sending, which is storing, stage, this one, the state, it represents, I have assigned the position value of error, you have performed and they can say date, they have changed d value index with d jet index value so like this. By doing what is it d minimum number of pressure required she is storing dp one of is dp tu of i bill disturbed so total minimum number change what does it mean how many minimum number of resistance will be required true date to make strictly increasing me element not changed they have not assigned other value from are you tu this me index will represent that dp tu of come so if you have status cleared but main dp one of i just but me dp tu of i bill one proceed per date So let me repeated very quickly so I dp one of I come this whole what is this d minimum number of this is required you make me are one strictly increasing from zero you just 35 and store it bill store number operation minimum number required you make me Are strictly increasing from they have not given above other value from are you tu this index so us this dp tu of represents problem because problem so let's talk about ho d dp one comma i comma related with that I have got strictly increasing other If I have replaced it then what can I say if I do n't have the first element which is not my first element then I can say how many operations will it take to do this particular operation internally on this D count, how many operations will it take to do this true date. I - 1 index also j - 1 I - 1 index also j - 1 I - 1 index also j - 1 value okay what is d minimum number of business period required you make me and this increasing and let me refer to it like this okay so how many operations will I have in this to do this thing I six raha hoon ki what are d minimum number of required tu show d tu make me arrival increasing zero tu i - show d tu make me arrival increasing zero tu i - show d tu make me arrival increasing zero tu i - 1 true date i have k - 1 true date i have k - 1 true date i have k - 1s value tu me i - 1 is value 1s value tu me i - 1 is value 1s value tu me i - 1 is value one so dp become of i - 1 J - 1 one so dp become of i - 1 J - 1 one so dp become of i - 1 J - 1 Oblivious will take and plus one and operation is on it d me last operation of assigning d tu object same i bill b greater give zero because of this zero will be so k minus one bill b - 1 zero because of this zero will be so k minus one bill b - 1 zero because of this zero will be so k minus one bill b - 1 date is out of d index from d lower Limit so that's why we are doing this to him I bill note change it this note change give what should I say minimum number of cash management right so now in these two which is the minimum of this comma BP of Icom what is this D DP one of I store if my Pass greater dene zero hai agar mere ko know aur aapne paas hoga aisa relate ho jaati hai let see ho can i relate me dp tu of aaye videesh mother program aur zero tu ai - 1 sir tha zero tu i self aur zero tu ai - 1 sir tha zero tu i self aur zero tu ai - 1 sir tha zero tu i self date me ice and thing so I know that in that which I have are here I have zero one you are in that I - 1 is one you are in that I - 1 is one you are in that I - 1 is indict hai -12 dp I change the index to anything can be from zero you and right image when I have that which are tube I am changing here DP one of I - 1 I can write n on do and I bill check this condition every time if me are you of j li dene are five give I bill se me DP you DP one of I - a bill se me DP you DP one of I - a bill se me DP you DP one of I - a Not only this, what we have to do is either this or the minimum meaning, I have to store here the total number of n, the value of k can be replaced with zero value of any, if any rate is kept increasing only change then any operation. If you have not performed and there is only one element, there is no element in front of it, then for that there is no need for me to perform Father of Perform, because if there is no element, then DP will now be zero, so this thing is already given to us in the base conditions. What have to be done next to that, so let's date along with a called, so what we have to do, so here we had done this condition to do the flower will come right and on D DP you will give IPL, after that I will have to do loop on him But what will I do after H value of BP will become full, DP will come off, so what will be my final answer, I have zero, till N-1 index, I will zero, till N-1 index, I will keep the value of N-1 unchanged as it was and I will get strictly increasing keep the value of N-1 unchanged as it was and I will get strictly increasing keep the value of N-1 unchanged as it was and I will get strictly increasing number. What will be the minimum number for this, zero you and minus one, if I get strictly increasing then minimum value of this and minimum of DP you times of DP one times so date bill be me answer but how have you removed duplicates if you have Whichever unique value will be there, we are doing 10 years from error you sorting we have already done if intx zero first element way have you it in I time specter if me are this not I - 1 it specter if me are this not I - 1 it specter if me are this not I - 1 it mains it is a unique element because way Have already if we had these duplicate elements then other tu n five bill b equals tu where so we pushed this but by doing this we will have all the sorted unique elements in type a date is d size of me transform and I new array her After I did the description which is DP station and D first row of RTP one bill b set which will be D elements in D first floor index we have them all I have made one side two fox on this part tu D comments because you get tu Optimize after that what is loaded tu file all d rest of d status tu one tu and -1 and from K d status tu one tu and -1 and from K d status tu one tu and -1 and from K equation zero tu m - 1 I have done this of two loops equation zero tu m - 1 I have done this of two loops equation zero tu m - 1 I have done this of two loops so phase one what was that DPO I repeat one of I Coma gk was storing that I am changing the element with l tu now j element right for that the functions I had for that were if this is greater give zero then this is what we have to do edwise we take the minimum of this so think I Bill Over Har Agar Apne Paas Ye Apne Paas Greater Than Zero Hai Student of I - 1 + 1 Date They Have Not Displaced So Let Me Discuss It Humne Jo Change Hai Change Kiya Hai But Hum Bol Rahe Ki Hum If you don't change I-1s, then Ki Hum If you don't change I-1s, then Ki Hum If you don't change I-1s, then how many minimum values were there in it? The voice how many minimum values were there in it? The voice how many minimum values were there in it? The voice was telling the thing that if you come to me, keep my changes and you make respiratory increasing DP, if you have I-1s and change, then I-1s and change, then I-1s and change, then I have you. Mere overall from zero tu i split ring one condition to hall honey chahiye na i - 1 hai date should be li dene i - 1 hai date should be li dene i - 1 hai date should be li dene change value of other tu of change right hoga agar late se mere paas are one of i - 1 strictly greater dene is i - 1 strictly greater dene is i - 1 strictly greater dene is equal Tu hota hai in de kaise ho it bill b ho are bill b from zero tu ke good best trick increasing nahi patna so that's why I have added this condition here so but no hope you get it of I ko fool We had discussed here, Hey 5 - 1 to 100 Apne Paas BP Tu Hey 5 - 1 to 100 Apne Paas BP Tu Hey 5 - 1 to 100 Apne Paas BP Tu complete minimum de raha hoon DP One of five minus one times of value is equal to you and > It is done Hey from one so equal to you and > It is done Hey from one so equal to you and > It is done Hey from one so for that all the values to come also > He will be for that all the values to come also > He will be for that all the values to come also > He will be if when se because erect with a short it so that's why I have broken right after date and after feeling d complete dp we know r answer bill b what minimum of dp tu times of and -1 tu times of and -1 tu times of and -1 minimum so initially I have answered DP, you have already done the times off and management and after that, the value of the child who is coming is from the last row of me, DP one, the value found for all of them is also from that, finally I have minimized the answer, all these The minimum amount will be finally stored in the answer after the date termination of this particular globe and we will return it. Here we have the code explained but if we submit it then it will be given to us clearly because it will look late at the time. Complexity Per This Part In D Problem Using D Say One More Time Order Time Complex You Bill B And In N In One More And It's Like And Times Of D Say Water And It Bill Be Around It Is Really Hi Time Complexity Per This See, what are we doing till I have all the valid values, where I have you sorted A, in that I have the value till G index which is smaller than the others, which is the minimum value among all those values. DP on off i2 We are comparing that with deadpool and finally we install that DPU right so if my how to know what is this d minimum value of DP one off i - 1 so d minimum value of DP one off i - 1 so d minimum value of DP one off i - 1 so now index a² 0 tu this valid index If I want then this will return me index is greater dan and equal but I just want smaller so its just first element will be there it has definitely oh one of such will be smaller so I did one more minus one so I need you check weather it is in d aa it is in d it is d valid index and note per date i use this condition after date i just used one condition again just tu close at weather me added tu to off index jo yahan pe kiya wo yahan pe IDFC ho Is it small No if it is small then I will store ppt final of dp tu of i d result minimum i and d minimum value of which d dp one of i - 1 from minimum value of which d dp one of i - 1 from minimum value of which d dp one of i - 1 from index zero tu k and in this particular how from india Tu history right, so what are we doing to that, we can actually store it, prefix off minimum actually casts any rectangle on any state, it is doing prefix and minimum come dp one off i mines one time bp one off. After replacing i - 1 302 nothing but minimum of prefix mail of a minus one comma bp s minimum distance this condition value has to be done here starting - if it has to be done - if it has to be done - if it has to be done now by doing this which is mine here which is on extra third. I had a friend, I do n't have to do that, I don't need to do that, instead I can find the valid index in time using lower bound, I can actually determine what is the minimum value of BP of I from within zero, you are valid. ID is just in constant time se thing perform date I was using a linear time now what will be the final time complexity and people with make of fan and this can be this canvas you satisfy this particular constant so thank you if you find this VIDEO HELPFUL PLEASE SUBSCRIBE TO ME YOUTUBE CHANNEL AND LIKE THIS VIDEO AND IF YOU HAVE OTHER FEEDBACK AND OTHER THINK IN WHICH I CAN IMPROVE YOU PLEASE TELL IT IN THE COMMENT AREA THANK YOU
|
Make Array Strictly Increasing
|
print-foobar-alternately
|
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9`
| null |
Concurrency
|
Medium
|
1203,1216
|
448 |
foreign in the range is from 1 to n and we have to return an array of all in pages in Arrangement when they do not appear in the given area so if you see the example the number ranging from 1 to 8 are given so 1 to 3 4 is present okay 5 is not present so that is my number so they can be have duplicates and they are non-sorted also and you could they are non-sorted also and you could they are non-sorted also and you could see one so what is the missing number you have next to this that is two so this is the question what is the approach to solve the problem so one major thing is you could just have the sorted version of the array so sort the array and in the each Loop just compare the index with the given element particularly if I say here is it should be actually zeroth index first two four five six seven so this is the limit Index right so compare whether index plus 1 equal to given number once you saw the array it will be in the format one two three will be one two three four seven eight check whether index plus one equal to first number yes it is 1 plus 0 plus 1 equal to one again check here next plus one two is equal to 2 yes index plus 1 3 is equal to three no please not equal to 3 then you have to move further again whether you have to check please message or not so but that is not the optimal one optimal solution so what other thing we can do within the array you can try to solve a problem so in the given question foreign will be 0 or not zero one two three four five six seven eight so we could see for the numbers which are not present in area 5 and 6 are not present in our instant they have just duplicated the given elements two and three two three separate base and our task is to find which element is which of the elements are missing in the given so these are the actual numbers and this is the given array so this is and this is what we need to find and this is the index so how do they do comparison now okay so first we have four first roof will start from four check okay now we have four right so four spirit is position actually this position so what we do is giving Mark the element in its index as negative so whichever element is present in Array we will Mark that particular index the element at the particular index is negative and after the loop the elements which are greater than 0 that will be the so now here we have four right so we will increase it so four means it should be over here in this position so we have to make this as minus 7. okay next so this position is nothing but index minus 1. so nums of index it is 4 minus 1. so in third index the number 4 should be the 8 because the indexing is starting from zero you have to give minus 1 that's it to shift that position by one so this will be minus seven next move three again numbers of index minus one it is 3 minus 1 2 so get the second position 3 should be there so we make this 2 as minus 2. next again move to next number minus two so we have minus two here how do you calculate the index signal minus 2 minus 1 is it okay no so what we have to take is every time you need to take absolute minus 3. now again an X position fine so this is 7 absolute of minus 1 7 minus 1 is 6 so at this position 7 should be less Exposition and it will make this 3 as minus three so how do you make pieces minus three minus of sums of I okay next again move further ahead we have 8 over here so 8 minus one will be seven so last index will become the element at this index will become minus one next again move ahead for two so two means it will work into this position 2 minus 1 will be one so here I could say it's already minus three so if I do again minus of numbers of I it will be it will become J but we should keep it as minus three how do I keep it so here also again we have to take the absolute foreign so next again move here so minus 3 well 3 would be 3 minus 1 2 and this equation solid minus two so absolute of minus 2 is 2 so with that again you do negation foreign greater than zero so these two numbers are greater than zero and we are having the numbers that is missing here five and six that is nothing but the given index plus 1 each other number is greater than zero you just add index plus 1 to the resultant vector or list in uh list to be using several Vector in the C plus so I'll click quickly program this so first we will write the result end okay next run and lesser than first let's say is write the size also foreign so first you have to check if first what we need to do we have to make the position as negation here so like we will write in index equal to absolute of numbers of I minus one okay so here you get the index in which indexing because if it's 4 minus 1 B 3 that is the index now at this particular index we have to negate the particular number so index will be equal to minus of absolute of amps of index if it is possible and it will be negative next again run the follow if any number that is greater than 0 then what should we do we have to push back the answer to the resulting Vector that is nothing but I plus 1 index Plus this is what I'm telling fire six so I knit last on the resultant vector okay just why did you write like this yeah vectorate yes I am for Java we will be using the list so this temperature resulted same index here math dot absolute function you have to use the result of add of I plus 1 so we'll submit this also yeah successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come with another video in the next section until then keep learning thank you
|
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
|
93 |
hello everyone welcome to Elko simplified let's solve today's lead code challenge that is restore IP addresses in this problem we are given a string as that contains only digits and we have to return all the possible valid IP addresses that can be formed by inserting dots into s so let me explain you we are given a string like this and now we have to form all the valid IP addresses so that they have some conditions met now I'll explain you those conditions and also how we will be solving it let's jump on to the algorithm part and the conditions part so in this problem we need to get four dots separated integers out of that string and the second condition is that it should be between 0 and 255. both the numbers inclusive and the third one is that no leading zeros should be present now from these conditions we can say that foreign since the number is always between 0 and 255 it means that it will always be a three digit number or less than three digit it can never be a four digit number because the smallest four digit number is 1000 which is always a greater than 255 so now we will always be having a number which is which has number of digits less than or equal to 3. and the second observation is that it should never start with leading zeros it means if it's a single digit number double digit number or triple digit number if it starts with zero or zero then this one will be valid because this is a single digit and it represents zero but these two are not valid because these starts with leading zero and it doesn't mean anything or either like this even then also it will not be a valid thing so the second thing is if it has two or three digits then it should never start with a zero so these are the two observations that we have made and we will use these while solving the problem so I will not be explaining these things again I'll be just using them now let's see if we have this string now we have to form all the valid integers which form the IP that is given in the condition so we have three possible things the first one is that we have to find all the possible IP thing IP addresses so the integers will always have a size greater than 0 or equal to 0 and less than or equal to 3 means the size will always be ranging between 0 to 3 so we can take all the possibilities and this is basically a backtracking problem while you just you can just think we take this two now 2 is a valid number so considering these two we will move ahead and considering this is the first integer of the IP address and then we will find the second one similarly third one and similarly fourth one or for the very first integer we can consider this 2 5 and then we can go for finding second third and fourth or we can consider this two five f as long as it is less than or equal to three digits and it has like it is a as long as it has like less than or equal to three digits and it lies within the valid index of the string so that's how we will do it this is basically a DFS based approach you can say like we will jump on to all the possible things possible ranges from a particular index and while considering that also so we will be using this DFS based approach now talking about the space complexity and time complexity so first talking about the time complexity since we have basically let's say we want to get n that is n numbers of dot separated integers then the time complexity would be we have three possibility then again we have three possibilities so it will be big of 3 raised to the power n which in this case since n is 4 it will be big of 1. now talking about the space complexity would be the same that is bigger of 3 raised to the power n which is for in this case is Big of 1 since n is 4. so that was all about the time and space complexity and as you may be not pretty clear with the DFS approach that I am talking about but you are going to understand it while coding it so now let's jump on to the code and understand this thing but before jumping on to the code let me just give you just like first we will consider these three possibilities and then we will jump on to the next possibilities so that you don't get confused while coding now let's get to get back to the code We have basically what we will do here is in this code we will store all the numbers in form of string that forms a valid IP address so this is for a particular IP address and we will store all the valid IP addresses into the string result now if the size of the string is less than 4 means it has one or two or three digits then it's never possible for us to separate four notes like it's never possible for us to make four dots separated integers out of three or two or one integer so we will directly return a empty array of string now we will call the function DFS starting from the very beginning index and giving S as in parameters input parameter and now we will I will return this result now this DFS function will do all the operation that is required in the problem statement so you have an index and given string now what we will be doing here is we will be going from index till index Plus 3. so here what we are doing is like since like just think we are at index 2 so we can go to three possible indexes either we are at the same index like at this particular index like only considering this two or we jump to the second and consider 2 5 as one of the integer or we jump to the third one and consider 255 as an integer so we will have three possibilities ranging from I equal to index till I equal to index plus 3 but there is one more thing what if we are at this particular index that is that has a value equal to 3 then we can only consider three and three five and after five we don't have anything if we just go to that index it will give us an error so we need to make sure that we don't go beyond the size of the array so we will take minimum of this and end and let me Define n as the size of the string okay now while iterating what we can do here is we will get a string which is basically starting from the index I and D till index I so make a substring starting from index till index so this is substring function it is a STL function and we have to give it two parameters the starting index and the size of this the substring that we want to get so it will start from IND and the size will be basically between I and I N basically between I and D and I so the size will be I minus I and D Plus 1. now we have to check whether it's valid or not based on the conditions so if the size of this string is greater than 1. and if the first the L the first digit is 0 or this like converting this string into integer using sty if it's greater than 255 then we will break we will jump out of the for Loop otherwise we will push this string into our IP Vector of string that is if we just get 2 5 then we will push this into our Vector 255 and then we will move ahead for finding the rest of the integers in the string from index I plus 1 so we will call this function with I plus 1 comma s and now since we have checked everything now just think like we are at this we have checked for 2 5 and we have considered 2 5 as a possible integer and then we have checked for the rest of the string now we come at two five so we need to take that 2 5 out of the vector so we will pop this the last element from the vector string Vector of string IP so basically we have done almost everything but now what's left is when will this function that this recursive function will end so for this to end we will add some conditions so we are forming when the moment we reach index that is equal to n like at the end and also we get a size of this IP as 4 because we get four valid indexes com and like we get four valid indexes and we have covered all the complete string like all the string elements like all the string integers all the integers that have been formed from this string are included in the result and this is only possible when we reach the end index and the size of the IP Vector of string is four it means we have we got four valid integer from this string and we have used the entire string we have U used each and every element from the string that moment we will just add all those integers with a DOT like we will separate we will make a string that is like let me do it then I'll tell you we will make a string temp and we will store all the so in this way what we will do while iterating through all the integer strings we will put this in our new string and also add a append it dot in this way we will get something like one dot now we have added an extra one so we will just pop this out and we will put this in our result so in this way we will do it now one more thing what if we don't reach the end but we have formed four valid IP addresses like four integers for the IP address that moment we have to return back because we cannot move ahead we have all we already have four integers we cannot move ahead and like for example we form two and then we have five and then we have two five and then we have one so it's not possible to append these three or five into this one because if we add one more three then it will exceed two five but we still have not reached the end of the string so if we have IP do i p dot PSI is greater than 4 we will probably return so in this way we will solve this problem let's run the test cases now so test cases are accepted let me submit this problem so the problem is accepted so thanks for watching the video do comment if you have any doubt please like And subscribe and share it with your friends thank you for watching I'll go simplify
|
Restore IP Addresses
|
restore-ip-addresses
|
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses.
Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.
**Example 1:**
**Input:** s = "25525511135 "
**Output:** \[ "255.255.11.135 ", "255.255.111.35 "\]
**Example 2:**
**Input:** s = "0000 "
**Output:** \[ "0.0.0.0 "\]
**Example 3:**
**Input:** s = "101023 "
**Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\]
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of digits only.
| null |
String,Backtracking
|
Medium
|
752
|
293 |
hey everybody this is Larry this is me doing week one of the premium weekly premium challenge in February hit the like button hit the Subscribe button join me on Discord let me know what you think about this one this is a Yeezy one according to them 293 Flip Game premium um I'm trying to think what I do maybe I won't do an extra one but yeah uh let's do it you're playing a flip game with your friend you're given a string current string with plus and minuses you are you and your friend take turns to F two consider plus to minus the game ends when a person can no longer make mov therefore the other person will be the winner we return all possible stat of current oh I don't I was going to have to get into like some uh game theory for this one but I guess it is a easy after I was like how do you how would I be able to explain a game theory problem uh in a Yeezy kind of thing and I'm like H but then it's just apparently return all possible States after return one red move and you can do in any order so this is just simulation right um I think the this is a really weird one only in terms of um space complexity and even time complexity right because the um because basically you're bounded by the output size I think that's the thing right and because the output size could be n Square um you know you're not going to do better than that even though in theory you can do like one scan and you do there are some tricks to kind of you know like you only need to count of number of possible outputs then of course you can do an all of n time all of n or you all of one space in that case but here because you're bounded by an O of n sare output U it's going to be n Square time n square space no matter what because I have to construct output so or like that's the lower Bound in either case um but yeah uh let's just scre it down and I don't think there's anything that tricky about it um if you really want to learn how this problem gets more interesting I think no me I'm not going to go over it this is a easy one so maybe another day uh but yeah but I is equal to plus and current state I + one I guess I could win this a I + one I guess I could win this a I + one I guess I could win this a little bit differently but whatever right um then we want so we have answer thing right and here we'll just use a slice notation in Python though I always get it wrong so uh let's see if I can get it right uh it's not clear to me that I can get this right but we'll see it's good practice though for me because it's not something that you want to do very often um these kind of string slice notations because it's usually not very efficient as I say because this is linear time um this complicated thing or this yeah looking thing is this is linear time linear space for this line and then you have a linear uh loop on it so yeah um yeah that's pretty much all I have 1402 day streak did I not submit the other one why did I why did the streak pop up here but yeah um that's pretty much it I don't know that there's anything much to explain definitely if you want me to explain this uh leave a comment and I'll try the best I don't know I mean I sometimes you know I don't know how to explain this like what I don't know uh yeah I just do what they tell you so anyway that's all I have for this one that's all I have for today let me know what you think have a great rest of the week of the month I'll see yall later and take care bye-bye
|
Flip Game
|
flip-game
|
You are playing a Flip Game with your friend.
You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make a move, and therefore the other person will be the winner.
Return all possible states of the string `currentState` after **one valid move**. You may return the answer in **any order**. If there is no valid move, return an empty list `[]`.
**Example 1:**
**Input:** currentState = "++++ "
**Output:** \[ "--++ ", "+--+ ", "++-- "\]
**Example 2:**
**Input:** currentState = "+ "
**Output:** \[\]
**Constraints:**
* `1 <= currentState.length <= 500`
* `currentState[i]` is either `'+'` or `'-'`.
| null |
String
|
Easy
|
294
|
1,913 |
okay let's try to solve L code problem number 19113 maximum product difference between two pairs now the product difference between two pairs a b and c d is defined as a into B minus C into D given an integer array nums choose any four distance indexes like WX y z such that the product difference between Pairs of nums W nums X nums Y and num Z is maximized so let's say now let's look at the example so 56274 we have given an array and the output is 34 now how do we calculate the output so we choose index number one and three so number one and number three and index 2 and four for choose the second pair is 2 and 4 now the product difference here is 6 into 7 - 2 into 4 = 34 the example so we into 7 - 2 into 4 = 34 the example so we into 7 - 2 into 4 = 34 the example so we have an array with elements 5 9 742 so here the maximum difference uh so here the maximum product of difference between two pairs that is uh 97 and 42 is 2 16 so if we choose these two indexes so our maximum product difference will be 16 so how do we now let's think of an approach so hence we know that we need two pairs two Max and two mean so what we can do is we can sort the array so the first approach is sorting now after sorting it will become 2 4 5 7 and 9 now we know that we have to take two small elements and two Max elements to find the maximum product difference so we can take these two elements and these two elements from the aray and we can return that difference so let's code it in JavaScript so we need to sort it so we can use nums of sort so here I'm getting the second last element and the last element from the array like the as these are the two Max elements and I'm just subtracting it to the two smaller elements now let's run it indeed the submission got submitted now let's try to think of second approach so as you already knew that we have to get two Max elements like Max One and Max 2 and two minimum elements Min one and Min 2 we can declare four variables take two of Min and two of Max and just subtract those so in the second approach we can use two Max variables let's call it Max one now I have these four variables so we can itot through the loop is greater than Max one that means we found our first Maximum element so we can now we have to first initialize Max 2 s Max one and nums of i s sorry and Max one NS of 5 now why we have declared this so we can maintain the previous Max element so we do not lose the track of previous Max element that's why we are doing Max 2al maximum now let's try to find second maximum element so else if nums of I is greater than Max 2 we know that we have found the second maximum element so we can initialize it with this now let's find minimum limit so if nums of I is less than me now we can use LF again nums I if it is smaller than nums Min of two that means we got our second minimum element so we can use Min to equals nums of I indeed the solution got submitted and the space complexity is order of one and the time complexity is just order of n because we are using a single for Loop thank you so much and I'll see you in the next
|
Maximum Product Difference Between Two Pairs
|
make-the-xor-of-all-segments-equal-to-zero
|
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
|
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
|
Array,Dynamic Programming,Bit Manipulation
|
Hard
| null |
456 |
Hello Hi Everyone Welcome To My Channel Today Problems 132 Pattern For Giving Energy Of Institutions Now 132 Pattern Subscribe I Challenge Se Zinc And Subscribe 4,320 Solution To This Subscribe 4,320 Solution To This Subscribe 4,320 Solution To This Problem Just A Great Life In Stolon Oil Is Equal To One To Neo4j Equal To Plus One to the best wishes for j&k subscribe And best wishes for j&k subscribe And best wishes for j&k subscribe And subscribe The Amazing will use this condition subscribe Video Solution is very short time complexity of dissolution of oo and distress complexities when big boss will not used any extra space suit how will father optimize solution so let's Disawar was the head and acts like a gradual hence no any minimum balance minimum right side dj sanjay seth vinut left side of villagers chaddi right side effect i.e. this chaddi right side effect i.e. this chaddi right side effect i.e. this week is the first president of exams is hanging in the middle of the number of which is great Anschaff's A 285 How they can solve this will update in is lies this loop condition from the requested one to end and exactly zero and will keep minimum left side minimum judge no first A and B rather update after doing checking these numbers of military grade one For you for J&K, for J&K, for J&K, follow-up of diet K and KM follow-up of diet K and KM follow-up of diet K and KM from Z plus one and witch acid will also be updated minimum to the meaning of the name of one sandesh solution dishes *Added for situation will go after one sandesh solution dishes *Added for situation will go after one sandesh solution dishes *Added for situation will go after any Score So Tight Crop Ko Dorsal 100 Heads Code Implementation Is Created This Left Minute Beach In Phone No. Follow Fauj Channel For K From 2nd subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our A Word Can We Father Optimizing Select try to understand more in detail show agency is stubborn minimum on the side of the Indian nation will give me no will to t&c is so let's say over here Vinodi minimum bestos the minimum of women from a minimum of twenty three minimum 10 minimum are from The what is the meaning of no subscribe here you know click subscribe button on the right side 2012 the great and the meaning of this current jain president jj is first grade minimum are satisfied nor the can no need to know right side value of j&k side value of j&k side value of j&k hai murshid great slow write value environment twelve and destroyed when is the meaning of i so what we will do i will user data structure stack hair soft it's there is no element which means accept doing nothing will start to where late so well fair from Hair to have less than one hair noida for and minimum over a good one and you see in first one other element which is the meaning of this country 12142 subscribe button and this vision for india will first subscribe key shopping of class tenth class no record If rather porn from distick under this is gold through all the states have no element benefit subscribe Video otherwise current element into its implementation please subscribe our channel subscribe 0 4 ki in tie request 111 and half inch plus meaning of i request to maths dot meaning Of meaning of river in the attack and the current president subscribe to The Amazing will create a step-by-step new rack a step-by-step new rack a step-by-step new rack A flat straight from point J is equal to minus one Ranger Greater Noida 20 - - to minus one Ranger Greater Noida 20 - - to minus one Ranger Greater Noida 20 - - subscribe And subscribe The Amazing is not to t&c not to t&c not to t&c A Wasted No Time To Time And Space Dot Element Is Duration And Quality Current Minimum Element Made The Current Affairs Quiz Page Elements Of Obscuritism That And Distinct Headquarters Pages Lunkaransar Beach Thursday Other Electronics Dots * Subscribe All Electronics Dots * Subscribe All Electronics Dots * Subscribe All It's Not Found In The Most Obscure Or That Soha Type O That Article Work That Station's Platform A Decade And C If It's Great Accepted 3761 Election What Is The Time Complexity Of Questions Page That Running The All Elements Which They Are All Elements Of Obscuritism Subscribe Boys Element First Step Hair Removing All Subscribe subscribe kare subscribe and subscribe the Channel Elements of Joint Kar Fennel 100 Grams Fennel Like This Video then subscribe To My Channel thanks for watching
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
145 |
hello guys and welcome back to my video series where I saw each one of leeco's problems going for the from the easy ones to the hard ones and now binary tree post order traversal and I have no idea what this is given the root of a binary tree return the post or the reversal of its nodes values this is similar to the previous one I just need to know what the post order traversal of its notes values means so I'm going to do exactly what I did before I'm going to Google it is defined as a type of tree which follows the Left Right root policy less subtraces travel first than the right sub tree finally the root node of the sub trees traversed all right so I guess that we can do recursion so if groups is none return empty array and now we return uh so it's left right roots so it's so Dot post order traversal of root dot left Plus root dot right Plus the dot value run accepted submit yeah okay pretty good I'm just going to submit again and see if the runtime gets better well it did get better the memory got worse well I'll take this as a victory was pretty simple hope you guys understood so if you I explained the recursion thing better on my previous video and this is pretty much the same as the previous one so go and check it bye guys
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
199 |
guys welcome to the channel this is waga we're going to do another leech good question and the question in question is number 199 binary tree right side view right so um what you what this question does or what it is it expects you to write to return the right most value values in a binary search tree right binary tree not binary search binary tree binary not binary such right so imagine you're a person here and looking at this binary search tree you're supposed to return the values that you can see and the values on the right obscure the values on the left so in this case you will have an output of one three four right but now there's one case where we should look at right now imagine if this five here had a left child like this five had a left child here let's say it had a six here so when you come to five here and you look you'd see a six if you are standing on the right because the six to the side here is not blocked by anything it would be added to our cube because you can see it right the only time you can't see a value is if it's obscured by another value on the side by a value on the right side right so we should um we should consider values that are obscured like this um also part right uh also part of our output right if there is no corresponding right side that could obscure it right so in this case how we would solve it is um let's just go to our rupple and um we would use level loaded reversal right so let's just get rid of this um get rid of this so we use level loaded reversal and the first thing we would do is let's write our numbers right um i don't know if i can shape it correctly so i have um we have a 1 here and we would have let's say a 2 here and then um would have uh um let's go to the next line and have let's say a five here and um let's have uh six here right and afterwards you could recreate this by coming here and making this um making this a three and um after that and after that coming here and um we could make this a four uh okay uh a four right so we have um an imagine um an example tree we could use right so the first thing we could do is we could come here and we could have maybe uh q which can be represented by q like so and um our results array which is going to have our results which we are going to return right so we start off at the root right we push in the root and um we put in the root in our q and we could have it here and the first thing we need to do is check whether or not um the root has children right now um we push the roots children we also have our results array like so we include the root first and then afterwards we check whether or not our root has children after i push the roots children and we need to push them in order remember um the children we put the left child and then the right child right so after this we push in our we remove our one and we put it in our results queue and our results array like so right and then before we remove our two we check whether or not two has children right so after that we come and we check and uh we do have um two does have a child right so two has a child and we put the child in there and now that we have two's child here we can remove it from our cue and we can come here get rid of it and we check does three have a child and the answer is yes we put the child in this case the child of three is going to be 4 and um we remove 4 from our q 3 from our q and we put it down here we can put it in our results array like so right and then before we remove 5 we check if it has kids a child nude rather and it terminates in six which is a leaf nude so we do include the child here so we have six here but uh we don't need five we remove it and we're gonna remove the coma also and we check does four have a child and the answer for that is four doesn't have a child it's a leaf nude so we just include it in our array like so and then we come down here to six and we check the six have um the six have a child no it's a leaf node and there's no right node obscuring it so we could have our number here it's going to be six so this would be if we run our code and this would be our answer and that is how the queue is going to operate so basically now that we have a conceptual overview of the question we can now put it in good the first thing we want to do is we want to create our results array which you're going to return so you're going to say res is going to be an empty array like so then we create our queue right and we could just call it q and um we can get it from collection let's just spell it correctly collections dot dq and what we need to add in is the root we start off with the root at the queue we can't just we can't start it empty so we can come to our loop and um we check that the queue is nonempty right while q so we check if it's nonempty uh we get the rightmost element and we put it in we get the rightmost element right first we say right is going to be none and then we get the length of the current q so that you can know how many things are there so we're going to say q len is going to be len q like that right and after that um we loop through right the elements currently in our queue right so we save for not gore for i in range and the range that you're looking at is qln the length of q right um we first put uh our leftmost node you know we pop off nodes from the left so put our leftmost node like when it starts one will be our leftmost node we put it in a variable right so we could say node is going to be um q dot pop left right so pop left like so it puts in the node and then um the node could be null right so we check fast if it has something we check if the node is non-null check if the node is non-null check if the node is non-null so we say if node and we put we assign the node to the right variable to the variable called right not to the right variable but you could say right is going to be node so we assign it there and um because we are sure that the node exists we can now append its children right and remember the order of a over pending is very important right we start with the left right so we say q dot append and what we want to append is the left node dot left and then we do the same for the right we say q dot append and what we want to prepare is the node dot right like so right so we have up appended the right and then we check if um our right is none empty so we say um this needs to be outside the for loop right so after the for loop is done we check if um if right and after that we just put it in our results variable right so we say res dot append and what we want to append is obviously um the right actually it's supposed to be right valuable value the value in the right so after that we should just return our array like so basically that our time complexity is going to be oven right because we uh we look through all the nodes in our array in our tree rather but then an array right so it's going to be oven and our space complexity worst case it's also oven because we create a structure that might be as long as our input array so basically that um thank you for watching subscribe to the channel and i'll see you in the next video
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
1,347 |
hey everyone today i'll be going over leak code 1347 minimum number of steps to make two strings anagram so we're given two strings basically and uh in one step you can choose any character of one string and replace it with another character so basically you have to count the minimum steps to make them equal by doing these replacements so just very simply let's take a test case as i always do and put it there so we have these two strings they're not anagrams yet so to be an anagram uh two words uh basically need to be uh structured in a way that you could shuffle them around to make them equal so what really what it means is do they have the same occurrence counts of each character so s here has two b's and one a and t here has two a's and one b so basically to make these equal we have to do this steps logic so we're trying to find the minimum number of steps so really all that we need to do here is just turn one of these a's into a b in t or one of these b's into an a and s either one worries so basically you could just uh replace that a with a b here and these are anagrams because see how now there is two b's one a here so these are now anagrams so it's one step and if we look over here in the example the output is one so it matches what we're expecting just by doing that on paper so basically now what we want to think about is how we're going to approach this so really all we need to do is count the occurrences in each anagram and the proof is if these are completely equal if the strings are completely equal or they already are anagrams the occurrences should be completely balanced so really we're just counting the characters that are unbalanced so to track the balance we're going to have a counts array so as normal uh we'll do a counts array of 26. now the reason why we do 26 here is because if we look down in the constraints uh these can only contain lowercase english letters so this 26 will just be the 26 lowercase english letters so next what we want to do is go through both strings simultaneously if we also look at the constraints uh these lengths will always be equal so we can make that assumption so let's go through them at the same time and we'll just do a simple for loop and basically we want to as i said we want to make sure that both of these strings are balanced and if they're completely balanced that means they already are anagrams so basically to track this balance we need to increment one of the streams counts and decrement the other stream count so we'll use s as the increment so let's go counts s dot car at i minus a plus now we do this because as i've said in another video maybe you haven't seen it basically if the characters a minus a will be zero so that'll be like mapping to 0 in this counts array so as i said we want to make sure the balance so we also want to do the same thing with decremented to t so see increment s decrement t so this will like track that balance so right here intuitively you can tell if these are anagrams this counts every single character should be zero because there will be an equilibrium like well plus and minus an equal number of times every single one should be zero so what does that tell you if they're not anagrams the ones that are non-zero anagrams the ones that are non-zero anagrams the ones that are non-zero means they're not balanced and we have to make some character swaps so let's have a result and let's return that result at the end and let's actually just do exactly what i said let's just count the character occurrences or the unbalanced characters and uh sum them up because those are the amount of steps that we'll have to make for those replacements so let's just go through each count and i'll make it count to be more clear and let's just sum them up so we'll go res plus equal count so the thing is that's tricky is that you want to do this but you can't really do it this way because some of these are going to be negative counts at the e if it's not balanced because some will be negative we really just want the positive ones so what we're really actually going to do is if count is greater than zero uh we'll go res plus equal count because really if we replace one of the characters we don't need to replace the other one because we could just uh make those characters equal so we don't actually need to account for every non-zero uh count just the positive ones non-zero uh count just the positive ones non-zero uh count just the positive ones let's run this and it looks like that's good let's submit this and yeah it looks like this is a pretty good interview solution uh now let's talk about time and space uh space is easy it's constant the reason being is the only space we use is this counts array and it's bound to a fixed constant value of 26 time is o n the reason being is we just have this loop here which is om and then we have this loop here which is uh o 26 or o of one or whatever simply because this is bound to that 26 value up here so really it's uh of one space o of n time where n is the length of s and t so yeah i hope this helped as i said this is a medium but it's really an easy problem so thank you for watching
|
Minimum Number of Steps to Make Two Strings Anagram
|
distance-to-a-cycle-in-undirected-graph
|
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**.
Return _the minimum number of steps_ to make `t` an anagram of `s`.
An **Anagram** of a string is a string that contains the same characters with a different (or the same) ordering.
**Example 1:**
**Input:** s = "bab ", t = "aba "
**Output:** 1
**Explanation:** Replace the first 'a' in t with b, t = "bba " which is anagram of s.
**Example 2:**
**Input:** s = "leetcode ", t = "practice "
**Output:** 5
**Explanation:** Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
**Example 3:**
**Input:** s = "anagram ", t = "mangaar "
**Output:** 0
**Explanation:** "anagram " and "mangaar " are anagrams.
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `s.length == t.length`
* `s` and `t` consist of lowercase English letters only.
|
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the node that was seen twice and all the nodes that we visited in between. Now that we know which nodes are part of the cycle, how can we find the distances? We can run a multi-source BFS starting from the nodes in the cycle and expanding outward.
|
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Hard
|
2218
|
424 |
everyone let's do lead code 424 longest repeating character replacement so we're given a string s which is composed of all uppercase English letters and an integer K we can choose any character in the string and change it to any other uppercase letter we can perform this operation at most K times and we want to find the longest possible uh substring that contains the same characters let's look at this example so we've got a b and we've got k equals to 2 we can replace two letters so it can either be a and we replace them with two Capital BS and the longest repeating characters here are all BS so the output is four we could also replace the two B's with two Capital A's and we would get the same result let's see how to solve this problem using a linear time solution so one way to solve this problem is to use something all sliding window so let's say we have a window of size three here there is a simple way that we can check whether one replacement is going to be enough to have the same characters in this subring so we want to take the length of our uh window so in this case is three and we want to subtract the occurrence of the most frequent character in this window so in this case it's b is appearing twice and 3 - 2 is it's b is appearing twice and 3 - 2 is it's b is appearing twice and 3 - 2 is 1 now we want to check is one less than or equal to K yes it is uh one replacement is going to be enough to make this window have the same characters so in this case uh we are going to have three Bs so you might be asking how could we take the frequency of the most frequent letter in the window and we can use a hash map for that and here we're using the most frequent ones because the number of Replacements is actually limited so we want to make sure that we're we going to substitute only the necessary characters in this case a is less frequent so we want to substitute a okay let's go through a complete example uh here on the right we've got the formula to see if a window is valid or not so I'm just going to leave it here so we're going to need two pointers left and right now we want to update the hashmap with the frequency of the characters appearing in this window in this case is just one a we want take the length of the window which is one subtract the most frequent character subtract the number of counts for the most frequent character in the window in this case is one the result is zero Which is less than or equal one so this is a valid window and we can update our Max so far which in this case is going to be one we are going to now move R so R is now going to be here we want to update our hasm with the right frequency so a is appearing twice the window length is two we want to subtract count of the character that is the most frequent one in this case it's a again same thing we want to update Max with the new longest character with the same elements in this case it's two R is going to be here we won't update our hash map the length is three but the most frequent character is still a so this is going to be 3 - 2 = to 1 which this is going to be 3 - 2 = to 1 which this is going to be 3 - 2 = to 1 which is still less or equal to K which in this case is one so is this valid window yes it is and it's of L three so we W update the max so far we're going to move R again we won't update the hash map so a is equal to three the window length is four minus the most frequent character which is still a this is still going to return as one which is still less or equal to K we are going to update our Max so far which is four now we want to update R again R is going to be here we want update our hashmap so we've got B appearing twice a three times so we're going to do the same thing uh we get the window length which is five minus the most frequent which is three 5 - 3 is two which is actually not three 5 - 3 is two which is actually not three 5 - 3 is two which is actually not a valid window because two is greater than one what we want to do is move L1 position so L is not going to be here and when we do that we actually want to also update our map a is now only appearing twice now let's actually calculate again if the window is valid take the length of the window which is going to be four m is the most frequent one as you can see both A and B appear twice so you can just choose either of them the result is equal to two which is still not valid so we want to move our L again L is now going to be here we want to update our frequency a is now appearing once we want to do the same thing now with the new windows length which is 3 - 2 which is 1 so this is which is 3 - 2 which is 1 so this is which is 3 - 2 which is 1 so this is valid the window length is three so it's not greater than four we are not going to update our Max we are actually going to move R Now by one more position first want to update the hashmap now B is appearing three times we are going to uh again calculate if the window is valid 4 - 3 which is 1 which is valid but still - 3 which is 1 which is valid but still - 3 which is 1 which is valid but still uh the max is again four which is the same so we're not going to update our Max we're going to move R by one position here the hashmap 2 and calculate whether the window is valid so it's 5 - 3 which is 2 window is valid so it's 5 - 3 which is 2 window is valid so it's 5 - 3 which is 2 so this is not valid we actually want to now move L by one position here and we want to update the frequency so in this case it's going to be two and two we take the window L which is 4 - 2 which take the window L which is 4 - 2 which take the window L which is 4 - 2 which is two so this is not valid again we now want to move left again so left is now going to be here we want to update the frequency so in this case we've got two BS and one a I'm going to continue over here so window length is three and the most frequent character is two so 3 - 2 most frequent character is two so 3 - 2 most frequent character is two so 3 - 2 is 1 which is a valid window in this case because it's smaller than K but the max of far is going to stay unchanged we can't move R anymore because we have reached the end so we can return our Max which is four and as you can see it also matches with the output of the example so this is how this algorithm works so the time complexity of this algorithm is Big O of N and the memory complexity is a constant so we are using a hashmap but this hashmap is going to contain maximum 26 entries because we are only counting the frequency of the letters that are appearing in our string and as the exercise said the only possible input characters are capital English letters which are from A to Z I hope this was clear okay let's try some code now the first thing we need is a hashmap to count the frequency of the characters appearing in the window next thing is a result variable that is going to contain our maximum so far we need the left pointer and the right point it is actually going to go all the way to the end of our input string we're going to use a four for that now we want to update our hashmap we take our character as key and then we just add one to it we're going to use get function from python so we can return a default value when you're first updating this entry now we want to check if the window is valid so we're going to use a while loop and in order to calculate the length of the window so we can use uh right minus left + one minus the right minus left + one minus the right minus left + one minus the frequency of the most frequent character and we can do it by using the max function and we want to check if this is greater than K it means that the window is not valid so we want to shrink the window so we're going to move our left pointer by one to the right but before doing that we actually want to update our hashmap with the new frequen here let's update our hashmap we know that the window is valid again we want to calculate the max maximum so far and we can simply do use the max function and here we're going to check whether the current window is actually greater than the maximum we already found earlier so once we have gone through all these operations we can simply return our result okay let's see if this works as you can see it does work please like And subscribe if you found this video useful thank you
|
Longest Repeating Character Replacement
|
longest-repeating-character-replacement
|
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest substring containing the same letter you can get after performing the above operations_.
**Example 1:**
**Input:** s = "ABAB ", k = 2
**Output:** 4
**Explanation:** Replace the two 'A's with two 'B's or vice versa.
**Example 2:**
**Input:** s = "AABABBA ", k = 1
**Output:** 4
**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ".
The substring "BBBB " has the longest repeating letters, which is 4.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only uppercase English letters.
* `0 <= k <= s.length`
| null |
Hash Table,String,Sliding Window
|
Medium
|
340,1046,2119,2134,2319
|
288 |
good evening and welcome to my channel welcome back to my channel and thank you for watching keep watching my video and today is lethal time again and before i dab into the problem i first will uh i first want to introduce a really good solving problem method metal name is yellow dark muscle the chinese name is and so what's the meaning of yellow dark muscle so uh so mess up yeah what's the meaning it's mean that when you're start at something you'll find you just try to and look around like some little sort of like it's a yellow dark like when you take the take a shower and you can put the yellow duck right you get some something similar to the yellow dark and talk to the yellow dog and like everything you are really confusing you bring and you just you confusing and you talk to the dark and after you talk to the dark you figure out the way to solve the problem it's like the magic so and it's it sounds like really but it's really weird because today like i start i really start off one of my projects to processing uh data is just a mess and i just keep to talk to myself and i actually what i'm doing is i open the camera and i talk to the camera okay over here a thing okay here and eventually i solved the problem so that is why i want to talk to you guys this month so today because i just using it today and it's work okay it's now let's do in delete code today i also use the same way to picking the little problem is a pick one like the little to randomly pick one to me and today the problem is 2a unique word abbreviation let me first um turn on my recording is here okay cool let's first dive into the problem um so this is a medium this is a little medium problem and the problem name is unique word abbreviation so what is abbreviation the abbreviation of a word is a concatenation of its first letter the word the number of characters between the first and the last letter and its last letter so if a word have only two characters then it is an abbreviation of itself so it's so confusing let's look at some examples so dog the abbreviation of it is d1g that's because one only one uh character is uh only one character is all that between the first character and the last character so that's why d1g okay and the second one is like in something and it's i 18 and that's because okay here between i and n there have 18 uh character between them so that is why i 18n okay and i t is i t because any words with only two criteria is an abbreviation of itself okay cool and so what this problem want us to do is implement a valid word a break class and it should initialize the object with a dictionary a word so here this class is do the initialization and this class is given a dictionary and i and the dictionary is let's see some example input it's just okay so the dictionary is a list of the at least a list of words so here let's see the include is something like this okay and for the is need this method the input is a word and we should and let's see because the output is the boolean value so we need to figure out when is reason true when circumference so it says there's only two way like there's only two condition which would return true the first condition is there's no word in the dictionary whose abbreviation is equal to the worst operation okay so let's returned one is written true and it's written true the first one is the worst this words abbreviation so we see the check word the agree abbreviation this word abbreviation and we can and we cannot find any like this dictionary also like in this dictionary also we have a list of variation right so this word abbreviation is not in the this aboriginal list then we should return true that is the first k like the first in the meaning and the second one let's see what they want the second one is for any words in dictionary whose abbreviation is equal to the word's abbreviation and the word are the thing so the meaning is for any word in the dictionary is for any word in basic dictionary and we first should force a list of this abbreviation let's see let's just please here this one is d to r and this one is d to r this one is c to e this one is c to d so we got a list of variation right and the new words also have abbreviation so here let's just um give use this example d-e-a-r so use this example d-e-a-r so use this example d-e-a-r so e-a-r the new word variation is d e-a-r the new word variation is d e-a-r the new word variation is d to r and so if the new word of variation uh so if the new operation is same as like this operation and okay here is same and only that meaning is like that word and that was same and also it's like so in this case this d a r and we have a d to our here we also have t d2r here so one of d2 r is a d e r one is d two r is d o r um and both is not same and i think this is the first case it should return true but the second case is like i think now i understand what the second case is meaning is mean like we're given a word like for example let me find the example it's like for example we get the card we give a card and the card is contained it is already contained like in this list right and in this case we should return true because the card already contained its list and also card is the only word in this uh in this dictionary that held the abbreviate as a variation of c to d so we can contain true if we have another word somewhere like c some see some d i don't know and then we'll have two will have two words in the dictionary have c two d in this case we should return false so like now we are clear the second case is like we need to make sure in this dictionary we have the word and this is the only word and also for the this is the only word like how this have this uh abbreviation okay so i think because the number of the abbreviation really mattered because we the second case actually set the uh restriction for that so uh i think i should use a hash map definitely should use a hashmap to uh let me hush my string and also uh i need another disk structure to store like uh the relation between the abbreviation and the words have this abbreviation so for the key i will put for the abbreviation and for the value i think i would choose uh another zero structure just like array but actually i want to choose that because actually we don't need to like we don't need to contain the same word right so i use the hash set okay i just use a set to contain the string okay cool and this is the map and the new hash map okay now we yeah i think that is the only uh digital structure we should use and we said that we also like because it definitely we will always check a words abbreviation so i will create another function the function name is uh it should return string and the name is abbreviation and how to spell variation and what the function doing is i give i given a word and it will return the operation of the word so what i'm doing view um so i first check if word dot laws is um equal to two if uh if is less of less or equal to two if it is i just return the word and another case just like i check for in opera i equal to zero i plus oh what i'm doing okay actually okay i first i was like let you guess what i'm doing but i just think i just come out a new like easy way to do that i want to do is because we need to return uh return something like the first character of the word something like a string and hero of first character word and also a number of the uh the distance between the first and the last and then the last character so what i'm doing is i want to iteration from for the words from the index one to the index uh words of lens minors too but and then i want to use like something like the count to count the number between the one and the length minus two but i just figure out like the number i just can get from the index right so that means the intact count is just uh is equal to the word that lungs minus one right i think that is and then we just return the word the character char height 0 plus we need to um we need to convert the integer to a string so we should do the string in the last one or the chart at this should be the word minor one right yes it looks good so let's delete this stuff so this is the abbreviation and now let's just go to the this one so valid word abray so we got a dictionary we want to for this function is just go leave easily do iteration for all the word in the dictionary and update to our map so i will do um for i equal to zero i less than dictionary the loans and i plus boss and i will get a string is current word is equal to the dictionary and also i got a brie by our function here is unique and our design is unique it's a free the asian abbreviation uh word and we got a word and then we get the current set is set um you new currency set what new currency you have said sorry you hush set your heart says yes and we make out the current set we update our current set.add we update our current set.add we update our current set.add and which word and then after that we update our map method and put this in here okay we update our current key current abbreviation with a new word yes and after that after the iteration over already finished our preparation part so now let's go to our is unique so we got a new word but first check the first condition is just check if the map have the this have this key so we just check if the map dot contain key um but we first need to get its abbreviation right so the vibration is stream of three is the free asian of the word and then we check if map have this abbreviation and if it don't have the abbreviation we can directly return to right and but if it has a variation we need to make sure the operation only have one word inside here and also the one word is the one where we input here so we check if the um if the we need to get the set right get the preset is mapped prepare for the set we get a set currently set equal to map so a free variation and we check if the current set the size make sure it says equal to one also so kindness that dog contains it's a word and if it's true just research and the elves will return of course i hope there's nothing wrong with my clothes looks good and that's runny this is working yes it's working it's a meeting nice uh so for this problem um i think it's not that hard it just the description is a little bit confusing and so for the time complexity uh for the time complexity i think it is like we only actually we don't only do uh iteration here for preparation so here should be uh o n right and for the is unique part for here is unique part actually um we use the hashmap as a contain key message it is in the constant time so here is a one and here also is 01 because this operation we just get the render index right so the overall time complecity should be open and for the space complecity we use a actual space to store our data structure the map so the space also should be a linear space yeah so that is today's problem and i hope you like the video and please let me know if you find something um something not correct during my explanation and or you have any new idea to solve the problem in your battery and just comment under my video and i hope you like the video and see you guys later bye okay let me stop the recording how to stop the recording nice goodbye
|
Unique Word Abbreviation
|
unique-word-abbreviation
|
The **abbreviation** of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an **abbreviation** of itself.
For example:
* `dog --> d1g` because there is one letter between the first letter `'d'` and the last letter `'g'`.
* `internationalization --> i18n` because there are 18 letters between the first letter `'i'` and the last letter `'n'`.
* `it --> it` because any word with only two characters is an **abbreviation** of itself.
Implement the `ValidWordAbbr` class:
* `ValidWordAbbr(String[] dictionary)` Initializes the object with a `dictionary` of words.
* `boolean isUnique(string word)` Returns `true` if **either** of the following conditions are met (otherwise returns `false`):
* There is no word in `dictionary` whose **abbreviation** is equal to `word`'s **abbreviation**.
* For any word in `dictionary` whose **abbreviation** is equal to `word`'s **abbreviation**, that word and `word` are **the same**.
**Example 1:**
**Input**
\[ "ValidWordAbbr ", "isUnique ", "isUnique ", "isUnique ", "isUnique ", "isUnique "\]
\[\[\[ "deer ", "door ", "cake ", "card "\]\], \[ "dear "\], \[ "cart "\], \[ "cane "\], \[ "make "\], \[ "cake "\]\]
**Output**
\[null, false, true, false, true, true\]
**Explanation**
ValidWordAbbr validWordAbbr = new ValidWordAbbr(\[ "deer ", "door ", "cake ", "card "\]);
validWordAbbr.isUnique( "dear "); // return false, dictionary word "deer " and word "dear " have the same abbreviation "d2r " but are not the same.
validWordAbbr.isUnique( "cart "); // return true, no words in the dictionary have the abbreviation "c2t ".
validWordAbbr.isUnique( "cane "); // return false, dictionary word "cake " and word "cane " have the same abbreviation "c2e " but are not the same.
validWordAbbr.isUnique( "make "); // return true, no words in the dictionary have the abbreviation "m2e ".
validWordAbbr.isUnique( "cake "); // return true, because "cake " is already in the dictionary and no other word in the dictionary has "c2e " abbreviation.
**Constraints:**
* `1 <= dictionary.length <= 3 * 104`
* `1 <= dictionary[i].length <= 20`
* `dictionary[i]` consists of lowercase English letters.
* `1 <= word.length <= 20`
* `word` consists of lowercase English letters.
* At most `5000` calls will be made to `isUnique`.
| null |
Array,Hash Table,String,Design
|
Medium
|
170,320
|
20 |
this is the 20th Elite code Challenge and it is called valid parentheses given a string s containing just the characters parentheses curly braces and square braces determine if the input string is valid an input string is valid if the Open brackets must be closed by the same type of brackets Open brackets must be closed in the correct order every closed bracket has a corresponding Open Bracket or the same type so for parentheses that is true this is true and this is false so the length of the string can be anywhere from 1 to 10 000 and it only consists of these type of parentheses okay I'll go get the project set up okay so my thoughts for this is we can use a stack which we add the opening parentheses into and then when there's a closing one we check to see if that matches the one at the top if it does then we remove it if it doesn't then obviously it's not valid and then when we've gone through every character in the string we can check to see if it there's anything left in the stack if it is then it's invalid so I've never actually used Stacks so this would be interesting to do so we got new stack here we will do for each class C and string we'll do if C yeah sure let's do this because it's nice and quick if it equals that or C equals curly brace opening or Square yep push the so adding that there else if C equals closing how do we get from the top that's what I want to know Pop I assume yep so actually it would be else wow opening equals pop we will do if opening equals that and see does not equal Closing one or just do the same thing with curly brace and then same thing with square brackets I've got that pipe so if none of roping wrinkles this one but it doesn't exist then we returned false it would have I only need to do one equals it's written false and that's fine then at the bottom we do if it's greater than zero returned false otherwise return true okay I think that's all that needs to be done so let's run it apparently there was an error what did I do wrong oh whoops this is meant to be outside like that now we run it okay so we can see we got true and false so it seems to be working so let's copy this and put it into lead code we'll do the test ones first just to verify that's all good yep those came up and not submit okay we've got an error here stack empty okay we didn't think about that so we will go here belts would it if open parentheses dot count equals zero return false let's just copy and paste that into here because it's nice and quick and now let's retry it yep so that's the solution to the 20th Challenge on leak code which is valid parentheses if you like this video make sure to like And subscribe
|
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
|
59 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Spiral Matrix To Give Positive Veeravansh 2ND Year In Spider-Man Positive Veeravansh 2ND Year In Spider-Man Positive Veeravansh 2ND Year In Spider-Man Subscribe And Elements Of Obscuritism 123456789 Will Solve Problems Will U Will Go Through Subscribe To That Buffalo Life Rear Seat Matrix And Start From This Point From My Point Of Order Top 1.5 Point Of Order Top 1.5 Point Of Order Top 1.5 Stop Processes For The Bottom Which That Time And Another Is From Left Which Will Left Uttar Pradesh Lepton Hair From Years Will Have Right To Left And Right Will Attract Dip Column Number Wild Top And Bottom Track Number Tele Top 10 End Left 2051 Subscribe Know What Will U Will Use This Less Hair 100 Blouse Paper Value In His Life From One Schezwan Cent Uttar Pradesh Will Be Our Vaikuntha Vitamin A Delight Morning Run From Where Will Start From Fear And For This Top Road will all columns from left to right one to three loot will prevent topic subscribed to were content from her being starts feeling dish column middle is rights kollam police long field from top to bottom sweets and destroyed most column and got down at what time will Run From Top To Bottom Thursday Decree Responsibility And Is It Not Expansion Feeling Disla Strong Will Be Different From Home Made Hair To Gotan Hair Researchers From Varied Playwright Moss Right To Left Civil Defense Bottom Row From Right To Left Her 606 Air Chief Indictment Of Water By One Who Believes They Will Learn From Bottom to subscribe our Vidron From Top Toe Bottom Left subscribe this Hair Will Run 51234 Subscribe 560 Quiz Hindi Last Leg Gautam Rog Expert 90 Direct Share Will Default Column From Bottom To Top 10 Vikram 1112 110 Will Repeat Sam Swadesh Will Be 3114 06 Sudhir Weight Is More 200 For The Calling Part First Of All Will Declare The Matrix Of And Processes Of Versus 90 Water From Nuvvu Left From 200 According To Android From And Minus One Sunidhi Indices Representing A Four Places of other metrics and wealth from given no veer is this is the first world will withdraw from left to right in treatment plus in the field of subscribe value that and will place value after one fill all full toppers will increment by one and will divide Column point is requested to end violence no requested to call from top to bottom condition will win 10 top and bottom clipping cream and you know very well s that further in one field brightness palam vihar to decrease right one so nice - - similarly e know decrease right one so nice - - similarly e know decrease right one so nice - - similarly e know you Will Feel The Water Most Row Which Starts From I From The Right And Will Go That Greater Noida Authority Ko Sunao Records Were Going From Bigger Number Right To The Smaller Number Left So Will Get Here And With This Time Decrease Also Index Of Sexual Vinod G Road Water and columns of this brings wealth plus one will depart that decreases also at bottom same will do for the left problem solve problem will start from bottom subir water and it well wishes and to top leaders feel a gossip column and please subscribe and travels in four Top Right Corner To t&c 200 Recording God Compile And Were Getting Back Translate Trisome Custom Test Cases Want To 4 MB So Let's C 200 Gr Co Departing From All Recent Ice How To Choose With U A Scientist Accepted Sued For Write Any Questions 80 Time In The Comment Section President Will Run Away From This Point To Point Subscribe Considered As A Result Of Written Test And Share My Video Thanks For Watching
|
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
|
3 |
4 Rico Le No. 3 Yes, there was a problem called Gist Business String Upper Down Lifting Characters. This is now a sliding degree problem. It is a very similar problem to the Amazon coding interview problem I saw earlier. It feels like u3, and in fact, the problems that appear in this ret code are Yes, most of the coding interview questions are very informative and creative. Sometimes they come out once every few years or so. Most of them are variations of existing problems. So there are a lot of similar ones. So, only the 100% difference is on the pill box side and the So there are a lot of similar ones. So, only the 100% difference is on the pill box side and the So there are a lot of similar ones. So, only the 100% difference is on the pill box side and the conditions are like this. It's a little different, so it adds a little bit of context. So, problems like this make a lot of use of materials. And sometimes, when an original problem comes up, it's a little embarrassing, but I do n't think there are that many problems like that. So, there are also problems. The fact that it is similar to the problem before and again is probably a bit of a problem in itself, so there are quite a lot of problems of that type, and these problems are hidden everywhere in these two clubs. There are a lot of problems for me as well. Lately, in the coke era, I have been unable to solve problems such as u patents, etc., me as well. Lately, in the coke era, I have been unable to solve problems such as u patents, etc., me as well. Lately, in the coke era, I have been unable to solve problems such as u patents, etc., so that's it. Next, I was originally a paid member, but I lost my mind and now I pay less attention to this place. In the meantime, my paid membership period is over and the two cuts are still locked, but since you can only see them while working, I created some content and didn't show it at that time. However, if you pay for this, Eun Ajo Lee Kun-hee's nose has nothing to do with it. pay for this, Eun Ajo Lee Kun-hee's nose has nothing to do with it. pay for this, Eun Ajo Lee Kun-hee's nose has nothing to do with it. Just in case, the frequency appears here. Problems that come up frequently in interviews are displayed, but anyway, there are 7 problems that are hidden even if you go to the Inno tab on this slide. In fact, there are difficult problems, shoe problems, and many similar problems. But the principle is. Most of them are similar. Most of the differences in difficulty are in the part where you check the conditions. So if you try to solve a few problems like this, you will soon get a feel for how to solve them. 9 This problem is at the medium level and you solved it earlier. It's almost a similar problem to the one that was given. The number of characters is given, and the question is to find a long substring with no overlapping characters for that character. Previously, the length of the substrings q was measured by 2 each. In particular, with the characters. The idea was to find all strings whose length is cane, but this is not true. Find the length without repeated letters and find the longest technique. Then, from what we saw earlier, the length condition disappears. The length condition disappears, and the length itself becomes a beat. But the way to find it is the same. If the left right is reduced by law and there is a tax cut, this is the left right. At first, you put this writing a and the light increases and decreases. Then, because it is held by Lee Eun's Cass, the top will become a candidate again. At first, it is 1. Then, by supporting ap b, the light increases, and then when this type of seed is done, Unica Ceci can also become the top. The next type comes in. abc Then, this can also be the answer, so the length of 3 is 3. After that, the meaning came into my mind again. The conditions are no longer right. That's right. What do you do when the conditions are not right? The moment the conditions are not right, you move to the left and force it until the conditions are right. This could be the answer. Since we can't, we 're reducing it again from the left. Subtract a from the left. If we 're reducing it again from the left. Subtract a from the left. If we 're reducing it again from the left. Subtract a from the left. If we subtract every day, the condition is met. 4 The condition is met. I've seen canola avoid raptors, and then this can also be the answer. But in 3rd place, the original one is now 3, yes, 3. It's like this. Then, increase by one space to the right again and p again. Trog pca. But since the op cap pcb is already back, decrease it again to the right and left again to reduce the ratio and cab. That's how it becomes 3. Yes, I came here because I didn't like it, right? And then again. Oh, put c again, and this time, if you put c in, it's cab time, so it's not like this, so I removed the seeds from the left side, and I reduced the seeds a little bit from the left side, and it ended up like this. abc After moving 10 rafts like this, it doesn't rain again. I'm reducing it by one space left, and it's pointing to the raptor, but when I reduce it, I remove it, and this isn't it yet. Then, I have to reduce f Ranka further, until it hits again, and it becomes cb. It's already 12a guard c bb. No, then what happens? Reduce Mr. Raft like this Ah Yong 1 Here's the fact. Lap special a cube 4 o'clock is shortened to bb, so it's not a condition, so I open the apps again and move them further. So until it becomes 1 then 2 will be the answer of 3 which is the largest among all numbers. Yes, then let's deal with letters filled with only B. This is actually simple. When there is a raft flight, at first there will be b 1 and then it will be 1. Then, as the Google Light on the second floor on the right increases and becomes bivy, it becomes an embedded state, so it increases again on the left and subtracts the position in front, so it does not become a bean, and repeats this process again until the length becomes 10,000. It's profitable. It's length becomes 10,000. It's profitable. It's length becomes 10,000. It's profitable. It's simple. Then, this time, let's match this character with the value. When the left right is revealed here, there is only p, and the answer is long, so now the length will be like this, and then when it becomes pw, the right will be If it increases and becomes pw, it will be 2p ww. Then, if you add the lighter to this point, it will be in Illidan state at this time. Then, you will have to go rafting. When I do blood, it has become w, and this is also in an inventory-like state, so please increase it by using my apps again. this is also in an inventory-like state, so please increase it by using my apps again. this is also in an inventory-like state, so please increase it by using my apps again. In this way, I typed wsw and it became e. My daughter now added K k from the right, so it became wk, which became e. After wk went up to 2, I added this. How about this? Since there are no duplicates, it became 3, and then wk w. There are two. So what if I don't receive this, so I removed the new raft and it became kw, but since this has become a Weleda state, only the tank is moved, and in the end, the largest Susan among them is 3 Long Gist Service Trin Length. Well, I'll be a person. Let's code it like that. 7 It's not that difficult, so I think you can do it. That's right. Now, the code that I made when I solved the problem is moving. I'm writing down the code that I can use in Rooty. Ah, yes, this time the answer is long. Because you made it as an in-teaser, the number of letters and the number of letters are still important. You can't have two companies, so you can do it. Then, if it comes in the next few months, you will have to update White Light or Zara Jo. Then, the number of letters will be 4. Let's do it. Right, since the incoming letters of the light are new, we are increasing the number of the new letters of the light. Now, what should we do with the update leti? Under what conditions and what are the conditions for mat or update? The number is the new letters to the right of the new incoming letters. If the number of letters the child enters is greater than 1, you need to move them to the left. If the number of new letters your child enters is greater than 1, you need to move them to the left when they become more than 2. This is how you tell the child to move the letters at the current position to the left. Subtract it, subtract one like this, increase the sector, and it will look like this. In October, I can use it for discharge. So, with the Gogo app, I'm pointing at Raptor, subtracting the number of letters, and moving the level frame. What am I doing? Please update the top next. The update will be included by the When the state is reached, update the left side again. Continue updating the left side, update the left side, and when a condition that could be the answer appears based on the updated conditions, set the answer as if there is no answer. It goes like this. If it's a more difficult problem, solve it. Let's see
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
1,786 |
hey what's up guys uh this is chung here so this time uh 1786 number of restricted paths from first to last node okay so you're given like undirected weighted connected graph here and which is like represents by a n which is the number of nodes and a bunch of edges with the with weight on it right so and the path right so a path from start to end is a sequence of nodes sorry so here's the definition of path here and so the distance of a path you know it's the sum of the weights on the address of the path right and then so we're defining like a distance to last note x so this one means that you know the current nodes a current node x the this the shortest distance between the x and the n right and basically the last node right that's the definition of this function here and then another one is that we define like a restricted path here so a restricted path is you know the uh basically it so the distance of each node right to the last between the current between each node to the last node is in the decreasing sequence here and then last lastly it asks you to return the number of restricted paths from node 1 to n remember it's from 1 to n only we're only calculating the restricted path from the starting node to the endnote right so then here's a here's an example here so first thing is obviously we need to calculate the uh basically the shortest path right between all the nodes uh and the nodes end here which is five right so here we have like uh so of course you know five the distance between five and five zero right and then between distance uh the distance between two and five is two and then between one five is four between four and five six is six right so on and so forth and then the uh once we have the shortest distance right between each node and to the last node here we can find the restricted path right so like i said the restricted path is that you know the distance right has to be in the decreasing order which means that you know in our case we have three paths here the first one is this one the first one since it's always going to be from n from one to n right that's why you know from one starting from one it can go to two and from two sorry one two and from two we have two options here we can either go to five directly or we can go to three five and another one the last one is we from one three and five because there are they're all like in decreasing order right cool and then we have this kind of like uh constraints here right so we have this kind of uh almost 10 to the power of 5. right so i mean to solve this problem you know i think it's obvious that we need to first calculate the uh the shortest distance right between each node to the last node which means that we have to use a dikestro right algorithm to do that and after have after calculating that one you know i think the rest will be simple like a dp problem right uh from one to n basically from each of the from the current one we uh we enumerate to each of the neighbors you know as long as the neighbor has the distance right uh smaller than current one then we can just continue doing it until we have reached the last one right as long as we can reach the last node which is five here and then we know okay we find the path that's when we will return one there cool so i think it's pretty clear right so the first step is that we have to calculate the shortest distance uh so which means that we're gonna first we're gonna build a graph here so i'm gonna default up dictionary here so we have a list right and then to build the graph we have this uh u v and w right in edges then the graph of u dot append uh v and w right since we need to build the undirected graph here you know append uh u and w right so for the shortest distance okay i cut shortest this distance at the beginning you know everyone is max size okay and plus one for each of the notes and the reason i do m plus one is because you know because the note is one based right that's why we have to do one plus one and shortest distance like zero right that's not zero in this case it's n right because we are calcula we're starting from this from the from this uh last node right this one equals to zero now we have a scene equals to set the set and then we're going to use a priority queue right so at the beginning it's going to be the uh the current distance which is uh zero and the node is end right while priority q we have kind of uh the current distance and we have the current node right it's going to be a heap q dot keep pop then probably q and then we add this one to the scene right so this is just like a digestion template you know if you guys don't know what the actual algorithm is i think you can easily find a lot of like explanations online that can tells you tell you what this algorithm is doing right basically for each neighbors right in the graph of current we check we first check if the neighbor has not been seen before not in scene and then we have the new distance right so that require i call it new distance so the new distance will be the distance plus the current weight right and then if the new distance is smaller than the shortest distance of the current neighbors and then we know we find a better answer uh find a shorter distance for this kind of neighbor right now i can just we can just push this one and use the priority queue right with the uh with the new distance plus the neighbor right and then we also update the shortest distance right with this new distance right and basically after this while loop here you know we're going to have the uh we're going to have the shortest distance for each of the nodes stored in this kind of in this array here okay and then the next one is just like the uh we just need to do a basically the dfs right or a top down dp to calculate the path from one to n so which means i'm going to use a uh basically a dp of one here you know and then in the end we have mod equals to 10 to the power of nine plus seven return answer mod do a modular right and so the last part is which implements dp function right lru cache none right i mean for this kind of dp i think it's kind of uh obvious that you know we simply need to do like uh a dfs right from the from one to five you know and every time we have answer equals zero basically every time we check the neighbors right we check the neighbors and the weight you know in the in graph the current one you know if the shortest basically if the shortest one if the current distance is greater than the uh then the neighbor distance we know that okay it this path is a valid path right so basically this dp what we're defining here is that you know that's going to be the total uh the total path right the total restricted path starting from the current node and the end is the last node that's going to be the definition of the dp here so every time when we add the current node here we check all the neighbors and then we and we do this one right and if this one if the current distance is greater than the neighbor and then we know we can go to that path which means that we're going to do an answer accumulate that one to neighbor and then in the end i will return the answer so the reason b we can do accumulates dp is because you know if the current one is equal to n which means that we have find i reached the last node then we know okay we find the path which means we're going to return one here right and so one more thing here is you know we i didn't check the uh the dupli duplication here basically you know let's say we are starting from one we reached two here right from one we reached two here but when we add two here you know two has like neighbors right has three neighbors which is three five and one which means that for in this four loop here it will also check one here so the reason i didn't uh maintain like a scene set is because this one will always be false uh whenever we uh we check the current one with his parents right because if we add a two here you know the basically the neighbors in this case the neighbor which is one the distance will always be greater than the current one that's why you know we'll all we'll never go back to the node we have ever visited before because of this if check here okay all right i think that's it is and if i want to run this one let's see short test okay i think there's a typo here accept it yeah so it's passed right uh let's see what else and regarding the time complexity right so i mean for that the dikes throw algorithm the time complexity for dax algorithm is the uh is the number of edges times log the numbers of vertices that's the time complexity for that diagonal and then for this kind of dp here you know it's actually so obviously it's like of n right so uh so n is the node the current node is v right number of v times uh times the neighbors right the neighbor of that node so it's going to be a v times uh yeah because i would say this one is like kind of um of one here because you know one note uh yes it could have like um up to n neighbors but in on average i would say it should be like a limited number of neighbors so i would say this so for the dp i think the time complexity is close to o of v here so i think the total time complex is going to be e times log v plus o of v yeah i think that's it right so this one i think it's kind of uh straightforward basically the first step is that we use the uh dikestro algorithm to calculate the shortest distance for each node between each node and the last node okay and once we have that information so we can just utilize a simple dp uh solution here to calculate the total uh of the total restricted path right given like by using this kind of a constraint here right um yeah cool i think i would stop here and thank you for watching this video guys and stay tuned see you guys soon bye
|
Number of Restricted Paths From First to Last Node
|
count-the-number-of-consistent-strings
|
There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes.
|
A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force
|
Array,Hash Table,String,Bit Manipulation
|
Easy
| null |
63 |
hi today i'm talking about lead code problem 63 unique paths this problem asks you to do similar to the previous unique it's similar to the previously code problems unique paths one what it asks you to do is it says it's going to give you a grid and the grid can have obstacles on it an obstacle is going to be marked by a 1 in the grid and a space that you can walk on is marked as 0. you control this robot starting at the start position and what you want to do is find the number of paths that can reach the end position the number of different paths that can reach the end position without traveling through the obstacles obviously so i drew this little diagram because i thought that this was going to work the same way as unique paths one as the original and in fact it does so what i do here is i say okay the end is one if you're at the end then you have one path to the end and then our robot i forget if i mentioned this or not our robot can only move down and right so if you're at the end you can only reach the end from above it by going down or to the left of it by going right and yeah so then what you need to do is set the value for the adjacent cells to be the sum of all of their adjacent values in other words from this cell that i'm currently drawing around you can reach the end by going right or down so you take the sum of the path on the right plus the sum of the path going down and that's two and then you can fill in the other cells similarly so i'll just quickly draw this and start one two i guess i don't really need to fill it in one you can only go down um three and two excuse me this one's three and here we are at six so what makes this problem different than the previous unique paths one is that we can have these obstacles spaces we can't move through and so how i treat those is i just say that there are zero paths going through the obstacle that reached the end so rather than follow the behavior for a normal square where i'd sum the paths down and to the right i just say if it's an obstacle then it has a value of zero it has zero paths that go through it to reach the end so with these um with this approach we can essentially solve the problem and if we're ever in the special case where say all paths are blocked then this will work as is so start and if we have blocks all around then these just go to zero and everything else is zero proceeding out from it so zero paths to the end if it's blocked i think that makes sense um yeah so how this is going to work the function that the solution object is required to have is this unique paths with obstacles function and it takes the obstacle grid and the grid is that um a two-dimensional grid two-dimensional grid two-dimensional grid or a list of lists zero being a traversable space and one being an impassable space and what i'm going to do is i'm just going to call my helper function robot at which i'll explain right now so robot at is going to approach this in a recursive way it's going to have a base case as the first thing which says if you if the rx or robot's x position or the robot's y position is outside of the bounds of our grid so if the robot has traveled off the edge of the grid then we're just going to return a zero yep just return a zero the next thing we do is construct this args tuple which i'm going to use for memoization i'm just going to store the request any unique request in a dictionary that's specific to my solution object so if you've ever tried to get the number of paths from a coordinate before rather than calculating it we'll just be able to look it up in our robot apps dictionary so once i have the tuple oh and i should say the reason for using a tuple is because i just want an easy way to look up these two values in the robot at's dictionary um yeah so we here's the check that i was just describing if the args are in my robot at's dictionary then just go ahead and return the answer from the robot at dictionary the robot ads dictionary is just where i collect previous executions of this function so if i have an execution with the same input then i know what the answer is without having to do any calculation another recursive case oh sorry another base case would be that there's an obstacle at the position you're currently looking at and in this case we're just returning a zero this is what i was saying with the red x there's an obstacle if we're evaluating this position so it just returns zero um yeah so if the robot's x coordinate is equal to the last space on the grid so the length of the grid less one or um yeah i guess this oh i see sorry and the robot's y-coordinate sorry and the robot's y-coordinate sorry and the robot's y-coordinate is equal to the length of the x sub-list x sub-list x sub-list of the grid meaning we would be down here so we're at the maximum x and the maximum y then we're at the very end and we can just return one so if we're evaluating the final spot and we can return one so those are the base cases we already have the answer we're off the edge of the grid it's impassable or we are at the end so what we do is we just say okay let's say the right value is going to be my recursive case we're going to call the robot app function pushing our robot one to the right the down variable is going to get the value of the recursive case pushing the robot one down adding one to my robot y and then the result is just going to be the sum of the right and down paths and then we're going to store the result in my robot at's dictionary so that we can look it up if we need to a second time um yep and so like that's essentially the code and it winds up running pretty fast when i ran it previously yep it's faster than 99.2 percent yep it's faster than 99.2 percent yep it's faster than 99.2 percent of other python 3 submissions i don't know how many python 3 submissions there are you can see i was tinkering with it for a little while to try to get the solutions or try to get it to run faster by just taking things out of the solution and then re-running it solution and then re-running it solution and then re-running it and eventually it got to be pretty quick but um yeah that's the solution i'm going to try to do a liquid problem a day maybe slightly more frequent than that so if you're interested like the video comment let me know you're watching or subscribe to see morally good problems thanks a lot for watching bye
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
1,690 |
hey everybody this is larry this is me gorman q3 of the weekly contest 219 of lead code stone game seven wow we're already up to seven too fast too furious so which one was the seven let me know if you have a good point on stone game seven but anyway so stone game this um there's seven of them so hopefully by now you put practice a little bit more uh if not that's okay that's what i'm here for but it is just dynamic programming as you may have guessed um for me uh just my thought process was that this was actually pretty straightforward i have to go watch the video but i actually solved this in about like five minutes however i did it with top down um and i can actually show that submission real quick and i'm going to actually explain the top-down solution and then um top-down solution and then um top-down solution and then um you know we could go over the bottom sub solution as well but it's what technical difficulties hang on uh and then we'll go over the recurrence a little bit uh hopefully if you have done the other seven or the other six uh stone games uh you have the idea of what to do right so basically the idea and this is top down which i think is easier to explain uh though i did the steps a little bit weird but basically we have this idea of prefix sum uh why do we use prefix sum well and so that you can answer the query um you know you want to get the score between two numbers or two end points and get all the sum of all the numbers in between right well that's a perfect job for prefix sum uh if you're not familiar with that please practice it comes up all the time on lead code interviews to be honest probably not as much but it does come up with a lot of neat code and stone games and stuff like that so using this prefix sum we're able to get these kind of queries and all one time so because if you do a loop from left to the right then it's going to add an additional o of n and that's going to be too slow it turns out to be too slow anyway because the code hates me but that's another story um okay so then what is the recurrence after we are able to kind of get this score right well the recurrence then become very straightforward because okay you start with the entire array which is zero and n minus one inclusive to be clear and inclusive means that we zero we want to be able to use zero and n minus one so that means that we have go left right i also had some issues with the base case but um but actually you should return zero in the base case because when you have one number left one stone left and you remove it then there are no stones for you to gain points and that actually cost me a couple of minutes as well but okay so now we said the best is just negative infinity is the central value it doesn't matter and then now you can either take the left stone or the right stone right if you take the left stone then your score is just the entire um and actually you might actually not now that i think about it for a second you actually don't need the prefix sum if you just keep the total and then subtract that from the total in the running kind of way but maybe that's messy so this is a little bit easier but you might not need it per sec but in any case yeah so what happens when you remove the left stone right well the score that you get is just the total score of you know the sum between left plus one to right which is what we have here and then we recursively subtract it from the score because that's the score that bob is going to get or your opponent is going to get and that's the negative score because we're going to subtract it i should win it the other way but you still get the idea and then the other move that you can do is removing the rightmost stone and when you remove the rightmost stone your score of course is the entire array except for the rightmost stone that you just removed and then bob now gets to play that sub game so that's basically the entire problem um however i and i don't know why uh as i said this actually leads to time limit exceeded however this is n squared and i don't think you could do faster so i was like what is going on so basically i rewrote it bottoms up um i also debated during the contest to rewrite it in java but i don't know i think to be honest i think python just got screwed or at least i got screwed a little bit uh if other people pass using the recursion um but yeah and this is basically the same idea as the tap down recursion with memorization it's just that i converted it to bottoms up this is not as easy as the another one the tricky thing to note is just to make sure that you have the order in the right place um because note that the for loop in the loop i go actually from right going in um or from right going out the reason why i keep this is because that what i want to do is start with left and right you know as close to each other as possible and then propagate out that's kind of the idea i know it's a little hand wavy converting between this bottom up uh from top down to bottoms up is not always easy um and after the contest i'll see whether you know like whether that's necessary i really don't know why i got time limit for you century the same thing so i'm a little bit sad about that um because n is only a thousand it's not even a big number so n square should be very fast so i'm a little bit disappointed that it cost me about eight minutes like probably five minutes coding five additional minutes coding and the wrong answer is like 10 minutes in penalty in total so that's a little bit sad um but yeah that's all i have for this problem uh except that every time i say i always forget to go over the complexity so because of um you know this is dynamic programming this is a matrix it's an n by n matrix it's going to be an o of n square space uh here the o of n loops on of n loops so it's going to be o of n squared time um that's all i have for this problem you could watch me solve it live during the contest and watch me be sad during the contest and i will oh yeah you can just keep on waiting to do you so oh oops oh this is um so success hmm do so that's not right so why oh this is not it huh this is zero because there's no stones left really that's actually surprising that is only a thousand now this is so fast huh this is one of those like python it's getting screwed kind problem it seems like because this is just n square for a thousand where they should not be uh 68. i'm wasting so much time on this is silly i mean it's not fast but it's not slow so this is okay this i don't know that i got the order quite correct to be honest so we'll see what am i doing wrong what a mess no this is right there going bounce oh just being dumb it's not even that much faster and of course my answer's wrong but okay this is right i actually don't remember it's faster but is it fast enough if i have to switch languages i'm not gonna be as happy really it's still too slow oh what a stupid problem yeah thanks for watching uh let me know what you think about today's prom and just let me know what you think hit the like button smash that subscribe button join my discord more uh so you can chat with me and people and ask questions and i will see y'all next contest next farm whatever bye
|
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 |
507 |
hey everyone welcome back and today we'll be doing another lead code 507 perfect number and is even a perfect number is a positive integer that is equal to the sum of its positive divisions excluding the number itself a divisor of an integer X is an integer that can divide X evenly given earn integer and return true if N is a perfect number return false otherwise so 28 is a perfect number because all of its Division if we add them up we'll going to return 28 itself 7 is not a perfect number because 7 has only to visit one and seven and we are not going to include seven because they have said like the number itself does not count uh yes here excluding the number itself so one will be left alone and one does not make up seven if we add it with nothing like one is not seven simply so in the case of 28 you can see like we have one two four eight all of its divisors and if we add them up we are going to return 28 so we can just Loop tell the number and just add if there is a divisor but we have to make a more strict approach because it just exceeds the time here if you take a linear approach of an approach so the time limit must be like and complexity must be like less than of n so we will be doing it by taking the square root so the square root of uh the 28 will be something like 5.2 5.3 or something like this but we 5.2 5.3 or something like this but we 5.2 5.3 or something like this but we are not going to put it in our Loop like the floating value so we'll be at a type casting it into end and then adding it by one because we do want to include that for the floating point and now what we'll be doing is first of all taking that Visa itself so one is a divisor here if you start our uh you can say uh start from the very beginning and then we are going to take the question so the question here is 28 and these two are the division you can say divisors of 28 now we can move on to 2 and now 2 will have 14 because obviously they both are the divisor of 28 as you can see here now 3 is not so like D is not so we are just skipping 3 and 4 is still there and four has seven and then we have reached five and five is not going to divide 28 evenly so these are our values now we can see that these are our required values but 28 we do not want 28 in our you can say resultant so we can just pop it off like subtract minus 28 or minus the number itself so that's it and now we should have a duplicate protection like if there's a 25 then obviously we are going to have a 1 and 25 and now uh five and five so we do not want to add the number that is duplicate so we will be just having an if condition for that and that's it so let's get started so we have a resultant that is equal to 0 so for I in range of 1 starting from 1 and taking the square so the square will be num and 0.5 adding it by 1 because we do want to 0.5 adding it by 1 because we do want to 0.5 adding it by 1 because we do want to include that floating point and now if the number is divisible by I we can just add it to our result and if now we will check the duplicate if it is a scare of the number then we are not going to add it to like twice so the result will be like num taking the quotient and now after all of this we can just return the result subtracting it by nums because obviously we do not want the number itself in our result and that's it just that's it like if this is it and this works
|
Perfect Number
|
perfect-number
|
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly.
Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`.
**Example 1:**
**Input:** num = 28
**Output:** true
**Explanation:** 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
**Example 2:**
**Input:** num = 7
**Output:** false
**Constraints:**
* `1 <= num <= 108`
| null |
Math
|
Easy
|
728
|
1,312 |
hey what's up guys chung here again and so this time let's take a look at this little problem here number 1312 minimum insertion steps to make a string palindrome another classic not classic but another astringent palindrome problem you know i think it's very easy very simple description not easy sorry simple description you're given like a s in one step you can only insert any character at any index of the string return the minimum number of steps to make as palindrome okay so it asks you to get the minimum inserts number of steps which means like in another words to insert the minimum number of strings of letters that you make that makes this um stream becomes a palindrome some examples here first one z-z-a-z-z it's already a valid first one z-z-a-z-z it's already a valid first one z-z-a-z-z it's already a valid polynomial so then the output is zero for the second one mba dm we need to insert two strings one for d the other one is for b here okay yeah so on and so forth okay and for single numbers single ladder we consider as a valley's palindrome right that's a it's a known right okay so i mean every time we see a palindrome it's like it's as if it's like a sign telling you that it's a signal right so it's a dp problem okay and so i mean today i'm gonna use two dp solutions not the top down and bottom or the bottom up both of the solutions are all bottom up but there are like some variations between the thinking process okay so the first one is we just follow the is the description basically we're thinking the problem is like every time when we have like a options here we insert okay so we do an insert we just use the description from the problem and you guys might have already know so for this first string here right we usually need like uh i'm sorry so i'm gonna so the normal definitions for like a string problem you know for example this one for example for the palindrome i and j means that the index basically from for the substring i and j the minimum right the minimum insert the mean the minimum insert okay so that's the definition of the dp for all the palindrome problem almost okay so since this is the index right and let's say we have um i'm gonna try to okay and since we're getting the minimum right so we're gonna initialize everything to the maximum okay and here i mean we can use m minor m plus one or n i think for this problem n also works because we're not going back to the i my minus one i'll tell you guys why that's the case so to be able to get the from i to j we need to first when we loop through the i here we need to loop from the last one to the previous one so that the j can be on the right side right otherwise this thing will become to the j to i if we loop through i from the if loop i from the smallest to the biggest since i'm trying for me i j makes more sense that's why i uh i look through from the n minus one and minus one basically i'm looping from n minus one to zero okay and then for the j right then the j is from i to n minus one okay makes sense right so you know for all the palindrome problem or for like or even for like us added distance for string problem remember this we always check if the s i is equal to s j or not always have this like conditions here if else remember this because if i equals to j it means that we can simply ignore the i and j and only go back to the uh go to the i plus one and j minus one case right because in this if x i equals to i s j means that uh this these two letters it can be part of the palindrome right so we don't have to worry about those two letters anymore right because for the palindrome like the left side and right side has to be the same so but we need the base case so what's gonna be our base case is like all the ladders uh all the single ladder like it's a palindrome right and this two is also palindrome okay so that's our base case so basically what i'm doing is if j minus i is smaller than two okay s sorry d p i j equals what equals to the uh j minus i plus 1. so what i'm doing here is that basically if the i equals to j okay if i is the same as j because as you guys can see i start from i so the first one is the j s i equals to j right so in that case it means that single ladder here and another case is the two ladders here so i minus j minus i less than two is this case so for those cases right and uh we need zero sorry okay yeah so for that's zero it means that since we're defining like this is the minimum insert we need to make we need to do to make this uh dp the inj like a palindrome but in this case uh as long as the length is less than two and the si and sj are the same then we don't need to do anything we simply just assign zero it means that we don't need to insert any character okay elsewhat else dpi else if this like has more values right has more letters let's say there's like g a b d e and g so that's the case this is i and this is j so now we can hand over the results to the i plus 1 and j minus 1 because whenever these two are the same we can simply ignore those two letters and we can just uh calculate the substrings which is the i plus one and j minus one okay so that's the uh that's the ice i equals to sj case now in the else it means that i and j are not the same so this is a little bit tricky here so let's say we have a b c and d okay and this is i this is j okay so in this case we have two options to match this either a o or b we can either add a on in here okay we can add a here or we can add d here right we have basically we have two options we either add a here to make the uh to make a and a uh are valid part of the palindrome or we can match d yeah basically we either match a or we match d here but the tricky part for this problem is that we are actually not re actually adding the strings to the uh we're not actually adding the letters to the string i think this is some of the thinking obstacles you need you guys need to uh really to really think it through let's take a look let's say whenever let's say we add a letter here let's say we add a here okay and if we add a here what does it mean it means that a is here but j is moving to here okay j moves to here okay and so after moving the j to here right since the a and those a are the same by using this formula then we can go back to this s i equals to s j case here so in this case and the i will become i minus 1 and j will be the same j because here is the j plus 1 right and then the j because here it's going to be j plus y minus 1 so it will still be the j but i will be moving towards i minus 1 here same thing for if we match d here right if we match d here i mean this is gone i will become i minus one right and then by removing this i d and d here we have i and sorry this is i plus and it's j minus one okay yeah that's how we uh mimik that simulates the adding process so when it comes to the coding here it's pretty straightforward like i j equals to since we're getting the minimum right we're getting the minimum since we're inserting one of the letters right and we have to add one here and after that it's just like dp uh i minus one j so this is the case to match uh to match j this that's the this is the case and if we want to match i it's going to be the dp i j minus 1. sorry here i plus 1 remember this it's not the uh it's not the i minus 1 because we're moving to the right okay and here we simply return the dp uh zero to n minus one okay i think this should just work let's run it okay submit yeah cool so this one passed you know i you know this one the first if statement is pretty straightforward to understand right i think it's the second house here second part here which is kind of tricky because i mean we have to think i like as a way right since we're every time when we see like a difference we try to insert okay and when we try to insert we have two options we either match i or we match j so um yeah so basically when we match i here we insert this one as a j uh we insert a here so now the j will become uh j plot plus one and then we use this formula to remove both a from to remove a from both sides and then we have i minus one sorry we have i plus 1 and j and same thing for matching the j here we have dpi j minus 1. at least that's how i interpret this formula i mean if you guys have any other better explanations for this like formula yeah please do let me know leave some comments i really interested to know that what do you guys think about how to explain this like this formula here or state transition function here okay see so yeah that's pretty much it is okay so we in the end we simply return from zero to n minus one that's basically the entire string here what's the value of this one okay so that's the first approach right i mean the thinking process a little bit weird especially for this part and okay so that's okay so the second one is really like a brilliant way of thinking this problem you know for adding like us letters to a string seems really hard to appreciate right for example especially when we think about these things here right but i don't know if you guys have solved a problem i think number is on number 516 that problem asks you to find you're given like a string and you it asks you to find the maximum palindrome of a subsequence a sub maximum sequence of palindrome you know you guys know the subsequence right subsequence is like the yeah it's the subsequence does not have to be continuous but it has to be it has to keep the original like other so in this case we have mb mba d a right so the sub one of the subsequences m a and m okay and for that problem number 516 it asks you that you're given like a string it asks you to find the maximum length of a subsequence that can be it's a valid palindrome okay yeah so can you guys think about how can we utilize that solution to solve this problem right i think some of you may have already noticed here so let's say we have a this is the maximum subsequence uh to be a valid palindrome which whose length is three right all we need to do is we just need to use five minus three that's gonna be our answer here another example here let's see so then e t c o e right so the total length is eight okay the total length is eight what's the maximum subsequence that can form a valid palindrome three right so that's e and e okay that's the maximum subsequence uh that can be uh like a valid palindrome right this one is three so the answer is eight minus three equals to five right so why does this thing work why does like why does this solution work because you know for example this one i'm not going to pick this one as an example you know for the sub sequence for the for those valid subsequence as a palindrome we can simply ignore those ladders right because those are already a valid palindrome all we need to care about is this the left the remaining letters which in this case is b and d okay so to make the remaining letters like to be a valid uh valid palindrome all we need to do is we just need to add the same amount of letters to make those remaining letters uh to be a valid palindrome right because this is thing we can simply add a b and a d and d right that's going to be the valid palindrome so by utilizing this like the conversion basically we're converting this problem from an insertion problem to uh to find the maximum subsequence as a palindrome stream which is i think to me is more it's more intuitive to come to think so let's try to code that things and same thing right i mean i'm going to copy these things over but remember now we're trying to calculate the maximum value the maximum strength the maximum length of that of the palindrome so that's why we need to have like uh the i the zero here okay still i think we can do a i minus i think we can do n here um yeah sorry uh back here so i think i told you guys so i mentioned that uh we can use n here the reason being is that we don't have i minus one here okay and we're starting from the uh we're starting from yeah we're starting from n minus one to zero of course but you guys can see we have a j minus one here right but the j minus one will not go out of the boundaries because whenever the i and j are the same we directly set the value here so there won't be any uh cases that the j minus one will become uh like a minus one but it's always safe to keep like a buffer here but so that's why i'm going to use the same unplus one here so when we have this one right so same thing here right for i and the definition actually is the same the definition of dpi instead of but instead of getting uh having the minimum value the minimum like insertion numbers now we are in the dpij we it represents it means that for substring i and j what's the maximum palindrome okay so that's why i'm going to use the same structure for loop here and the inner loop is j i to n okay it's actually it's almost identical to the solution here we still need to check right if i is equal to sj okay so same thing here right so if j and i is smaller than two okay dp i j so okay so now we are we're getting the uh the length the maximum length of a plenum so whenever the j and i the s i and s j are the same and the j plus the j minus one is less than two it means that for the g and gg right that's the two cases we're covering here so for the g for a single letter the length is one for the two ladder is two so i'm just combining those two here basically i'm just going to use j minus i plus 1. okay elsewhat else dp i and j equals to what so when there's like when there is like a two more strings here let's say a b c d e f a and this is i this is j similar as this one but instead we're not doing this okay because we already have a here right so a and a means that we already have like at least two strings two letters that can form like a palindrome right so that we have two here as a base case and for the remaining part we just hand it over to the sub problem which is dpi plus j plus one j minus one similar as this one but we're doing like in the reverse order here since we're getting the maximum value of that okay and okay so that's that and how about else here right so for the owls dp i j okay so when the so now when the a and w when the i and j are different okay so what options do we have right we either go when they're different so which means i and j cannot form the uh a palindrome so we have to go back basically dp i minus 1 right we check that basically sorry i plus 1 we're moving i on the to the removing i to the right side to see okay how many uh what's the maximum plenum we have from i plus one to j and another thing is we can move the uh like to j to the left by one okay right yeah because the current i and j cannot form it so we have to uh basically the value should must have come from the previous one because from current i and j we cannot add a value on top of it so we have to go back to the previous one to check okay and yeah and at the end the dpi the dp0 and one here it stores the maximum palindrome of the entire stream so all we need to do is listen to it to n minus dp 0 and to m and minus 1. let's try to run it should just work submit yeah call this one also pass i mean as you guys can see so this thing is it's easier at least for me it's easier to understand uh comparing to this insert action here because here we're not doing any insertion we basically will simply move the cursor to the right or to the left because the current i and j is not a valid it's not it's they're not matching so we cannot use those use i and j as part of the palindrome yeah i think that's pretty much yeah i want to talk about for this problem you know it's a it's interesting palindrome problem i mean either way it's fine you can you guys can either use the first approach or the second approach i mean whichever you guys feel is easier to understand yeah but for this one yeah like i said if you guys have a better explanation for this state transition function do let me know leave a comment i really interested in that uh so yeah i think space and time complexity is pretty straightforward right so they're both and square right because we have a nested for loop here cool guys thank you so much for watching the video stay tuned and see you guys soon bye
|
Minimum Insertion Steps to Make a String Palindrome
|
count-artifacts-that-can-be-extracted
|
Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zzazz " is already palindrome we do not need any insertions.
**Example 2:**
**Input:** s = "mbadm "
**Output:** 2
**Explanation:** String can be "mbdadbm " or "mdbabdm ".
**Example 3:**
**Input:** s = "leetcode "
**Output:** 5
**Explanation:** Inserting 5 characters the string becomes "leetcodocteel ".
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
|
Array,Hash Table,Simulation
|
Medium
|
221
|
208 |
let's take a look at leak code 208 Implement try or prefix tree and this is a great question to be able to practice your tree data structure we've been seeing a lot of binary trees and a try is a string related tree which allows you to better search for Strings such as autocomplete and spell checker so a try or a prefix tree is a data structure used to efficiently store and retrieve keys in a data set of strings there are various applications of this data structure such as autocomplete and spell checker so in this question we need to implement the try class so we have a class which we can instantiate to initialize the try object and then we can go ahead and we can have these common methods so we can insert which inserts the string into the try so thinking in terms of a tree structure we're thinking of inserting a character into each node and then that has children which corresponds to another character and so on then we have the search and starts with functions so search it returns true if you've previously inserted a word before so you're able to search through the try that you've created and if the letters are there and you've marked the end of a word that counts as a search retrieval and then we've got starts with which is similar to search but starts with is where you're just looking for a prefix so there could be letters after that and but that doesn't matter because we're just searching for the prefix so there's a clear distinguishment that needs to be made between the search and starts with and we'll see that in the code so we can see that we've been giving this boilerplate of the try class which has a Constructor and then it also has the three methods that we want to create it has insert search and starts with and then it has an example instructions of what we want to achieve after we fill out those methods so basically we want to instantiate the try class and then we want to insert a word into the try which is going to take all the characters in the word and it's going to make it into a tree structure and then we want to be able to search for the word now it's very important to note that search it's searching for the word being completed so if you put in the word apple a-p-p-l-e and then you search for the a-p-p-l-e and then you search for the a-p-p-l-e and then you search for the word app that does not count as a search but that would count as it starts with so that's the difference between the two methods starts with just Loops to see if the letters are in the tree and search searches to see if the letters are in the tree and the last letter has been marked to signify that a word has previously been entered into the tree so let's just go ahead and clear those instructions up so basically a try is a tree data structure where each node is composed of characters and each node has unique characters as children so I'm actually going to create another class for the node so I'm going to call this try node and try node it's going to have the children and as mentioned because the children are unique characters we can use a map to map the character or string in JavaScript and it's going to reference itself in the same way a tree data structure can reference itself or a tree node would reference itself where each of the children corresponds to a try node so for example the very first node is going to be a the root so in our try we can and I might just tap this back one we can say well we want the root node because we need to have the root node so we can Traverse through the tree that we're yet to create so basically we in the Constructor of the try we want to just set the root node equal to a new try notes that way when people create a new try we have access to the root and then we can do things from that so these three operations here so essentially since we've created this first try here basically we need to well the first the very the root node it doesn't have a value itself the value itself is related to its children so basically we want to have a Constructor in the trinode and we just want to set this children equal to a new map of this form here and recall that for search that we need to be able to detect wherever the word has previously been entered in so not just the letters but the actual word itself so we need a way to be able to mark the end of a word and we do that by on the try node so the trinode represents the character on the last character we need a way to be able to detect if it's the end of the word or not so I'm just going to have it is end of word which is a Boolean and then in our Tri node we can say well this end of node or end of his end of word we're going to set that to false by default so that means when we create a try node his end is going to be false by default and the children is going to be a new map so it's initially going to be empty but then we're going to use the insert method to be able to insert into the so now we've actually composed our data structure let's go ahead and begin to work on these methods here so let's start with insert so insert it takes a word and we need to compose it into the tree so right now we've just got a root node and the root node is a blank empty node and then we want to take each character of the word and make it into a tree structure so to do that we first need to get hold of the root node so I'm going to say let node equal to this root and we're going to need to Traverse through the tree if a word's already inserted so if we've already inserted the word app for example app then we want to insert the word apple or we would already look at the nodes A and P and then after that we'll be able to insert L and E so that's in the second case so we need to be able to Loop through so each character of the word and essentially if we see that the node has no children with that particular character so recall we've made that map data structure here so we're looking for a particular character of the word here in a key lookup and we want to get the corresponding try for that word if it exists but if it doesn't exist it means that word hasn't been um all that character for that position in the word hasn't been added to the tried data structure just yet so if that's the case what we can do is we can simply add it and we can do that because we have access to the node and we have access to the children and then we can go ahead and we can set that character to a new try node as well so the new try node is going to have children of its own and then that just ensures that we have the right data structure matching to this type here so basically that's in the case that no words have been added or that word or the characters haven't been found so if they have been found well regardless if they have or haven't been found we need a way to be able to go to the next node so basically what we do here is we say we want to set the node equal to the children and then we just want to get the particular character that we're on and then after that outside of the for Loop we can say node is end of word equal to true okay so that means we've made it to the last character in the word and then we can mark that as the last um is end of word so then when we Traverse through the tree to search we can actually tell if it's a word or if it's just a prefix so let's go to the search method here so the search method it is looking for we need to Traverse through the Trice so the nodes of characters for each character in the word and then we need to look through to see if we if that word when we Traverse through the tree if the last Traverse character marks an end of word in which case we have a word so to do that we once again we can actually copy some of this code up here and I'm going to copy actually I'm going to copy this here foreign so basically what we can do here is we can just return false if that's not the case so we pass in the root node we look through the characters of the word and if there's no children of the node which has the character that means that character hasn't been entered into our Tri or tree data structure of characters just yet which means the word doesn't exist so we can just say we can return false the word doesn't exist however if it makes it past that what we want to do is we say okay well we want to once again we want to set the node equal to the child so then we can continue to Loop through and then when we Loop through again basically um it will keep looping through until we get to the last character of the word and if it makes it past all of that so outside this for Loop here which should have a closing bracket if it makes it out of that then we can simply return um true if it has the if the character has the or the try has the is end of word or false otherwise so we can return the node is end off word here which will return true in the case that you know we've previously inserted a word and then that last character on that node on the last letter has that Mark there so then we can return true so that's in contrast with starts with because you might have all those letters however it wasn't previously entered so the example I gave before is if you um entered the word Apple but then the next word you're looking for you're searching for the word app or you haven't entered that into the tree so the second p in the word apt uh it wouldn't have the his end of work marked therefore that would return false but this starts with is looking to see if that prefix exists so rather than searching for the full word completion those prefix those letters app that does exist because the words Apple the letters Apple have been entered as nodes into the try and the characters representing them so what we can do is we can actually essentially reuse this code here if we just add a little tweak because we can add a is prefix variable here or parameter and then we can set that argument to false so basically using this is prefix flag we can actually say well if is prefix return true because we would want to return true if we're just doing a start with looking for the prefix because if it's made it to here would be true otherwise it would have returned false before you got there um otherwise you return the node is end of word and since this is false by default um if you're just considering the search method this will be false but then it will evaluate this condition here which means the starts with method can be simplified to just returning this dot search and then passing in the prefix and also just pass in the true flag here so let's go ahead and submit this code here and we can see that it was accepted
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
1,690 |
hi everyone it's albert today let's solve the minion question from the weekly contest stone game seven the question statement so we have two players alice and bob they take turns and playing a game and with alice playing first and they are unstones arranged in a row and on each player's round they can remove either the left most or right most stone from a row and receives the points equal to the sum of the remaining stones value in a row and the winner is the one with a higher score where there are no stones left to remove and for some reason bob found that he will always lose the game so he decided to minimize the score's difference so ali's goal is to maximize the difference in the score as big as possible and we are given an integer array of stones where stone's i represents the value of the i stone and we have to return the score difference in alice and bob if they both play optimally for example one alice will remove the rightmost stone 2 and gets 13 points in the next round bob will remove the leftmost zone five and then get eight points and next round alice will move remove three and then bob will remove one and at the end the score difference between alice and bob is minus 12 which is 6. and for example 2 with this integer array the output will be 122. and the data constraint the length of the array can go up to one thousand the key intuition to solve this question the main algorithm we'll use is a dfs that first search with memorization kind of similar to dynamic programming and the data structure and the key idea we will have a matrix called memo ij and it represents the maximum score difference of alice and bob between the stone's array i j and why the maximum score difference that is because it's alice playing first and ali's goal is to maximize the score difference as big as possible and now let's look at the code the first part of the code first is to generate the memo matrix and its size will be n times n and n is the size of a stone's array and here we have a sums array which is the accumulated sum of the stones array with the dummy 0 attached to the front and next create a dfs function which will return an integer and the base condition if the left and right pointer overlapped then we would return zero and next if we haven't calculated memo lr then we will calculate the range sum using the sums array and then update memo lr to the maximum of one of the sub problem which is range sum minus stones l and minus dfs l plus 1 r or range sum minus stones r minus dfs l r minus 1. and then dfs function will return a memo lr and then run the dfs function and then return rest now let's see the code in action and here we'll be looking at example one and the stones array is five three one four two and first is to generate the accumulated sums array and attach a dummy zero at the front and at the beginning it's alice playing first and the left and right pointer will point to the first and right last element in the stone's array and here calculate the range sum which is the sum of the stones array between the left and right pointer and it is 15 minus 0 which is 15. and now alice have two choices she can either pick the first stone the left most stone so the score difference would be range sum minus stone's l and then move the left pointer to the next element and this will become the sub problem which is dfs l plus 1 r or alice can pick the rightmost stone so the score difference will be range sum minus stone's r and then move right pointer to the next element and that's our problem is dfs l r minus one and memo lr would be the maximum of the two and then the dfs function will return memo lr at the end and this will conclude the algorithm finally let's review so the main algorithm to solve this question is dfs with memorization in the data structure and key idea we have the memo matrix which represents the maximum score difference of alice and bob between the stone's array ij and because alice is playing first so we want to maximum the score difference as big as possible and time complexity is big o of n squared because for every element in a stone's array you have to recurse into the subarray every time and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
|
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 |
623 |
hi guys welcome to algorithms made easy in this video we will see the question add one row to tree given the root of a binary tree then a value v and a depth d you need to add a row of nodes with value v at the given depth d the root node is at depth 1 that is we are considering the adding rule is that given a positive integer depth for each non-null tree node we need to for each non-null tree node we need to for each non-null tree node we need to create two tree nodes with value v and that node's original left subtree should go to the left sub tree of the new left sub tree and its original right subtree should go to the right subtree of the new node that we have added in the right if the depth is one that means we need to add a node at root and so we create a tree node with value v as the root and whole of its original tree would go into the left of the root so that's all about the question let's see an example and then we'll get to know more about it so let's take this tree and at depth d equal to 3 we need to add the nodes with value as 1. so here we can see that the root node will be at depth 1 this will be at 2 and over here at depth 3 we need to add the nodes with value as 1 and then attach these trees to the left and left of these particular nodes that we will be adding so now this becomes our resultant tree so as 3 was in the left of 2 it would be the child of the left node that we have added for 2 and since 5 was also in the left it would become the left child of the left node that we have added for six and over here there was no right child so the right child would become null as it was in the earlier case and over here also for six there was no right child so right child would become null as originally so that's all about how we need to insert the nodes now if you compare the input and the outputs you will see that the nodes are changing after the depth 2 what is this depth to it is the depth given to us minus 1 after this because we need to add these nodes with value given and then again reconnect the original tree nodes into the respective positions so what we do over here is that till this we do nothing the tree remains the same but as we reach depth minus 1 that is the depth given to us minus 1 we'll take its lower nodes in a temp variable so we start with the left node we take it in a temp variable and then attach a new node of the value that is given to us to this node we'll attach the temp node that we have taken in its left similarly we do it for its right because there was no node attached to 2 in the right so there was nothing in the temp or we can say that the temp value was null in this case and so nothing got added beyond this if we do this similarly for 5 we will take this 5 in a temp variable and then attach this node with value 1 over here and then attach 5 to it similarly we attach its right child so this gives us the output so now we know that we need to keep everything same till d minus 1 depth after that we can use this temp variable as we have seen if we are using a iterative way we will be using q and in that case we will be having this particular level in my queue and then on that particular queue i'll be performing the operation of attaching this left and right so this is all about the question and how we will solve it let's go and code for it so that you will better understand that how it is happening so over here the first base case that was given to us is that if the depth is 1 we need to put that element to its root and attach the whole sub tree to its left so let's write the code for that so this is the case for one that i'll take a node with the value that is specified and to this node i'll attach my whole tree that is in the root to its left and return the node and if this is not the case we need to insert the given values node at the level d so we'll take a helper method for that so over here i have taken this values that are given to us so i'll take this root node or let's say node over here the depth that at which we need to insert it the value that we need to create the load with and the current depth at which we are if my node is null i can simply return otherwise i need to check if my current depth is equal to depth minus 1 then i need to do the insertion operations and the shifting of the node by taking it in the temp variable and then inserting everything otherwise what i'll do is i'll simply call insert on the left and on the right so let's copy this now what goes into this particular loop or this particular if condition is that i'll first take the left node in a temp variable now i need to attach a node that is with the value v to my node.left with the value v to my node.left with the value v to my node.left after i am done with this i need to attach this temp node to the left of this newly attached node which would go into left dot left similarly we need to do it for the right as well so let's take right in my temp node and then node.write in my temp node and then node.write in my temp node and then node.write would be new tree node with the value v and its right would become my temp so this would take care of taking the value in temp and attaching the new node with the value v and then reattaching that node that was held into the temp to its corresponding left and right parts now how do we use this we just need to call this insert method over here on root then we have given depth we will give d will give value and then we will give current depth as one because root is at depth one and once everything is done just return the root that's all about this let's run this code and we are getting a perfect result let's submit this and it got submitted the worst case time complexity over here could go to the number of nodes that are present in the tree that is n and the space complexity would also go to o of n to store the recursion stack so that's about the recursive way of doing this what do we need to do in order to change it into a iterative solution for this iterative solution we would not need this method but we would still need these operations because these are standard operations that we need to perform in both recursive and iterative version over here this condition would remain the same we will be returning the root as well but this insert would go from here and over here will take a q in the queue initially we will add the root variable or the root node and then we will try to iterate over this tree so firstly till we are reaching the d minus 1 level we need to do nothing once we reach the d minus 1 level at that level all the nodes that we have are the ones that will be needing for further processing so for that we'll need a variable that is current depth let's take this variable itself and this would be 1 initially and we need to loop while my current depth is less than d minus 1 and in this while loop will take a temporary q so inside this as we write for our normal operation we say while q is not empty we would need to remove an element and then adds left and right into the queue but over here will not add in this queue we'll add in the temp queue because these left and rights would be for the next level so what this loop is effectively doing is that it is trying to put all the nodes at the same level in the temp node and this same level is nothing but the level which is current depth plus 1 after we come out of this loop we will increase our current depth and we will put all the nodes that we have found in temp into our queue so what is happening over here is while i am at d minus 2 level in that case this temp q would contain all the elements or all the nodes from d minus 1 level and while i am doing this q equal to temp i am getting all those nodes into my queue so after i have terminated this while loop i'll have every element on the level d minus 1 in my queue now i need to perform all the operations that are present over here so we'll again take a while loop while the skew is not empty so now over here in this while loop what i want is i want to perform all these operations so i'll take this and i'll paste it over here and i want this node so i'll take tree node and this is nothing but q dot remove the node that we are removing from the queue so that's it let's delete everything that is not required and let's run this so it runs perfectly fine let's submit this and it got submitted so the time complexity still stays of n as in the worst case we are going to iterate over all the nodes and the space complexity would be the maximum number of nodes that can be there for a level that are going to go in my queue or the skew so that's it for this question guys i hope you liked the video and i'll see you in another one till then keep learning keep coding
|
Add One Row to Tree
|
add-one-row-to-tree
|
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`.
Note that the `root` node is at depth `1`.
The adding rule is:
* Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with value `val` as `cur`'s left subtree root and right subtree root.
* `cur`'s original left subtree should be the left subtree of the new left subtree root.
* `cur`'s original right subtree should be the right subtree of the new right subtree root.
* If `depth == 1` that means there is no depth `depth - 1` at all, then create a tree node with value `val` as the new root of the whole original tree, and the original tree is the new root's left subtree.
**Example 1:**
**Input:** root = \[4,2,6,3,1,5\], val = 1, depth = 2
**Output:** \[4,1,1,2,null,null,6,3,1,5\]
**Example 2:**
**Input:** root = \[4,2,null,3,1\], val = 1, depth = 3
**Output:** \[4,2,null,1,1,3,null,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* The depth of the tree is in the range `[1, 104]`.
* `-100 <= Node.val <= 100`
* `-105 <= val <= 105`
* `1 <= depth <= the depth of tree + 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
241 |
all right let's talk about the different ways to add the parentheses so given a string expression of number and operator so you have to return all the possible results from computing all the different possible weight of the group and then you want to return the answer and this is the idea right so two minus one and if you add a parenthesis you will get this one right and if you add another parenthesis you get this one right and this is pretty much the possible outcome for two minus one and then for two times three minus four times five right you will get five different possible way to do this and in this question so uh we are actually we need to use the recursion solution so when we see the applause when we see the minus and when we see that multiplication then we just have to split the string for the left and right and then until uh until the integer so if there is a symbol like it's either plus minus or multiplication we just keep splitting and then if the base case is the integer right the base case integer then we just convert the string to integer i so the expression is string right so we have to convert to integer and then we will just add to the y add to the expression so we'll just do the math right and this is pretty much it right so let me start doing this so uh you want to use a hashmap to store the possible outcome because you'll get the duplicate uh a duplicate substring when you try version right so i will have a hashmap using a string for a key and then list of integers for the full value right i'm gonna call that new hashmap now uh i need to traverse so before i traverse i need to create so i have to create a chart c so i'm going to determine whether or not the current char in this expression is either plus minus or multiplication right so i would say expression dot chart or c equal to multiplication i will do the following create the left side of the expression and right side of expression so base of integer left equal to uh equal to different ways and then i need to create an expression substring right substring this is going to be y this is going to be zero to one two i right and then comma right equal to a different way expression the substring a i plus one right and using after i right so now i will get what uh so when or once i keeps uh keeps splitting right uh the base case is going to be the integer right so uh this is not the base case right over here so uh after i traverse so if the result uh the list of integer is empty so i know this is the integer substring integer expression so i will just say resolve the add integer the parsing now just passing closer expression right and then i would just put that into my map right so i know the current integer is going to represent what uh represent this string right so this is going to be one expression comma and then result right so i'm adding a result to the integer and at the end result right so now i haven't do any multiplication or addition and subtraction right so i'm going to traverse the left and right so in picture left for in picture r right so if one if c equal to is c equal to plus this is going to be resulta l plus r right i'll say c equal to minus raised to the i l minus r house is c equal to multiplication result right so this is the three different way of the operator right so resulta is empty will convert the current integer into i'm currently stringing to integer right and then i will have to do the multiplication uh subtraction and addition later on so uh at the end you'll get 20 in this case so two times currency three minus 20 right so 3 minus 20 is 17 right so you'll get 17 and 17 times 2 i mean the negative 17. right all right so this is the uh this look pretty good but the problem is you when you use a hash map you need to check do i ever traverse this substring before so if the network contains the expression if i do then i will just return what i have right and this is pretty much it so let me start funny yes so let's talk about the timing space so for the space this is going to be one this is going to be all fun right for every single recursion solution you create another space left and right of the leftist one uh oh all of l right and right is all of r but all of l plus all of r is actually all of m right and we all we already know we have our opponent already and this is like a square right so a square full of space and then for time this is all of n and this is going to be all of them as well because the left and right number is inside the expression right so the time and space are n squared and this is the solution and the idea is using the memorization recursion so this is a uh the end of the video so if you feel helpful subscribe like and i'll see you next time bye
|
Different Ways to Add Parentheses
|
different-ways-to-add-parentheses
|
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`.
**Example 1:**
**Input:** expression = "2-1-1 "
**Output:** \[0,2\]
**Explanation:**
((2-1)-1) = 0
(2-(1-1)) = 2
**Example 2:**
**Input:** expression = "2\*3-4\*5 "
**Output:** \[-34,-14,-10,-10,10\]
**Explanation:**
(2\*(3-(4\*5))) = -34
((2\*3)-(4\*5)) = -14
((2\*(3-4))\*5) = -10
(2\*((3-4)\*5)) = -10
(((2\*3)-4)\*5) = 10
**Constraints:**
* `1 <= expression.length <= 20`
* `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`.
* All the integer values in the input expression are in the range `[0, 99]`.
| null |
Math,String,Dynamic Programming,Recursion,Memoization
|
Medium
|
95,224,282,2147,2328
|
343 |
Hello everyone welcome back to my YouTube channel discussing our today's problem interior there will be a number in it like how can I do this for free 406 420 you can subscribe ok this is how you break it in Only after break, you have to return whichever product mixture is mixed with your ghee. Okay, so now how will we do it, I am a team, first of all I will tell you about DP, Deepika is better than Soni in this, DP is better. There is a solution which is optimized from the solution that the film will discuss every time, it is not that the solution of DP should be optimized, just like Taylor Swift, it is a little logical, we can do the same except for Deputy Ranger Pradeep, if we get it, then we do not know that If we love the pan that has done the first lesson, then we don't have that credit, we don't have this last ki tank, at how many passes should I break, if I want, I can do that in 25, if I want, I can make it close, okay, this is also okay and this Which press should I do first? Okay, if you don't know this, then what will I do? glutes core, I took part I from it, okay, so it was like that tank, I broke it, that's a Mirage solution, Manawati award, one drop, pieces, six, okay There are 14 crops to make one quite high profile top ghee out of which to do and it is my duty that it has been taken out of me to give you the function of means that subscribe to my channel the product which I have taken and After that, I took the problem and said that the express train has come in 272, this is a possibility, now I can say that this is the only answer, it is not necessary, it is also possible to * Function of 812 21 1999 possible to * Function of 812 21 1999 possible to * Function of 812 21 1999 is fine and 525 means. That I will try to find the first so I have taken the first step here subscribe you all that problem subscribe I have maximum product we will reduce the sound completely okay that means do macrame in the gas of time 312 Function of Seventh Now Because it is being calculated again and again, like in any case, it will be calculated for my seven, for it, for remind, for the pipe, for the middle, that now the phone will come from a plate, okay, now you are facing the problem again and again. So, there is ghee in it that you make a sketch of the universe general, what do I have to do, that according to the function of, this is my ghee to you, first of all, I take some of these, I took part of these, okay Pintu, function of n, the rest of that which is left. By breaking it, the maximum result is by taking it only with the maximum, I do n't know that 215 has no one to take the person's fat, that I am fine or will do it and if it means that in 2014, one third of you are working for me that And like I will sacrifice angry calculator medicare, okay then all that problem of buying or you can do it for free at home, then the maximum that comes out of it will be brought as my solution but this is not my complete reference in relation, okay in this too The thing has to be kept in mind as we take that I took it from here so I said that five is my co worker so I back to * is my co worker so I back to * is my co worker so I back to * Function of Misery Tips divided into parts into function of time and * * * * function of time and * * * * function of time and * * * * are those moments vansh this in Candy Crush Loot Function Now the maximum of this will be that this is the problem it means I can subscribe per three that these two I will not call you because I have a maximum of 21 Bluetooth okay it will be immediately and but I will do like this Two into three, medium size of veins, sitting butt. The answer is six, so it means that my statement is not complete because I have divided the list into two things. There should be two things that I have mentioned this thing. If I do not break these two, then it will be my fault. There may be a difference in Delhi like maximize the maximum products that if I do not want this for me, I also want to write a confused record that I am continuously doing maximum then what changes will I make in this that like I have got a function job then put this. Or free is fine, that means my answer will be two * free and two * function will be my answer will be two * free and two * function will be my answer will be two * free and two * function will be Jones maximum from the northern complex, he will be my financier, so how will I change it, to solve the function of n, it is assumed that equal to two, so it was okay. That I took one that * Maximum of I took one that * Maximum of I took one that * Maximum of that we turn off N - K and prescription that it tells that which is my last part like to the function of I body without break My answer is obviously that I break three So it will go but you do this that if I had fiber then * Function 525 that if I had fiber then * Function 525 that if I had fiber then * Function 525 was done in the same way but Mittu * Only was done in the same way but Mittu * Only was done in the same way but Mittu * Only fabric jhal then this my guy can but if I had broken Friday in two three then how many points will be my answer those people yours are mostly right So, to see that instead of without a break, an innovative 1000 break cigarette can be made to the maximum for that. * break cigarette can be made to the maximum for that. * break cigarette can be made to the maximum for that. * Now we are seeing that whatever you want, if this is also its this, then by the way, the total and the product is fine now. I like it, I want to, I moisturize, the definition will remain the same that we have to convert the tablet into Amazon, that I have to calculate the problem every moment, then my right came in place of and because we have I mean intermediate solution. By incrementing the ticket, we will implement the small solutions till the end of the year and then move ahead. Okay, you will replace them. My Tuesday DPI FIC code to K times maximum of DPO of According to * the prescription According to * the prescription According to * the prescription that now a virgin can go from Mary can become roasted then it means that Aamir of this temple is okay so because my cousin it is absolutely either it is in the loop how will we write mine till what in the final there is no With a jerk Isa defend witch denotes function Madhu Ghee If they should be divided, then my in was function friend, then mapping from him to him only differences, now I had to go till depend, okay, what will be the base of Abe, look, if you dip in it, then message can't be only one. That video can be to, you can be divided into 2 parts like 121, if someone is divine, if you can, then how should you blame for this, then how can I base it, how can I look for any meaning of two, how can you write, you can send a message to two1 * Function Open tell me two1 * Function Open tell me two1 * Function Open tell me how do I divide the pieces? There is only one way. 121 is ok, it means that the value of my function one should be 1. Ok, the function of 0550 has been used since then it is not an indulgence. Ok, only functions have been invented since late. By the way, this function of To, I will never write like this, To * Function 90 So, write like this, To * Function 90 So, write like this, To * Function 90 So, from the heroes of the beginning till the end, my team wants the final different, so at this time Nadal, Ronit, you should not start folding, it is okay from here, then definitely why. Vijay, my one-and-a-half benefits come - why. Vijay, my one-and-a-half benefits come - why. Vijay, my one-and-a-half benefits come - wait, have you got this done, this is absolutely correct, so one-third of mine is - which should be absolutely correct, so one-third of mine is - which should be absolutely correct, so one-third of mine is - which should be calculated first, so it means it will be like this in the show, okay, this is my whatever. The limit is there, play the to-do this is my whatever. The limit is there, play the to-do this is my whatever. The limit is there, play the to-do list and there was more change in between, from one to MLA supporter, okay now the questions come and 10 of this ruthless Kepler, I am not there, what is the value here? If she does this, then I will kill her like this, if not, then with me all through the internet, like I will kill her along with this, I will kill you for this, take my maximum off, okay, in Hindi PDF I - K Ajay Ko Ki and here pregnancy If you care about Ajay, then here is my relative A Saiya, once you see that right minute in the beginning, when I will see that young man, maximize it so that any of my when I point to the first letter, replace it with that. Okay, so like I replace 345 and I am leaving, okay you started Ghee in The Intern, so that whatever decision is element should come here, it should come in my mind so that I can compare it with the rest and find the minimum element joint. I will do it, set the maximum, okay, let's look here and there * If it okay, let's look here and there * If it okay, let's look here and there * If it is the maximum, then this was my final solution, once verified, Abhishek Bachchan seems to want a limit, so this was from the serial, so this would be my interior decoration because I have. Kitni chali meri chali - - - - - - You can subscribe if we do general knowledge about water kingdom, then it is difficult to find out, if you can subscribe for extra missions and difficult issues, then it is okay, if you tell us in a logical manner, then like Where is my device that 2016 is ok so let's decide together as much as you can reduce the difference between the two numbers ok that much is mine and that product will come ok now this is our people it is like n2h So it was found above the label of 11650 two plus one and two minus one so it was that if I do that my to-do - 2 - I do that my to-do - 2 - I do that my to-do - 2 - their product between the two numbers will be that much less. This should be done so that its There is a difference between all the things that I have to do something like people do, this is Chanakya's way, I can divide Trikudi * There Chanakya's way, I can divide Trikudi * There Chanakya's way, I can divide Trikudi * There is only one way and how can I divide it, then withdrawal, because when we talk about it in two, then It will give maximum result 22824 There is no use in dividing because if I do Tubelight, I will get 113 kilos of Battu * Need 500 more difference Free How to Win Today Satta Ka Matka 22222 Whatever is in it will be made Divided into three in 1995, journey completed If I can then I can achieve one can by consuming it and I have just entered this paste in between the numbers, how can I generate points and so on etc. So 1424 is fine but how did I do this point, fake points. 258 e want now look this is this solution we will feel that its last a solution inverter look what did I see moment that you are * * which is the what did I see moment that you are * * which is the what did I see moment that you are * * which is the answer to this wish is fine from train two three so that its sandhya vandan six but for this I am free I will live as per my wish, so it is okay that whenever I do whatever is my to-do, which is death, that whenever I do whatever is my to-do, which is death, that whenever I do whatever is my to-do, which is death, if its frequency is Mother Great and Free, then I will tell her that one thing, if I convert it in the fridge, then what is my answer to this? Apart from this answer of mine was not there, okay, then I will convert it into this, it is cream, tomorrow I will go to college, now this leg has been taken by me, my Ko has also gone to the 10th, my Aa is 512 fairer 18238 * * * three, okay then. This statement of mind is fickle to* to* to* that tunes 2323 has come inside the hands of till I find 12372 from the other side that the doctor means that is constant for thirteenth which was mine in the beginning1 had made it It was made here also, okay, after the key four of butt, which are inside me, it is okay and after that, I have only two numbers in it, so the entry will remain till Lal Yadav end, only two numbers of mine are all 2 F 3, out of that also I said. That I go to divide them like I have only one way to * I have only one way to * I have only one way to * So such a point they look at this properly it means that 341 323 is the highest I will not first of all find the T-20 weight I will not first of all find the T-20 weight I will not first of all find the T-20 weight like a tent you till my phone Where is less use okay because if my phone is four less if try to appoint a closet then my it we becomes less because was broken pre appointed that okay so I this is when Till my number is greater than four divides that best like it is given to me so in this is given then convert it into country at Indian then I have my number what is cigarette and sa is ok so my number is cigarette front part Which one is it, then my number will be made great and so I took the first part, so how much do you have left, tennis is still grade four, so I took it for the second part, so I felt like it, then I took my favorite or a follow, I am not studying. I will do that by dividing by and then I have that if I take this three then its time will become 193 but it is okay not to take that because we want to avoid one because it will be able to bind and if a small answer comes then if we take to-do then our and if a small answer comes then if we take to-do then our and if a small answer comes then if we take to-do then our Ancestor, what is the receiver, I wrote it like this, turn off the flight 19 channel, this product, which is my product, is equal to a, okay, then at the end, multiplex it into one product, whatever is left is my selection, so it is that whatever. I can do it's ok, then I will see if it is any number, I have divided it by that number, the way it is ok on my motherboard means that I can do it even in the login, so you will have to see a little, you can apply conditions etc. Now we can calculate the end on this so that I have to do the maximum vehicle Abbas Baahubali. Urmila towards the Deputy Election Officer, this was mine, that is the end, we can also do it from off people. Okay and you see this, you have to three in this way. That the government is selling flats, that number means it has One and Kairana, okay, so just see this for you and how you liked the sale in the beginning, you can start first, okay, so this was all about this video, if it is antiseptic, then the video. songs in video
|
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
|
1,751 |
hello and welcome to another leak code video today we're going to be doing the problem of the day for July 15th maximum number of events that can be attended to and so you're given an array of events where events I start day and day in value and the ith event starts at start day and the end day and if you attend this event you receive a value you're given integer K represents the number of Maximum events you can attend you can only attend one event at a time and if you choose to attend the event you must attend the entire event note that the end of the day is inclusive that is you cannot attend two events where one of them starts in the other ends if you're in the maximum of values you can achieve by attending the events so let's go through these examples so for example one what events do we have so we have event one two four and then we have event 343 and move event two three one so just draw these on a number line right so we have one two three four okay so event number one goes here event number two goes here and event number three is here and let's write the value so the value here is four the value here is three and the value here is one so when events overlap you can't attend both of them and so this one is pretty straightforward right we want to attend this one and we'd want to attend this one we also have two events we can attend so we're going to attend these two events and we're gonna get a seven points so let's go to the next example here and so let's go down here so we have event one two four and we have event three four three and we have 2 3 10 and we can only have 10 to 2 . yeah let's draw them on a number line . yeah let's draw them on a number line . yeah let's draw them on a number line again so one two three four so we have one two it's worth Four Points three fourths or three points and then we have two threes worth ten points so we can attend two but we don't have to attend two so we're actually going to take this event here and we're going to attend this one and we can't attend either of these because they overlap so we're going to get 10 points here we're just gonna attend them one event and then for the first for the last example um we're gonna draw it again right so actually we're not going to draw this one but you can see that the first event starts at one ends with one then two and three and four and we can attend three events so if nothing overlaps and we can attend three events we just pick the highest like the biggest three so we're actually going to break this down into two parts for the problem we're going to break it down to two parts and we're going to solve both of those and then from there we're going to get the intuition and how to solve this problem okay so let's break it down first of all we need to recognize this is an intervals problem because you need to attend one thing and then it needs to finish and then you need to make sure there's no overlapping time so this is an intervals problem so first we're going to sort it right so number one regardless we're going to sort okay so now I'm going to give you an example of some events and then we're going to figure out kind of what we're doing okay so let's give let's get some events here so we're going to have an event here one two four and we're I'm just going to write these out in sort of order because we are going to sort them then we're gonna have two three one then we are going to have two four eight then we're gonna have three four three and finally we are going to have 465. okay so we're gonna solve two problems here and from that we're going to get intuitions and let's number one we're going to sort okay now our first problem that we're actually going to actually problem is let's say that we attend some event so let's say we attend event over here well how do we figure out in an efficient way where is the next event we can attend so let's say we attend here you know the event starts at one it ends at two how do we figure out okay what's the next event we can attend and how are you going to do that right so let me actually get another color here let's actually do this and let's do this okay so let's say we attend this event ends at two right so it's start and end value how do we know what to attend well we could just go manually right so we could just say all right we'll attend something we'll have an index we'll keep going down and let's just you know let's try this one okay we can't attend that because they overlap right because if this end if this ends at two then the next event has to start they can't start at two because if they're the same value they overlap so then we're going to go over here can't attend this one and we're gonna go over here and this is the one that doesn't overlap so this is the one we can intend next now is there a more efficient way of doing this like let's say we just have like 10 000 events do we have to go one by one which would be of n well there is a more efficient way of doing this right so because we have at the index of we're at like let's say this is a valid index if this is a valid index that we can't attend then we know that like this is a valid Index right because anything to the right is going to be bigger or the same right so anything to the right is going to have this left value bigger or the same to what that one was and anything to the left like let's say this one was not allowed then anything to the left is not going to be allowed right so now we're kind of getting a we have a sorted list we're looking at start elements and we're trying to find what's the first value right an even simpler problem what's the first value greater than two right so value greater than two and we can just we have access to all these start elements well and we and they're sorted so how do we do that well it's pretty straightforward we do a binary search so we can actually do a binary search here to get the first value like the first valid interval we can go to right pretty straightforward that's going to be M log n so that's the first problem we needed to solve now we have another problem so problem number one binary search pretty straightforward right if we have some interval in a sorted array we can figure out where to go okay problem number two so let's call it three how would we solve this problem I'm actually going to delete this stuff for now so I'll just say two you know we're going to say binary search we have that solution right so we're going to say next interval to go to all right so we solve that binary search or just call that BS okay and it's going to be n log n time second problem how would we like let's say we have we can attend let's say k to like two events so we can attend two events now let's just get rid of the fact that these events have coordinates and let's just change the problem to if we can attend two events which events do we want to attend so ignore these coordinates let's just say we have an array of values right so we just have an array of values like four one eight three five how do we actually do this problem right so let's actually go down here how do we actually do this problem we can attend two events and how do we do this right without doing some kind of list Max like with a dynamic programming way because we can't do a list Max because we have to maintain the order so with maintaining the order without doing just like a list Max of like the two or three biggest elements how would you go one by one and determine which elements you actually want well what choices do we have at every element right so let's say we're over here what choices do we have so we have some index and we have a elements that we have left to take right and let's just draw out some base cases so let's just say we have an index as our parameters and like let's just call it El where El is the number of elements that we have to take still right so let's say we're over here and what are our choices well it's pretty straightforward let's just draw like a diamond dynamic programming solution for this okay well so if the index is out of bounds right so it's greater than let's just say array length or something array length right then how many elements can we take well it's going to be zero now same way in a dynamic programming solution if this is cached we can return that but let's say like what choices do we have if that's not the case if we aren't out of bounds and when and we're picking well it's pretty straightforward we can either take it right and then our K would reduce so then our next location is going to be index plus one right our next DP is going to be index plus one and then the number of elements is going to be elements minus one right or we cannot take it so not take and then our next index is going to be index plus one again right and now our elements left to take is still elements and so when we do take it we're obviously going to add the value right so we're going to say like Value Plus this and so those are our two choices so it's kind of like a House robber problem where if you boil it down to let's just ignore forget all the indices forget when it starts when it ends let's just say these you just have values like let's break it down to the simplest version of this problem so we can either take it or we cannot and then we're going to maximize here right so we're going to Max this choice so max of these two things okay and so if you just have the value it's a pretty like could you solve that problem right you have an array of these numbers you can't just call like dot Max or whatever you have to go one by one how would you do a DP version where you just get the max values so you can literally just add every single index you know and cache it as well just either take the value or don't take the value if you do take the value then you have elements minus one left and otherwise you have elements and then also another base case would be when you have no more elements left to take you can also return zero right so your two base cases are you're out of bounds or you have no more elements to take but essentially this is the dynamic programming solution for this simple problem but how do we take this simple problem and transform it into the problem that we have right so we know how to do this part now where we know how to do a DP here with no with nothing but how do we actually take these indices so because this is sorted essentially all we have to do it's pretty straightforward right so if we don't take so let's just go number four right and let's just write out some stuff so we have a couple choices so a if we don't take the value index equals index plus one right that's pretty straightforward so if we don't take the value then we just go to the next index because in our intervals if like if we don't take this then we can just go to the next one and try to take that but what if we do take this like what do we say we want to take this value well we can't just go to the next index because they might be overlapping right we have to find the next available index and how do we find the next available index well that's problem number two right it's I just said if you take an interval how do you find the next available interval to go to well it's a binary search and so let's write that as well so if we do take the value binary search to next available value and now we have pretty much everything we need to solve this problem except we do need a couple more things so let's go over that so this is like we're going to do a DP of a simple you know like a House robber or either like you know Rob the house or don't Rob the house we try to maximize if we do Rob the house then we have to binary search to the next available value and if we don't Rob the house we just go to here over here but there is one little optimization where we do this binary search there is an optimization because we might get to the same value and we're going to be binary searching from that value multiple times right like for example you know let's say we take here or sorry let's say we you know whatever take here and then don't take and don't take somewhere else and you know you can get to the same thing twice like for example actually I can give you a better one so let's say we would take here and then we you know can't take here and then we uh yeah so we can't take here let's say we take here so that's one case right we take here and we're gonna do a binary search over here but what about if we just go don't take care also do a binary search so you can see like in a big array you're going to do the same binary search multiple times and so not only do you want to Cache this DP you also want to Cache the binary search so cash here and we want to cache in our actual DP so cash here now that we cache our binary search and the DP how many times would we have to binary search maximum so it would just be n like the only plate uh you would have n places to binary search and so to get the binary search from every single index would be n log n time right because we're doing n binary or every binary search takes logs n and we're doing n binary searches and we already sorted right that was like our first step so this doesn't cost us anything so we're gonna have a cache of binary searches we're going to have a cache of DPS and now we kind of know let's break it down one more time right so we're going to start it every we're going to have an index and a number of elements left we can either take the value not take the value try to maximize it if we do take the value we're going to buy a scenario search to the next possible location now you could do this binary search one of two ways you can just binary search every single index in the beginning and just store those and then every binary search is going to be all one time in your DP or you could as you're calling binary search you know check kind of like a DP check if it's in the cache or not and so that's the approach I'm going to take but either one's fine okay so now we have enough to actually solve this so let's go through the solution here and I actually have it coded so let's take a look so we're going to sort the events right like I said we are going to have a binary visited cache as I said before and we're gonna have a visited cache which is actually for this DM sorry the visited cache is going to be for this DP and then the Buy Revisited cash is going to be for the binary search so the binary search is pretty straightforward right like let's say you visited an element let's say we visited this element we just take the this value here and we need the first element that has a start value of greater than this two right that's what we're gonna do because if it ends with two then we need the first element that has a start value that's created in this two which is going to be over here and so that's essentially what we're doing in this binary search so we are saying if it's already in our cash let's just return it we don't want to be repeating the same work but otherwise the end event is going to be events index that one we're going to pass in an index of like what element we actually visited and so let's say we visited this element index that one is where it ended right so it ends at two and then we just do a simple you know binary search not going to go too much into depth about this where we're just getting the first element that's to the right of where we visited pretty straightforward and we also need to check if we do we might not have like a valid location and so if we don't have a valid location like let's say we visited the last thing we're just going to return the uh length of events and then we're going to go into the base case where you know like let's say we've actually visited this last thing and there's nowhere else to go we're just going to return the length of the event and that way when we DP to that's just going to turn zero because there's nothing else to take so that's like our default case where if we don't actually have anything that we can go to okay so now in our DP so like I said we have two things we have an index and an events remaining just like I showed in this picture right so we have index and events remaining and what we need right so index here element number of elements left same exact thing okay so if the index is greater than or equal to length of the events that means that we are out of bounds and we can't take anything else or events remaining equals zero we can't take anything else either right we already took all the events we could we can return zero that's our base case then once again a normal cash you know if this combination is in our visited hash set hashmap we're just going to return that now we try to maximize the results so you could even write it in another way you could just maximize between these two essentially right so I just you know wrote it like this to make it uh fit but essentially we can do one of two things right so here what are we doing we are taking the element so that means this is what we're doing over here so we're saying okay if we take the element then where do we need to go to and what value do we need well the value is going to be event index two right so let's say we take something here 2 is the value so this is the value here and then where are we actually going well we're we have events remaining minus one we took an event and then we're going to call binary search on the current index saying we took it and give us next index to go to pretty straightforward now if we didn't take it what are we doing our events remaining stay the same and we can just go to the next available index we don't need to do the binary search there then we simply cache and return it and finally our you know initial return case is let's return DP where the number of events we have remaining is K right because we have K total events and we're going to start at index zero so let's try to submit that should work yeah okay and let's actually go through the and by the way so yeah so I would recommend for hard problems when you first when you look for Solutions look at the constraints and those are going to give you like a big hint of what things you can be doing so if you see this K times events length is 10 to the 6th that means you can't really add any you can't really add another n over here right because then K could be like 10 to the third and that would be 10 to the ninth it would fail so you either have to have a solution that uses this or maybe like this and log n or something but okay so let's go through the time and space complexity here next so for the time what are we doing so sort is n log n where n is the length of events that's already n log n okay binary search remember the most binary searches we can possibly perform is going to be n log n so we already have an N log n for the sort so that's totally fine and once we perform n log n binary searches we're going to have o1 binary searches and like this is what I meant by you could Loop here and you could perform binary searches for every index so you could just say you know for every index uh in the list let's do a binary search and all these will be over one binary services but either way the most binary searches we can possibly do is n log n so that's not going to cost us anything now in this DP events remaining is K and the index is n and so this is pretty much our so it's actually this is our um complexity where it's n log n plus K to the N because M log n is the time you need for the sort plus the binary search but once we actually do every binary search all of these binary searches are of one because we're caching them remember if we didn't cache them it would be more expensive and so if you look here K times n the most it can be is 10 to the sixth and then I think the most n can be is like 10 to the sixth I guess technically as well right so the most this could ever be is like 10 to the sixth Times log 10 to the 6 plus 10 to the sixth essentially which would should pass okay and so now let's think about the space so what are we doing and what are we storing so for the binary searches that's going to be o of n because we can only do that n times so you know we only have n indices and so if we cache that's going to be only n now for the events remaining that's going to be K times n and so this K and times n is bigger than the N so our total space is K times n for the cash this cash right here right then all the combinations we can have is events remaining can be up to K and index can be up to the length of the list all right so I think that's actually going to be it for this problem hopefully you like it and hopefully I explained everything pretty well I think I definitely did a good job of trying to break it down into base cases for you to make it a little bit easier but yeah if you did like it then um please like the video and subscribe to the channel and if you have some comments you have things that can improve and things like that please let me know in the comments below and I will see you in the next video thanks for watching
|
Maximum Number of Events That Can Be Attended II
|
slowest-key
|
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend.
You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return _the **maximum sum** of values that you can receive by attending events._
**Example 1:**
**Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2
**Output:** 7
**Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
**Example 2:**
**Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2
**Output:** 10
**Explanation:** Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events.
**Example 3:**
**Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3
**Output:** 9
**Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
**Constraints:**
* `1 <= k <= events.length`
* `1 <= k * events.length <= 106`
* `1 <= startDayi <= endDayi <= 109`
* `1 <= valuei <= 106`
|
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
|
Array,String
|
Easy
| null |
1,567 |
hey there welcome back to lead coding on this channel we discuss problems which are frequently asked in programming interviews today we are here with a problem called maximum length of subarray with positive product in this question we are given an array of integers we have to find the length of the sub array where the product of all its element is positive now if you see the first example we have the product of the entire array as 24 which is a positive number and hence the answer is 4 in this case if we see the second example we can consider the product from 1 minus 2 n minus 3 and this is the value of this product is 6 which is a positive value and 3 is the answer in this case if we consider minus 4 again it is going to be 24 negative 24 which will not be a positive value hence we are not considering that neither are we considering 0 because we have to obtain the positive answer it is mentioned that it should be a positive product it has not mentioned that it should be non-negative that is why we are ignoring non-negative that is why we are ignoring non-negative that is why we are ignoring the 0. now let us try to see same through an example the very first thing that we can observe is if we have so in order to obtain the product as positive the first condition should be all values as positive this is the first condition the second condition is number of negative values even so if there are uh negative values and the count of those negative values is even in number then also we can have this the product as positive so now if we consider an example where we have 2 minus 2 3 6 4 minus seven minus nine two nine okay now here we see that the number of negative values at one two and three so it is orange number what we can do in this case is we can either think of eliminating the first negative value if we do so we have to eliminate the starting part from the starting till this point and the answer will be from the very next element till the end so this is one possible option another possible option is to eliminate the last negative value and if we eliminate the last negative value we are going to eliminate the entire part which is after this negative value and the answer will be from the previous element till the start so this will be the answer in this case this is option number two so we are going to have two options if there are uh odd number of negative values in case we have even number of negative values the answer is simple it would be the size of the entire array if there are no negative values then also the answer will be the size of the array so this is the third case where there are odd number of negative values and we can either eliminate the first or the first negative value or the last negative value so whichever is beneficial we are going to go with that now there is uh the case of zero how we can handle that so if we say that we have a 0 in between 3 minus 6 0 9 8 minus seven six so there are two zeros here we don't have to do anything uh it is the same as the previous problem but we are going to consider each of these parts separate now so this is the first array this is the second array and this is the third array now we have to apply the same thing that we have applied over here to each of these and then we have to maximize the answer the global answer so each of these will have two options and we have to maximize the global answer according to those options let us try to see the same through the code in order to have better understanding i'm taking n as the size of the array and i'm going to run a for loop uh there's one more thing as i said that we can consider each of these as a separate array now instead of cons instead of making the array uh out of each of these what we can do is we can simply run an iterator from starting to ending and we can mark out the start and the end points so this is the start this is the end in the first case now we can run the algorithm from start till end now again we will have this as start and this is end and again we can run the algorithm from starting till from the start till end and then we can simply keep incrementing the start and end now we will see how we can do this through this example to this code i am taking i from 0 smaller than n now this will be my start which is equal to i a bit of cleaning over here while start is smaller than n and nums of start is equal to zero we have to increment start my and is equal to start initially and while and is smaller than n and nums of n is not equal to zero so this is how we are going to obtain our start and end so initially both these start and end will point to this position because i is zero initially and now we will be incrementing uh the end till the point the first zero comes so and we'll come over here start william over here now we have to apply the algorithm that we have discussed over here from the start till end but that we can do uh at the same time we are traversing this end so in case you obtain a negative value in case we obtain a negative value while going nums of and is smaller than zero we can do c plus where c is the count of uh the negative values now as we saw over here in the third case yeah in the third case we see that we have to get the position of the first negative value and the position of the last negative value so in order to achieve that i'm going to take two variables these start negative initializing it with minus 1 and the end negative initializing it again with minus 1. if the start negative is equal to minus 1 so this is my first negative element yeah this is the first negative element that i'm going to obtain start negative is equal to end and in any case if it is a negative value i am going to overwrite the and negative so now we have the start negative and the and negative also the count of the negative values as well so if the count of the negative value is even a number then we can simply have answers equal to maximum of answer comma the end minus start initializing the answer is zero else if the start negative is not equal to minus 1 then answer is equal to maximum of answer comma and minus start negative minus 1 so in this case we are considering from the end till the start negative minus 1 so basically in this case we are considering from the end point which is the last actually not the last uh the end will be and index which is after the last so this minus this thing they start negative so we are having the count of these element plus an extra element that is why we are doing a minus one over there so this is the number of element that we are going to obtain in this case if and negative is not equal to minus 1 then answer is equal to maximum of answer comma and negative minus s now in this case we are eliminating this we are eliminating minus nine so we are doing the end negative which is this point minus s the starting point so we are considering all these elements finally we can return the answer let us try to see it is giving us tle one thing that we forgot is to increment i now what should be i uh i should be i plus or i should be equal to and plus one so i should be equal to n plus one basically uh if we see how we are going to troubles this we are over here after the first iteration we are over here this is end and we should not start from the index one we should rather start from the index which is after end so that's why i am incrementing i as n plus one in this case also if it is the end then i should start from here now let us try to run this four three two one four let us try to submit it got accepted now if we discuss the space anytime complexity first of all we have not used any extra space over here so it is a constant space solution there are only variables the next thing is the time so from the very first look it might be the case that you will think it is a n square solution because there are two nested loops but that is not the case of course because we are incrementing i as n plus one each of the element we are going to visit only once so that's how the time complexity of the solution would become a linear solution the time complexity would be big o of n each element is only visited once so this is it for the video if you like the solution please subscribe to the channel thank you
|
Maximum Length of Subarray With Positive Product
|
maximum-number-of-vowels-in-a-substring-of-given-length
|
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return _the maximum length of a subarray with positive product_.
**Example 1:**
**Input:** nums = \[1,-2,-3,4\]
**Output:** 4
**Explanation:** The array nums already has a positive product of 24.
**Example 2:**
**Input:** nums = \[0,1,-2,-3,-4\]
**Output:** 3
**Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
**Example 3:**
**Input:** nums = \[-1,-2,-3,0,1\]
**Output:** 2
**Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\].
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
|
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
|
String,Sliding Window
|
Medium
| null |
1,043 |
Hello friends welcome to my channel here Sol called problems today's problem number 1, 43 partition array for maximum sum medium level given an integer array R partition the array into contigous subarrays of length at most K after partitioning each subarray has their values changed to be the maximum value of that sub array DET return the largest sum of the given array after partitioning test cases are generated so that the answer fits in a 32 bit integer so we need to partition some array into subarrays at most with size at most K with total maximum sum how we can do it I will solve it recursively and uh What uh what I can do for instance we have some sub problem some problem like sub some array like this with k equal to three so we can divide this array into Parts with uh size three at most so it can be one two or three so each uh in russion function we will find sum of each subarray started from the beginning for instance uh for instance we can get one subarray with size one and with some one and recursively call the same function on the rest array for instance here call F it's one option second option it's could be so we have same array we can use two numbers with maximum value two and two items so the total sum four and the rest array Ela we need to call the same function uh for the rest of array and third option we can choose three items with maximum value three and total sum nine and the same fun the same function f the rest two items and we need to find recursively some result so it can be R1 R2 and R3 and we need to choose the maximum value from R1 R2 and R3 and return it and after recursive recall recursive calls we will find the maximum result for the whole array so let's implement it first of all let's define the reive function helper with one argument start is a started index when we are calculating some we need some variable for result is the final sum which we need to return and also we need helper value Max sumal to zero Max SU sum is in our example is the sum of the subarray so in our example for the first it item Max sum equals to one the second two items Maxim is two so it's the maximum of the subarray uh in the third line the ma Max sum is three so we and we need to check all subarrays so we can do it I here is a the end of subar so I is like of set so it's start so it's items after start so if um so we need up to update Max sum so max sum is the maximum value of current Max sum and current item is a start plus I so if we have k equals to three we can have three subar including only start plus start and start plus one and the start plus one and start plus two so three items and uh we need to update result maximum of result and here we need to do the same things so we need to multiply Max so for instance here Max sum three and we have three items so we need to calculate it Max sum multiply by number of items so it's Max sum multiply by number of items equals to I + 1 and plus recursion code of start loose plus I + 1 so uh the next russion call will be started From Start plus one start plus two or start plus three depends or then we uh how many items we use in calculation and return result in our main function method return function helper with index zero so we need to find the maximum sum of all items started from zero let's check test something wrong um we need to start a mistake we also need to check if start less than the last item of our array so we need to check indexes so test pass submitted time liit it's possible because we have many recursion calls inside each function to fix it we need to use local cache like this it's a function from the package fun tools and it will save the result for each start argument and next time when we meet this same argument we don't need to call many russion functions and just return the previously calculated value so in our case it will reduce the total time yes now it works and pretty efficient by time and memory and you can check out the solution in the description below thanks for watching see you tomorrow bye
|
Partition Array for Maximum Sum
|
grid-illumination
|
Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._
**Example 1:**
**Input:** arr = \[1,15,7,9,2,5,10\], k = 3
**Output:** 84
**Explanation:** arr becomes \[15,15,15,9,10,10,10\]
**Example 2:**
**Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4
**Output:** 83
**Example 3:**
**Input:** arr = \[1\], k = 1
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 109`
* `1 <= k <= arr.length`
| null |
Array,Hash Table
|
Hard
|
51
|
417 |
hey everybody this is larry this is day 25 of the ditco march daily challenge the like button hit the subscriber and join me in discord let me know what you think about today's farm uh so i don't actually wear glasses uh but i'm trying this new thing with about blue light yellow light something like that so i don't know looks a little funky on the thing though but we'll see how that goes uh anyway i usually sell these lives sometimes i have a little minor daily update uh but yeah so today's problem is specific atlantic wonderful given an m by n matrix represent the height of each cell touch the left edge and the atlantic right cell okay water can fall in four directions find the grid coordinates where water can flow to both pacific and atlantic okay uh let's see of height eco or lower okay hmm yeah so i mean i think that two ways um maybe there's two ways to do it but the way that makes sense most to me is just start you know just do a breakfast search or that first search it doesn't really matter because it's a connectivity problem where uh you know you start from the pacific side you try to see what sales you can reach by going up or decode like basically the reverse of the problem so one thing that i always urge is that and this took me a long time to get used to when i was doing it is that when the problem asks you for one thing well especially if it's a easier problem well just try to see if you can simulate it right um and if you can then you know you're done and well you have to do the math and calculate whether the math works out that it's fast enough et cetera um if that doesn't feel like it could work um or at least that it may be too slow you could another common thing that would do is just see if you can think about it backwards uh where you know because here there's an invariant of you know um things can only flow from the top to the bottom right uh or nico in this case um but in that case you know you could think about this as almost kind of like a dag um i know that in the equal case it's not quite right but you think about it as a dag where you know there's an there's um or maybe just a regular graph then you have an edge between nodes uh that's going from a higher place to a lower price or you go to so that you have you know these cycles but yeah and then now from if you want to go backwards now you have a lower um uh a lower thing and then go upwards right um basically just reversing all the edges on all the graph um so that's basically the idea um why am i doing this i think you can also do it um you could i think you can also do it the other way where you can just for each cell do a depth first search to see if you're rich pacific and what and then do a second one maybe to do it see atlantic um with caching and memorization and when you cache then that means that yourself can only be visited um at most once there's some i think the reason why i don't like that one um is that you know what uh the reason why i don't like that one when i first thought about it like 20 seconds ago or whatever is that you get into the confusing states where you know you have two for example do you want you go to this two do you go back to this two i guess not um but then you know but then there are just more states that you have to keep track of and then you're they're just um and they're definitely things you can keep track of to i think make this easier but i think like there's just uncertainty right because in this case like yeah okay this makes sense that this goes to this two but if this two goes to you know this two goes to this two like if you do a recursive the other way where you go from this two to here then you know like it's not super clear that you know these are transfer and you go here right but if you reverse the graph then this is straightforward because you can uh then variant is slightly tighter and that if you start from the pacific then you could just do a breakfast search your way up and then you know that just you know you basically expand in instead of trying to figure out a way to do it backwards um and in terms of complexity you know breakfast search is going to be linear in terms of the size of the input um and because it's linear i know that's going to be fast enough and it you know that's basically uh enough for me to code and of course i know that i talked for a couple of minutes um because you know because i want to explain the explanation a little bit but in general um if i was doing a contest i probably would have started coding about three minutes ago or something like that um yeah uh okay cool so that's um let's get started um yeah uh and then for implementation i think just thinking about what to do right can flow right okay yeah um just thinking about what to do of implementing it in an easier way um i guess there's two way to do it one so one is just creating an extra padding for the you know for up here to the left to the right to the bottom and then just like you know choose those starting points um i think you can actually also just you can also just start by uh these border points um because by default they're going to be connected to pacific so i think we just can start from these um that's okay and then you do a second breakfast search on the atlantic and that should be good and then you just do an overlap of those uh two reachable states so let's uh let's do it so let's just say uh pacific is it good okay let's actually set something up small rows is equal to the length of matrix columns is equal to the length of matrix of zero um and then pacific is just that's just you know uh atlantic same thing you know we'll use them separately later um or maybe i could just um yeah okay and maybe this is fine i was gonna think about maybe i can uh do some do not repeat yourself and abstract this a little bit i might still um but okay let's actually do that let's say by first search let's just say starting points and then and here we can see reach as you go to this thing um and then q is you go to the collections.deck of q is you go to the collections.deck of q is you go to the collections.deck of starting and because this is a breakfast search um we are okay with respect to the ordering doesn't matter i guess is what i mean um because i think that's just what i'm double checking um and then now we write the breakfast search sometimes i write this in a different order like i write the set up before the breakfast search but it doesn't really matter because i think i just want to add most of the code in my head um and also probably during a contest i would probably just do it to naively and not try to clean up the code as i'm coding because i'm just trying to get it correct made some is it might involve some copy and paste and honestly uh it has cost me some wrong answers in the past but it is more um it's faster for me and um yeah i don't know maybe i have to fix that though anyway uh so yeah while q is see whoa uh let's see uh yeah x y is equal to q dot oops i've been writing that for some reason um so yeah so then here we also set up the directions which in this case i believe it's just up down left right yep all right in directions um and then okay and then yeah and then now because we always start from the point so we can do something like you know we just make sure that this is inside the bound before we check um and then the only thing that we have to check is that it is equal or greater than so you check um this is less than or you go to the next one that we visit because we want to go upwards and also not reach nx and why because if we could already reach it then we already going to um it's already in the queue is what i'm saying so then here we appen um nx and y and that's pretty much it oh i guess we have to set this is to go to true um also yeah okay and also we want to actually set um for x y in starting which of x y is equal to true okay and then now we just want to return order cells which has these um so yeah and maybe i'll just return reach that's fine um i was going to maybe return to tuple but i feel like that's not as clean probably not um but yeah and then now we can do something like okay pacific is the top one right top and left so if you go to bfs of um how do i write this in a queen way um let's just say a list of uh zero x or zero y for y in range sub uh columns and let's add this from you know x of 0 for x in range of rows and i am aware that um maybe we could add a set to this or something uh i mean i know that 0 zero would repeat twice but it doesn't matter because this become uh this becomes a no op because this is already done for all the adjacent uh a cell so okay i'm just gonna leave it here for now but i know that this is slightly uh not perfect but uh but bear with me i guess uh but yeah so same thing here now uh so rose minus one y for y in range of cows plus oops plus uh x cos minus one for x in range of rows right and then now we can just find the overlap the order of the return corners don't matter i mean we're gonna do it that way anyway so yeah results is equal to an empty array and then now we do for x in range of rows four y in range of columns and then results up and x of y if specific of x and y and atlantic of x and y um yeah well yeah this is just basically a reachability problem uh definitely if you have trouble with this practice graph problems uh and especially connectivity once and i think that'll probably be the way to go uh diver oh whoops that how did i miss the entire wearable name okay so is this right i seems to match up they don't give us another test case so let's give it a submit because i'm lazy uh oh no i was thinking about like oh don't give me an empty case thing uh which is a little bit of a gotcha but it's fine they have actually been litko has actually been better about that lately about not doing this but they don't even define it that's why i mean i guess technically they define it but um but it's still such a unnecessary case right because it only fails on here so yeah i mean it's fine but sad because this is not even a valid input maybe i don't know um either way i mean that's not we're here to sell prompts we're not here to add if statements i'm not gonna feel that sad about it um but yeah uh because yeah definitely in certain uh contests and com competition they do expect you to do this but from lead code i feel like they've actually been moving away from that lately uh which i'm happy about because i don't think that you know like there are ways to get edge cases that aren't just like oh you didn't read the problem carefully enough right like that's or like it doesn't teach anything or show anything i think but um and also this is what having unit testing is for uh but yeah okay so what now uh complexity okay so i mean this is just standard breakfast search as i said so this is breakfast search on the array starting from you know the left hand you know from one of the side or two for two of the sides and then we do it twice so and each breakfast search is going to be linear time and you know linear for breakfast which is three times d which uh where we is equal to the number of cells which is r times c and e is equal to the number of vertexes times four roughly so this is going to be o of you know r times c plus more r times c times four something like that which is equal to o of r times c um so this is linear in the size of the input uh where the input is not just this is it's the matrix of course um and we do it twice so it's going to be still linear and then we do one more linear scan to get the answer and i guess the setup is also um oh i guess that's it i mean i guess this is also ah there's a sublinear but that's fine um but yeah everything is linear as a linear time and we have linear space with respect to you know these two uh matrixes uh you could probably reuse them if you really want to but it's fine i mean that doesn't matter um yeah linear time linear space and when i say linear time linear space is actually r times c um for linear for time and space it's linear in the size of the input because the input size is all times c um that's all i have for this problem i think this is you know this is um i would say if you're having trouble with the uh graph theory or bfs or stuff like that connectively like i said practice that um i think the tricky part about this one problem is it does have that hey you know use this one trick to solve this problem and that is um thinking about things backwards and instead of you know um answering the question as they tell you which is um you know water flowing from top to bottom which maybe is intuitive um try to reverse the problem and try to see if you know you can figure out another invariant there um that's all i have for this problem uh let me know what you think uh hit the like button it's a subscriber and join me in discord hope you all have a great day have a great week have a great rest of the week uh take care of yourself take care of others uh to good health and to good mental health i'll see you tomorrow bye
|
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 |
219 |
lead code number 219 content duplicates 2 So within the window of the size of three which means the distance within the first integer first number and last number if this inside the tree then we will return true then if this has a duplicate I took the code from his video in here no it's not I took the code from the solution and the best solution the most upward is slightly to advance for me so I'll take this one it's quite okay so legendary engineer and let's see how does it work so right now we have an array of one two three one and K is 3 and it should return true let's debug it so we will create an object has map right now and it's called map that there we have the object has map right now and we will loop from I from 0 i 0 until the numbers of length that is four zero one two three is less than four and I plus okay so right now what is the num of I is one do we have that in the hash map well we just create the Hazmat we don't have anything so definitely this statement is false let me make it bigger this statement the condition whatever it's false and it's false we go to the else statement and that we put the first one is the number in here and the second is the index so when we click it we will have the hash map of the one and the index is zero and I do I want to drive it in here yeah so this one and map to zero call and it's kind of the same do so the next number is I is one and that number is 2 in here do we have two in the map no we don't so we just go put that number two in the hash map and we also will put number three in the hash map so we got number one two three two map to index one three map to index two then we will go to the I equal four three zero one two three and that value is one do we have one in the highest map yes we do when we have one we will calculate if I minus get the numbers of I num of three is zero so we will take the corresponding hazmap index in here so M if it is less than or equal the distance of the window which means that we are here and if the distance of that index Which is less than three this is at most three then we will return true if not it will be false so in here we have the distance of like one two and three so we will return true for this one therefore it will return true yep let's check it if we put another number in here what happened so we got 7 over there so if we continue and map size four okay so right now number one map to zero number two map two one number three map to true and number seven map to three in here and we will check whether do we have a map that contains of one yes we do that is at the index zero so we'll take out that index in here that's why the value in here is zero and then we will calculate if I which is four less than map of the number one that is zero if four minus zero is less than three this is false because it means that we have seven in there seven in here and the distance from one to another one is one two three and four so we will return false that is fast and quick it's good for warm up foreign
|
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
|
1,816 |
hey everyone welcome back to another coding challenge lead code problem 1816 it's called trunet sentence so we have been given here a sentence which is in the form of strings which is called hello how are you contestant and we have been given a K4 which is index so here k equals 4 means how many words they want us to have in our output from the beginning of this string for example here the output is hello how are you so basically the output should only have like K amount of words so here is four so we should only have four words here from the beginning of the sentence so hello is one 2 3 and four so we don't want anything after four that's all that's what we need to print here you can see input s is what is the solution to this problem so this is a sentence and we want only the big beginning for what so beginning for is what is the solution so we don't want anything after this anything so here you can see Chopper is not a Tanuki so we want five here five words from the beginning of the sentence so 1 2 3 4 5 so we give five words okay as there is nothing after this so we print the same thing okay so now let's try and solve this problem so to do this what I'll say that first I will declare a variable called let array of string and I will say so what I want to do this is string right and what I want to do is I want to remove everything after those four words or five words so for that I cannot remove it from a string right so what I'll do I'll convert all the strings all the words into a array of strings so for that I'll say s do split after every space I want to split it and what it will do right now my arrrow of string basically this is like this what is this is basically this for example this one like this it will become like this comma so on all of this so it has become an array of strings after this now what I want to do is now I want to remove all the words after my this Index right which is uh after my four uh words so here what I'll do is I'll splice it so I'll say array of string do splice I want to splice from where so I want to splice after my this four words or whatever words this K is so K Comm comma I want to splice till my length everything after that so that will be S do length okay sorry this will be ar of string do length and after that what I'll do is I'll join again so I'll say AR of string dot join and join it again in the same way how I converted it into array so array do join will again make it into a string and we will remove those last bits after our K words we will again join it make it into a string and if I run it then this should be working fine oh wait I need to return it so I need to return this so oh wait uh let's submit it submit will work so yeah our solution got accepted it beats 50% of the solution accepted it beats 50% of the solution accepted it beats 50% of the solution and memory as well it's really good so I'll see you guys in the next video and if you want me to solve a specific problem feel free to ask me and check out my other videos as well thank you so much
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
204 |
K Ribbon My name is Ayush Mishra and you are watching this mission Dress Today we are going to talk about the problem of this name on the list 34 problems of ours and it is a very important problem that the question is what to do with you Calling brother. What is the number of prime factors listed in the negative number and not get number 1? What does it mean? It is simple. Will any number be given? The grade will be zero. Will it be ok for you regarding that? Who is your train? How many numbers of science are there? Ask questions less than that number but no. If you are not saying then how many time numbers are there given this incident, it is taken up to 305 then the seventh is there are only 4 prime numbers less than 10, okay if here their value is given as 11:00 then here their value is given as 11:00 then here their value is given as 11:00 then 11 How many are less than :00? 2357 is divided by 9693. 11 How many are less than :00? 2357 is divided by 9693. 11 How many are less than :00? 2357 is divided by 9693. Okay, just 2357. 11th number is needed because 11:00 is prime in itself needed because 11:00 is prime in itself needed because 11:00 is prime in itself but we have to consider it because give us a list. We need the number. Okay, show you their country cot number. Given now the sister's values are toe, this is their value one sister's values are toe, this is their value one sister's values are toe, this is their value one 2012 Subscribe to the accused channel Before this is our ghagra can even be elemented and subscribe us how many numbers are there in jitne meghnad padhe this function should be simple that Number from how to till the end should not be divided by any number. Okay, he said inch welfare that what is the use of us knowing whether it is a number or not, it means there should not be any such number from two to four and then divide. If someone divides it into 1, then this number is not the camera, okay, one comes to, do not consider that in the morning, brother, one divides everything, that is why it is said here, then when you run this time function, it is okay. So you will be sent to check, you know, we said that check is the time or not, will you decide from you till the last that people will run, the gift for the hour is prime, how will you complete it, from then till 39th, people will run, okay? For each number, you will run end time form. Okay, time is your function. How much time will it take to generate foam? It is okay and overall, only in cases where you check the number, whether it is a wild animal or not, come on, it's my time. Is it okay on the result, is it prime time or four or not? It is taking us N time for each number, so there will be add numbers, now how much more time will it take, if the entrance time will be taken, then we will do disco as seen on 41st, like Bigg. Boss knows that this is the number, we told him that it is, now we will check what it is, whether it is prime or not, otherwise what were you doing till now, he will ask that we will see by dividing only and only 5, 6, 7 by all these numbers and if we divide then we will get If any number divides this number completely overall, then we will mentally think that this is not our front. Well, tell me, is there really a need to divide it by seven, do we know that we will not be able to divide 712? 800 from the possession of good. Will you be able to divide, what happened, you will not be able to do this, there is a chance in two, three or four, maybe you can divide, okay, but 572 never does, it means that if any number is mixed, okay, then who will divide it? Can we believe who is the maximum number at? If we are not considering anything then it's okay. One team has to check which is the biggest number and divide it by rotation. If not, where is it ? Will you invite me the apk file, you understand that ? Will you invite me the apk file, you understand that ? Will you invite me the apk file, you understand that this is going on, I said, do you want to chat on that side, is any number able to divide that particular number, otherwise you can run the full and minus one problem, on it, run it till Bittu. What will happen is that if we want to do an interesting thing about the office, then we will check two, three and four, is it able to divide three values, if we do it, then we will say yes, this is not the time, okay if we are not able to do it. Number, we say, brother, my number is prime, it is okay, there is no need to check five six seven here, it was just locking the unnecessary generation, so we can use it a little less, okay come, look at it a little more carefully. So if we know their network is prime what can they write two into six into this into 14.23 for 7252 write the previous video 14.23 for 7252 write the previous video 14.23 for 7252 write the previous video no 324 write your entire video no this now we need a WhatsApp app that brother if we see now Till we say, if we want to see, then only to check, we were running her two times, from work to till Bittu, we were checking her with such value that whether she is able to tweet, next does not depend, use this. If you subscribe * 3032 If you subscribe * 3032 If you subscribe * 3032 means we are contacting, if you think that I am giving you like a challan, then you must have understood it, but are you really giving the answer? Check again for four. What is the need to do, isn't it, this is how students are coming to us, because if you do 1622 and see, is it just coming or will you never see it, then this alteration is not useless, it means that what you do is take the square root of that number. If you take it out, how much will the Tehelka square route come? Around three point committee owners are asked. Okay, so I am telling you that the job square route has come, give it India number, go to its validity committee, 31 means come four times and see. Okay, atleast four. If you run the bar then first know how much was going on, it was 230 506. Okay, NYTimes, so after checking all these tuitions, we were seeing that our number which is crossing the divider in subscribing, we had to reduce it to how much it was for you and from. If we check two three four, we have further optimized our code, so now we can see here that this point is not necessary for the day, so we made it necessary for us to follow it till the root end. To do that, it is on the second number or No, their luck changed due to time complexity and square, their power 1.5 time, they have their power 1.5 time, they have their power 1.5 time, they have improved it a bit, now we can see how to make the limit, so first of all, here we have this pancake, from the admission figure or two to the square root of that number. Have and stay 0.5 inches to remove while doing which is stay 0.5 inches to remove while doing which is stay 0.5 inches to remove while doing which is its little what is this means their power point to and this means end power 0.5 Okay so this is what this means end power 0.5 Okay so this is what this means end power 0.5 Okay so this is what I said what entry 2015 square root will take out some of the play store of this After that we will change it to Indian and add one to the answer. From two till that number we will run a loop which will generate if we divide any value then immediately we will say that we do not have time as a result of the answer. If this is not happening then you will say that this number of ours is a point, is there time to measure it from the point or not, it will take time, its power is 1.5, ignore of ink is 1.5, it will get cycle power is 1.5, ignore of ink is 1.5, it will get cycle power is 1.5, ignore of ink is 1.5, it will get cycle time, ok, wow, what do we have to do? It is possible that from 2 to that number we might have been given some number, not that people are less than 100 than us, how many times are there from 100 to 19, if we subscribe, we will get it in 40 A Bigg Boss Ka. We will return it to you and the time limit will be exceeded because you have to keep only one end value, you will run in this form on Saturday and for each value, you will keep this 1.5 inch and how much time from 1.5 inch you will keep this 1.5 inch and how much time from 1.5 inch you will keep this 1.5 inch and how much time from 1.5 inch and so on. Yes, you are okay to check that it is taking so much time and it is taking 1.5. Okay, it should and it is taking 1.5. Okay, it should and it is taking 1.5. Okay, it should not happen like this in setting up the entire project. See, I am telling you that which is happening from time to time. For look, this is yours from one to the other, from buying to it, he will check their value by picking up the Aadhaar number and send it to him. In the function named Prime, how much time is it taking for Pranam to crush the fast? Anti power is running up to 0.5 inch Jyotiswarup. Is there a Anti power is running up to 0.5 inch Jyotiswarup. Is there a Anti power is running up to 0.5 inch Jyotiswarup. Is there a loop and how much time is it going on? Is it going on and is it the end time? And how much is the complexity? BDO of their power 1.5 While you have to try to do it Vivo of any way, of their power 1.5 While you have to try to do it Vivo of any way, of their power 1.5 While you have to try to do it Vivo of any way, You have exceeded your time limit in Inquiry Adventure 1.5. If it is there then you will use it exceeded your time limit in Inquiry Adventure 1.5. If it is there then you will use it exceeded your time limit in Inquiry Adventure 1.5. If it is there then you will use it there, you will use only brightness, this is a very simple thing, to get justice quickly, then you have to message the report owner that less than 10, how many hardworking characters are there, less than this, how many studies are there, how will you know, from 45 for two to three? 60 quality will not be done because if less than 10 are required then the prime members will be there in writing. Well, tell me one thing that if we have seen two first then two is selected and two has been set then it is certain that its Whatever multiple there may be, it will never be love because it divides the athlete and will not give for quota because when you are not able to divide 423 46 248 then I am fine, I left him. Trikoot is good, speed is here, so who is three, can he dry anyone? What was there, because of no suspicion of police, it is not like that, man, we can turn them, we will give them Noida, next time we will cook it, we can do 5 flower hand affidavit. That is, you cannot consume further, no, Tamil Nadu 357 574 has not come, this is our add on the limit, brother, you will only make numbers, you will pick the first number two and we know that all your multiples will be prime. No, because it will divide it too much, so we have done this, we will mark off all those numbers or remove them, okay then how will we do the next number three, Simreli, all the children will be on the field, it would not be like love has happened. It's well, it's three, okay, we will turn off this festival because we can't, okay, we will keep picking up our salt like this and whoever has it, his roots will be strong, we will remove all of us, so what is the anger of this much child at the end of us? What will be left is that our PM number will be less than 2357, this number will be our prime, the time when women will implement Champcash, first of all, I tell us that if we had seen the welfare officer example, after this, we would have left it and accepted this leaf, then you Do this, write here, first of all, boss, how many numbers can be there which are less than 5, which will be prime, 1 2 3 4, 42 numbers are possible, only these can be fried, if they are verified, then if we make it so interactive, here on Thursday But Luta Do Subscribe Now we have to subscribe the appointment, if this happens then tell me one number, which one is number one, will he ever be able to become prime, if not, then what do you do first, call him, simple, then its Well, this means that we were cutting it, here we have kept the full value, one, well, we had checked the two, all the multiples coming after the two are there, in this whole thing, we have reached that, I said that I Till the time my two come from the pan, what will we do that brother will check, okay, so this was friends, select the time, the juice and water value in it, is it through, how is it stuck, I2, that if it is true, it means that which is before this. If those numbers were ever able to be divided by two, then they would not be able to do so by two. Okay, so here it is 2000. As many people subscribe to Chhath. Don't forget to subscribe to the channel because if we click on this channel, then these people will not subscribe to the channel. I paused the subscription, it's simple, okay, in the case of our file, it is only so big, so we can only go this much and have fun, it is over because when you cover six, our six were established in this, it is over, it means the screen. Subscribe, whatever we have to do, it will not be of any value, do it and subscribe, it has become stable, okay, in this you are able to see this from Paul, this is good, so this means that it is fine, so the problem is that this is By the way, I went a little bit here, understanding the things, once more quickly, we will get some wounds to eat, we have a matrix called this which has made us agri, okay, after this we are going to multiply it with the pan. Because of these, people are going to like me so that they get broken by the number time and our value. Simple, okay, when the SIM gets activated in this time, then come friends, welcome, 20000 subscribers are not there, what will we do, we already know on 2 tables. It is found that the President of Young Seervi subscribes as many times as he wants, then again who will become the patrol child in Ghar Jaipur that there is a submit button of some number and at the end he will return the suit account. If he does all this, then in this C The concept of curved tennis is bad. You have understood from America, here how it is incremented is bad. Well but here is one thing which you are a whisker, that is this condition and time is going on, it can be said in more less. What to reduce you further let me tell you a whatsapp here see maybe brother we know that if we check pipe clear checking for man will fight will remove the train ok then cream Remove the pallu from the front and see it with the right shoulder. When I reach Delhi, I do all this, I admit the one who has medials, he calls 100 with his mind, the inner Paulus, then tell me that five * will give shift, Paulus, then tell me that five * will give shift, Paulus, then tell me that five * will give shift, okay tell me five * meaning. Will you be able to do 1010 by four-five? okay tell me five * meaning. Will you be able to do 1010 by four-five? Yes brother, there is also a medical at 10:30, otherwise Yes brother, there is also a medical at 10:30, otherwise Yes brother, there is also a medical at 10:30, otherwise this tow has to be set, then my test must have gone there, CCR must have been done before 2004, okay, just like that, three comes before five. Which friend has to set then six 90 first will be only that then in 5,000 know that there is a value less than five, in 5,000 know that there is a value less than five, in 5,000 know that there is a value less than five, she is removing its multiples so why should we double check for the pipe, first all the multiple sclerosis is lying in it. If you do all this in advance, then check that number, if it is 25, then going ahead with 25, make it 225, it will remove the pain, if you subscribe, then it means that these two 157 252 56001 are subscribed by 502 people, right? So it kept fast for this phase 5 * 5 phase 5 * 5 phase 5 * 5 I am understanding something, 5.5 means I am understanding something, 5.5 means I am understanding something, 5.5 means that instead of a, we have a side of the pipe, we will get a time dimple which will be able to fall in the pipe, so it means that brother, if a current If the number is Merapi, then we will always mark off the PVS on Umar which will start at the previous point, how will we do that, we will multiply that number by itself and find out what is going to happen like if I add this and a little Let me edit a bit and tell you, if we are talking about the pipe, then I could not touch the 10 1520 that you will be able to do here because who has already done their rally scars? In how many possible multiple samples will the mixing side have to be started from 5.25 started from 5.25 started from 5.25 5.21 Ja 520 10530 Cutting will already have balls at this number 5.21 Ja 520 10530 Cutting will already have balls at this number 5.21 Ja 520 10530 Cutting will already have balls at this number Which number will not be a force 512 5 Yes then that's what I should say that we are here above this is why it came What was there on this lead end here to be able to do so, hence if there is a stand, then the condition has started, my mother is law and vital, so she became the commissioner, then the title of the file or 5.5, became the commissioner, then the title of the file or 5.5, became the commissioner, then the title of the file or 5.5, which is here, will pause as soon as you get further appointment. If you go to make a call at 10:00, then at 10:00 you have already call at 10:00, then at 10:00 you have already call at 10:00, then at 10:00 you have already failed, otherwise why should I do that, because by subscribing to them 210 more, we will subscribe for 525 for the to-do list of the Sangh, which we will 525 for the to-do list of the Sangh, which we will 525 for the to-do list of the Sangh, which we will Can remove, they are children, understand that 1015 and 20, values less than 25 will be understand that 1015 and 20, values less than 25 will be understand that 1015 and 20, values less than 25 will be removed in advance, there are multiples of soaking it, so this is what I have told you, that I have made a table against the same, near the dowry that came out of the road, I will you to Now till the time I * I this list ends, first till the time I * I this list ends, first till the time I * I this list ends, first Iceland, now we have taken * will add oil, Iceland, now we have taken * will add oil, Iceland, now we have taken * will add oil, set reminder on that, what is that, hey Guru, then in the case, now I am going to get the purchase from the shop tomorrow, then 30 then 35 We are going to get this on time, for these we need to understand deeply first, what were we doing in the tenth chapter, the Supreme Court used to do it here, we used to start from two to the end, fax the pimples from two to the end, understood the button, note, this is the first one. If you pass 2500 crores then proceed from twenty five till the end and keep increasing fives and now whatever multiples are there near 25 then pause all those chords so that those whose multiples are less than 25 are safe. Two and three means whatever limit is less than five, all of them must have crossed it already. Simple, if I understand it lightly then it will be better than mine and if I could not tell you the commission, then if you do n't understand then the shape that I love you so much with my hands. Not going to do * If love you so much with my hands. Not going to do * If love you so much with my hands. Not going to do * If you put it back then you can also run the Iceland one and you like the above one, it is okay but in this your optimizer gets activated a little bit, so as I understand it, you will be better in this computer if you understand. If it has not come then you can run Iceland volume, it will have the same number of people who will be able to reach till 25 and if you are installing fiber WhatsApp in it then it will work from 25 till here. If we are talking about the next flight then it is ok. So in this way, my whole world is going to run here, at the same time the extra end which we have taken up the space, it is not toothed and we had made a table, there are some other running time properties also to make the plate to check it runs on time. Is it into law login that this is its total time complexity, so I have this is a million times better than the end square, I changed it from the side at the entry point, okay, now you are able to see that this is mixed into this and changed by breaking it. Done * Lots of Love and changed by breaking it. Done * Lots of Love and changed by breaking it. Done * Lots of Love and First Best Time Complexity can happen if you want to find the prime number for a given number and how many total numbers of time can be less than that. Internet You should avoid smoking cigarettes here. It must have occurred that you did not understand, then I will comment you in this video on the I button, so you can see that also, here I have actually made a table and explained this line from the other side, so you can see it a little on the side video. C will help and Jhal will help Ajay.
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
2,000 |
yeah so uh yeah so sometimes i don't want to do mathematics so i do something code yeah so just for fun it's very easy question hey so we can do easy i do easy questions so i don't spend a lot of time describing the algorithm okay so reverse uh reverse the prefix of a word so given uh zero index string we're in the creator ch so you have a character and then reverse the segment word that start as your index and end the next of the first occurrence inclusive and the reward if the current ch does not exist the word then do nothing so for example a b c d e f d and you go left right and you say oh the first guy is d so all you need to know is that the re all you need to do is reverse the first letter and the rest fix the same right so you return a dcba eft okay so in this case the first algorithm z right so you reverse the first four and fix the rest also this guy is the same oh this guy you don't have z right so you return the same okay so solve this uh this is easy right so first that's so my idea is very intuitive right so very stupid you first uh find the index which is the first occurrence right so once you've so for example you know that zero one two three the third index uh which is the same as z right so uh the same as d so you just reverse the first bar and the rest fix the same so j to be numb so let's change the how many at least j is the index that uh we want to find the first occurrence okay so and i go through the word i go to released and uh if the world equals the ch the first occurrence then i that index is equal to j and the break okay so now i find in this case i find j equal to three if j is num no means that id now means that the ch is character do not in word right so we just return word okay else uh will return we else we need to reverse the first part right so reverse the this is the first part and this is reverse i reverse the first part and add the rest at the rest okay so very simple uh yeah check it by yourself see you guys next video
|
Reverse Prefix of Word
|
minimum-speed-to-arrive-on-time
|
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing.
* For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`.
Return _the resulting string_.
**Example 1:**
**Input:** word = "abcdefd ", ch = "d "
**Output:** "dcbaefd "
**Explanation:** The first occurrence of "d " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ".
**Example 2:**
**Input:** word = "xyxzxe ", ch = "z "
**Output:** "zxyxxe "
**Explanation:** The first and only occurrence of "z " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ".
**Example 3:**
**Input:** word = "abcd ", ch = "z "
**Output:** "abcd "
**Explanation:** "z " does not exist in word.
You should not do any reverse operation, the resulting string is "abcd ".
**Constraints:**
* `1 <= word.length <= 250`
* `word` consists of lowercase English letters.
* `ch` is a lowercase English letter.
|
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
|
Array,Binary Search
|
Medium
|
1335,2013,2294
|
1,247 |
hi friends uh welcome to followup let's have a look at problem 1247 minimum slaps to make strings equal uh this is also a daily challenge problem so in this video we're going to analyze uh the strategy and demonstrate to you uh that starting from example one and example two actually we can derive the um Counting or the result for General case so without further Ado let's first digest the problem requirements and then we look at the analysis and finally we share the coding so now for the analysis or digest so we are given two strings S1 and S2 of equence consisting of letters X and Y only so our task is to make these two strs equal to each other or we can slap any two characters that belong to different strings which means we slap right pick one letter in the first one slap with another in the second one so we want to find the minimum number of slap required to make S1 and S2 equal otherwise we return netive one if it's impossible to do so right so if you look at example one so you know if this is this such a pattern right you have X or some uh adjacent or not and then you have v y right so in this case you just need one operations as in the explanation here right so if you have the uh scenario in example one so here you have One X you have one y so um maybe adjacent or maybe not but their corresponding indices are the same so in this case uh we need two operations so we need when operations to reduce to the case for example one and then need another slap to make it them equal right so we need two and uh we actually can see that um the generic case if it's possible to make them equal um is to be covered by example one and example two right so the example three uh is actually we return negative one this we regard as Ed cases so here we have 3x we have one y right it's impossible to evenly distribute them because uh three or one you just need to check one it's OD number right so here are the constraints are the following so their lens are the same and they both contain only X and Y so these two are consist uh consistency assumptions the first one is about the problem size so um the length because their length are the same so the length is bounded above by 1, it's very small um very small uh problem so with that said let's look at the uh strategy so what we are going to do is to count indices where the corresponding characters does not match uh do not match let's see and then we use pairing given by example one and the example two right so uh note that if any of the total conss of X or y's uh in the two strings is not even then we just return negative one right otherwise we try to find count pairs like this because this requires less operations and if for example you have 3x right you have 3x and you have uh see uh another one let's see oh we have u y and uh you have uh what so this is impossible but if you have this kind of thing like this x y and this the uh this x you try to count the number of X and then you match and wies right here just one operation for these two you just Ma just uh use two uh slabs right so that's uh that's going to be our strategy so for coding part and you have you can you have lot of freedom so you can write a very short code or you can write slight long code but here we are going to take a strat that we just translate the above analysis into coding format I guess later you can see you can do um uh see some simplifications or optimizations so here I'm going to connate this two I want to First exclude all the cases for example three so FS cont it's a number X um or two uh is not uh so it's not zero or you can say it's equals to one or S cont you know so this why um module 2 is not zero right then you just return negative one because you cannot evenly distribute them because the result will have uh equal uh S1 and equal S2 so the number of X and Y should be even so this the one case so next we're going to count the indices where the characters uh do not match so this actually super easy but here let me introduce uh some comprehension I'm also going to use a dip function so for I ab are the characters in enumerate so we use enumerate because we are interested in the indices and then also we want to compare the corresponding characters so we're going to step S1 and S2 right so here if a does not equal to B so we are going to collect those indices and then we want to see for those indices how many X we have how many y we have so this just uh another con right or you can just uh use um say um uh a for Loop anyway so let me n x n yal zero so you can call some buil in function or it's just a simple for Lo for I in uh indices let's see if S1 I uh is X it means S2 I must be y right so the count of X is increment by one otherwise the count of Y is inced by one so now we have those X and y's and then we want to count the pairs of X and the pairs of Y right and then we just uh um choose assign them so corresponding number of operations either one or two so now let's do C1 R1 let's use a Dev mode so NX um let's say NX I divide by two right and to similarly C2 R2 or C you can change this one to be X and the two to be y it's more suggestive so here I'm use NY and two right so you have C1 pairs of X all right so we just need this number of operations and we have C2 pairs of um what in S1 we need this pair of operations and then we're going to do C1 plus C2 if um R1 uh equal zero actually if this equal zero C2 must also R2 must be also zero because we have exclude this situation all right otherwise uh we are going to return C1 plus C2 this is pairing this kind of formations and then you have a one either you on X then you will have X and Y right here you have um so you have One X left you must have one y left in other words you will have an X Y in the first string and then you will have YX in the second string but this need two operations right we're going to add just two right in other words we need at most once for this kind of operations most we want to use this one so now let's do a test uh list object cannot be uh let's see for I in range also I see so for I in IND thises I read too much range so yeah it passes one example now if you look at example two so let's see um if it can pass this one all right so as we mentioned we will pass generic case see and let also test S1 is xx and this is the XY right so Ed Case the return is right it means that this logic plays a rle right and then the first two examples indicating the logic is here are right so now let's look at generic case yeah it passes all the cases you know so um here I would see uh this actually is not necessary even here but you just need to use for Loop to count the indices corresponding to uh differences and then count those and compute this but you know I read in this such a format in other words with redund but the purpose is only for pedagogical purpose it's just for the ease of understanding you have lot of freedom to modify the Cod but the main point is to digest the thought process so with that St I guess um that's basically about it thank you
|
Minimum Swaps to Make Strings Equal
|
decrease-elements-to-make-array-zigzag
|
You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`.
|
Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors.
|
Array,Greedy
|
Medium
| null |
130 |
hey everybody this is larry this is day the last day of oh i know is it hey i'm now no longer snorlax it's really hot i guess it's the first day of the november lego day challenge but it's still halloween where i am so i am i'm snorlax so snorlax no dexter alexa you're just joining us um yeah we will do this all week or a month or whatever look at my pause hit the like button hit the subscribe button join me on discord come hang out chat prom share solutions read other peer solutions and so forth um we're gonna be doing this for as long as i can or as long as it makes sense uh we'll see anyway today's problem is surrounded uh surrounded regions so given m by n capture origins that are four directionally surrounded by x okay so for these problems one thing that i would say is um one thing i would say is um the first thing i would do is think about um okay they tell you to find something right see if you can find the opposite of that easier and then negate it right um in this case that's what that was one of my well my i have two really quick instances and these kind of comes when you do a lot of practice you go oh can i do this well then the follow-ups can do this well then the follow-ups can do this well then the follow-ups can do this other thing right and which one and then you figure out which one is easier to code so it's actually not that hard per se you have to be really careful to kind of uh do this but i think for me my second immediate thought like the first story just do what they tell you to do and then the second was okay can i do the opposite of that right and what's the opposite of that is finding the regions that are not captured right and then my thought right after that is okay what does that mean that means that if a circle or us or whatever is on the border then it's good and then everything that's next to it is also not captured right so that's based on that premise i could build that and then keep the ones that are quite good and then remove all the other ones um i think for me that's a little bit easier with respect to maybe it's the same maybe we could do something like union fine-y thing but do something like union fine-y thing but do something like union fine-y thing but for me that seems like um a reasonable approach as well um and then it just becomes especially when you're in a contest or sometimes sensitive thing of okay which one um which one would be easier to implement with respect to fewer edge cases uh fewer silly mystic depending on who you are and just maybe even shorter to right or easier to implement right um those things are all factored in so okay so i am going to do the second thing maybe um yeah okay and so let's get started uh and this is just a regular front fill uh as a result because after we changed it we don't have to do anything weird um it's just a flood fill and that's pretty much it um yeah uh and the way that we're gonna implement it or i'm gonna implement it is recursively though you can also do it with breakfast search but i think we recently had a problem with breakfast searching we did that first search did we don't remember maybe that was a contest actually but uh yeah what the hell let's do it with um with my first search this time because i think i usually do that for search anyway so yeah so we start with a deck and then now we go we look up on the border to kind of start um on the circles right so yeah so for x um and okay let's actually also set up the rows and columns so i like i know people use m and uh m's and n's or the other way around but i just use r and c because it's oops oh and oh which is stupider but no nc is fine uh and yeah we want to make sure that it cannot be zero otherwise you have to add an if statement for this uh but yeah and then now we just do yeah rows and columns because it just for me it's just harder to get confused for me you should come up your own notations of course so if word of x y is equal to is it big o or zero that's a zero right oh no that's an o okay um then we um a pen x y and then now we did a couple ways you can do this um in terms of like you could have a boolean matrix of things that you've seen that are quite called good or not surrounded um we can do a couple of ways i don't know the way that i'm going to play around with maybe this time is by using the existing space and modifying in place so um yeah so let's play around with that so while and this is just standard my first search at this point um x y is you go to q dot pop left and yeah um okay directions i forgot to set it up so we set up the directions this is just a ford um i think i did do something like this recently right because i feel i think i ended this incorrectly one time i need to be more consistent about it i used to be really good at that but maybe not recently maybe just a little bit sloppy i don't know right so now this is just standard balance checking and stuff like that uh okay actually what we want to do is when we when we uh so we're gonna instead of having a boolean array i'm just gonna do something hacky just to show you an example of something that you can do but you know i'm just like g for good and now when we want to put something on the queue we also again uh do this and also board of x y is equal to good but of course this we only do this if it is uh if it is oh right and then that's mostly it and then now we do two pass through the system so now oh every after this breakfast everything should be uh good then we want to convert the existing o's two x's oh by the way and we want to convert existing g's to o i usually i was going to do this in two paths to be honest or two different loops but i think this should be okay because we do it in this order um yeah and then oh we don't have to return because it's in place so i think this should be good maybe roughly that's not useless okay i have the wrong answer though ah i'm just returning the output um that is interesting oh whoops really sloppy here but yeah should be okay now maybe okay still now i'm just returning to output or didn't get updated why is that hmm huh that's interesting okay let's print it out real quick just to see if we get the g's and if it's the bug is in here or before right and here we do see that the bug is in before because we do convert all of them to g's uh oh i messed up um this uh this code is just wrong right what i think i just got too used to doing something like this but um but i just say in english that we only want to k um we want to start off only the ones in the border right so and this obviously um isn't on the border so yeah so we actually want something like this um yeah and so we have something like this on a border um this is a little yucky but it's fine i suppose so this is the um yeah and this is c minus one i guess we could have done something like for y in zero c minus one um and then i could have done what i had before right and then we do the same thing again maybe there's a cleaner way of doing this but all right okay now we only uh and cue the stuff on the border you're not i think i set the english correct graphic i was just too used to writing my loops that i forgot or i don't know sometimes muscle memories get in the way so this looks good let's put in a few more test cases like this one i don't know i think these are maybe the vertical one just in case though i don't know this these things i tell i mean my inputs my test cases are terrible they're not really that example but uh oh whoops these test cases are terrible you should play more edge cases but more the edge cases are more to my dimensional so i am a little bit lazy about it today uh i'm obviously confident as well but yeah uh today got a 580 day streak yay um yeah i think that's all i have um what is the complexity well this is just breakfast search so it's gonna to have r times c uh times c space and time the space comes from the q and also technically we do even though we manipulate board so yeah and the time is that we look at each cell once ish right um so or o of one anyway so that's going to be all of our time c times and space um that's all i have for today uh welcome to the beginning of the month uh let me know what you think hope y'all doing well uh let's do the rest of the month together stay good stay healthy to good mental health happy halloween if you're still in halloween uh if not just enjoy it i'll see you later and have a great month bye
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
716 |
Hello friends hope you're having a fantastic day today so now we are going to do an awesome stack problem that is a actually a lead code premium problem so this is going to be really interesting very popular question and very interesting subject so without any delay let's get started okay so the lead code problem we are going to solve is called Max stack this is actually a lead code hard problem and the thing is because this is a lead code premium problem uh I took this description from another website called lead code. CA so thank you so much to whoever maintaining that website now we need to design a Max stack class that supports these five functionalities now if we see the functionality the first three are pretty common where we are pushing an element down the stack where we are popping an element out of the stack and where we are uh just checking what is the Top Value inside the given stack these three are the common functionality of any particular stack then we need to add two more methods where first one is a peak Max method uh and second one is the pop Max method so if we do the peak Max method we will need to know that what is the maximum element currently and if we do pop Max then we will have to pop the maximum element that is right now inside the stack outside so let's try to see the solution for this problem so logically uh let's assume that currently we have an empty stack okay so we have the option to use five operations and so let's try to First quickly push some elements inside down the stack so if we let's push value number three and then value number five and then value number one okay so now currently we pushed a few elements now if we want to pop and let's just add one more now if we want to pop we can pop one element out as well so if we do the pop operation then we will we won't have value number seven now we can also do a peak operation so if we do Peak operation then we can simply check that what is the very first element so answer of this is going to be one then if we do if we want to do Peak Max which means we should see that what is the current maximum element present inside the given array which means the current maximum element present inside the given array is actually value number five even though it is not at the top of the stack this is the current maximum element so this needs to be value number five and if we have to pop Max then we need to pop the value number five out of the stack not value number one even though one is the very first element so this is how we will have to design this algorithm and design data structure in order to keep these values now we know that completing these uh items is very simple and very similar no issues with this one this is a regular stack functionality and every single language like Java python C++ they like language like Java python C++ they like language like Java python C++ they have they all have their own stack versions that we can simply use the problem comes when we need to do this PE Max and pop Max problem uh operations because the thing is this is actually slightly complicated because of variety of reasons now the very first thing that comes to our mind is to have a variable called Max where we are going to store the maximum value that we have been able to identified inside the given array and this should make our lives easier this is the Primitive logic we can think of where let's assume that we add value number one so we need to update the value of Max to Value number one then once again we add value number six so we once again because 6 is greater than one so far the maximum element we have been able to identifi is six then we have value number three so three is not greater than the current maximum element which means we don't update anything or we don't do anything now after this uh let's say we add value number eight so once again the maximum element needs to be eight so far you must be thinking that hey this seems pretty convenient why don't we just have one value to keep track of the maximum element and at any given moment I want to see that hey what is the maximum element I can just simply look at this variable and find the answer the problem is when we do the pop operation out of this given stack then there would be an issue because now let's say that I decide to pop this eight so if I do if I pop this element 8 I know that now 8 is no longer the maximum element present inside the stack but I don't know what is the other element that is the maximum element but instead of just having one simple variable Max we actually need to have a variable another stack called Max where for every single entry inside the original stack for that entry we will have to keep track that what has been the maximum element that we have been able to identifyed so far and keep updating that list depending on the how we uh push out or pop out the elements from the given stack so let's let me try to explain what I mean the idea is let's assume that for the max we have to worry about two operations first one is the uh Peak Max where we are simply watching that what is the max element that is currently present and second one is the pop Max where we are popping the maximum element out at the current position inside the given array so we have created our own Max stack array uh sorry Max stack so this is our Max stack and this is our regular stack okay now let's assume that I wanted to enter value number one so what I'm going to do is I'm going to add value number one currently this Max stack is also empty so far the maximum element at this position I have been able to find is also one so I'm going to store value number one over here once again I identified value number six so because value number six is greater than 1 I'm just going to put six as normal value over here but over here because value number six is greater than value number one so I'm going to say that up until this point of the stack the maximum value I have been able to identifi is six that I have presented over here and some reason if I decide to pop this element out of the stack then I know for sure that this element also needs to be popped out and then the maximum element at this position will be corresponding to the maximum element at this position that is value number one so which is pretty convenient for us now let's try to add one more element let's say three now once again even though we added value number three over here so far the maximum value we have been able to identifi up until this point is once again six so we are once again going to mark value number six over here and then once again let's say we add value number eight so once again we are going to add value number eight over here because that is the maximum value we have been able to identify so far let's repeat what we have done we did the push operation in big off one time no issues with that now at this at any given moment we can also do the Peak operation uh and the moment we do Peak operation whatever element is located at the top of the stack we should be able to see that so this is also going to happen in big off one time so once again no issues with this one so we already took care of two variables we can also do the pop operation easily from the stack so pop operation can also be done in big off one time and we can do Peak Max as well in big off one time because this is also being happening or maintaining in constant time so this also happens in constant time so we took care of four operations in big off one time just by simply using these two different Stacks but now the important thing is that how we are going to manage the pop Max operation for that we will also have to do the pop so let's try to First do couple of Pop operations if I pop element number eight out of the given stack which means now stack does not contain eight value anymore and I will also have to update the maximum element up until this point as well okay now at this position let's say I decide to do pop Max so if I do pop Max at this moment I should not be kicking out value number three from the stack because this is not the maximum element so far the value I should be kicking out is actually going to be the value number six so what I'm going to do is that I'm going to kick value number six out of this given list up until every single point that I have been able to iterate so far and the moment I kick value number six out I'm going to do a peak operation to see that if this given current maximum value if that is greater than the current maximum value I'm left with and if that is the case then I will need to update the given Max element to add in incorporate value number three as well because remember that in the previous state in this state we did not had value number uh six as part of the given uh sorry value number three as part of the maximum value so far but because we did the pop Max we kicked a value number six out and at the same time we will also have to pop these two elements out as well and we would be left with value number three okay so this is the whole thing that we need to do and this is how we can solve this problem using two St Stacks in order to con convey this message so this is the whole solution and using this we can complete everything in big off one time all five operations so now let's quickly see the coding solution and then things will be make much more sense okay so now since this is a lead code premium problem and we don't have that subscription at the moment I'm just going to explain you the solution in the notepad but this code would work fine and the code is also present in our GitHub repository so let's understand the code so first we are going to create couple of inte couple of stacks for stack and Max stack now for the push and for the pop and for the top we need to the all of these three are standard operation the thing is pop and top are going to remain the same the only problem is that for the push operation we actually have to push the element in both the places which means in the stack we are just going to push it as a regular push entry but for the max stack we will first have to check that what has been the maximum element inside the given stack by based on the definition of this x value so far using math. Max function and checking that what has been the current maximum in the max stack versus the current value we are trying to enter so we are always maintaining the maximum element for any given X element inside our Max stack okay then for the pop operation we will have to pop the element from both the places Max stack and also from the given regular stack for the top operation we simply have to check that what is the maximum element on our regular St uh stack uh and we can just do a peak operation now for the peak Max operation we will need to do the same operation but now this time in our Max stack rather than our regular stack and the last one is the slightly more complicated method that is the pop Max method where first of all we are going to initialize a new stack called buffer because remember uh the value we are trying to kick out is presented somewhere in the middle in the regular stack so meanwhile we don't find that value we will have to buffer that from our regular stack so that's why we are going to push every single element uh from our normal stack to the buffer stack until we find the top element to reach to the Max and then we will simply pop that element out from the regular stack at the same time we are also going to pop that element out from our uh Mac stack as well and then in the end in inside the buffer we are also going to push all of those elements into our regular St stack using the elements that we just stored inside our buffer stab temporarily so that's why this pop Max method is slightly complicated method and uh you can see the coding solution present onside our on our GitHub repository so hopefully this explanation made sense to you and uh yeah thank you so much
|
Max Stack
|
max-stack
|
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the `MaxStack` class:
* `MaxStack()` Initializes the stack object.
* `void push(int x)` Pushes element `x` onto the stack.
* `int pop()` Removes the element on top of the stack and returns it.
* `int top()` Gets the element on the top of the stack without removing it.
* `int peekMax()` Retrieves the maximum element in the stack without removing it.
* `int popMax()` Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the **top-most** one.
You must come up with a solution that supports `O(1)` for each `top` call and `O(logn)` for each other call.
**Example 1:**
**Input**
\[ "MaxStack ", "push ", "push ", "push ", "top ", "popMax ", "top ", "peekMax ", "pop ", "top "\]
\[\[\], \[5\], \[1\], \[5\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, 5, 5, 1, 5, 1, 5\]
**Explanation**
MaxStack stk = new MaxStack();
stk.push(5); // \[**5**\] the top of the stack and the maximum number is 5.
stk.push(1); // \[5, **1**\] the top of the stack is 1, but the maximum is 5.
stk.push(5); // \[5, 1, **5**\] the top of the stack is 5, which is also the maximum, because it is the top most one.
stk.top(); // return 5, \[5, 1, **5**\] the stack did not change.
stk.popMax(); // return 5, \[5, **1**\] the stack is changed now, and the top is different from the max.
stk.top(); // return 1, \[5, **1**\] the stack did not change.
stk.peekMax(); // return 5, \[5, **1**\] the stack did not change.
stk.pop(); // return 1, \[**5**\] the top of the stack and the max element is now 5.
stk.top(); // return 5, \[**5**\] the stack did not change.
**Constraints:**
* `-107 <= x <= 107`
* At most `105` calls will be made to `push`, `pop`, `top`, `peekMax`, and `popMax`.
* There will be **at least one element** in the stack when `pop`, `top`, `peekMax`, or `popMax` is called.
| null |
Linked List,Stack,Design,Doubly-Linked List,Ordered Set
|
Easy
|
155
|
144 |
hey guys how's everything going this is chaser who is not looking at algorithms in this video I'm going to take a look at 104 binary tree pre-order traversal at 104 binary tree pre-order traversal at 104 binary tree pre-order traversal because I'm a front-end engineer and because I'm a front-end engineer and because I'm a front-end engineer and there you know we have a lot of tasks to do with the Dhamma right dominating Dom traversal and Tommy is actually a tree so I want to spend some time on all the tree traversal problems okay about the inner travels I have already done it before it's 994 please search on my channel for that and in this video I'm going to take a look at pre-order okay so we are a look at pre-order okay so we are a look at pre-order okay so we are giving the tree like one new one two three we need to return one two three right like okay so yeah so free order means the route must be first collected like route left right so this route left right order if you if we if you still remember how we do in you know Travis oh you know that actually pre-order is a little easier than the pre-order is a little easier than the pre-order is a little easier than the inorder traversal because it's actually the order we step on the nodes is the order reflected in those right we step on one and they can click this result so we step on one step on to step on three then the results one two three but four in order it's not in order is left would left root right so when we are step on one we don't know where the left is so we go to step on its left but this might be still left so we step a step and find the leftmost left nodes and then clicked right so the order is not how we step on a node at work I'd like to separate the tree traversal two to two phases like to process the first one is what so suppose did a little man step on the root and now let's think how it will move around the graph move on a move up around the tree but there is another basket money in his hand he like to collect the result right in some order so if a pre-order traversal in order so if a pre-order traversal in order so if a pre-order traversal in pre-order traversal is step on one then pre-order traversal is step on one then pre-order traversal is step on one then e ke can directly click the result and then the leg the next one would be go to left and then get to wrap right goes left and they still left then they go to lap right so for each node each walk step on the route and click the result and then go to left click the result now and do that recursively and if it is in order it was step on one but he will not collect the result he was step on the left right first step on it and then collect the result right yeah cool so let's try to intimidate the first idea of course is recursion as create a walk method the it accepts a node as a parameter and another one is a result so when this function is done we will return walk root that's right so now we will step on a node as we added last here one two three right you get the node would like to resolve of course if notice rule dude you're nothing right you do nothing and if it's not know of what do we clicked so result well push the know about and then what do what we walk on step on the left node right so walk lat and then what and step out left and then if it's not you'll become step on left so yeah it's working wrong try ooh ah I'm sorry I forgot to pass the result the last I'd need to try result yeah I think we're good let's submit yeah and now the time and space of course the time it's a linear for all the nodes space there's a call stack right so the max height of this tree max Oh max height oh hi three so worst case worst it's up in you now let's try to rewrite it in an iterative way nerium is very simple just like we did it here we walk and then we walk and we collect right so we first of course idiot that this is a DFS so we use a stack we put a root in the first put a root in and then get the root pop the hood and click the result and then push right then left and right so now we can handle the left again and then like you see if it's possible we get left right or something like right left right cool so this is what we want let's create the result and the stack would be rude were beautiful in it so our iteration works continue while the stack is not empty we pop the top note back finally we need to return the result topic is so previously this nor we do nothing right so continue and if it is not new what we do just like we did here we reflect the result gosh Wow and then result remember we need to write before left right so we push right which is top right not a result for that result in a bad sugar skull stack down push top black and then it's done so try cool yeah it's still accepted the time and space time yeah it's the same million time or space well actually it's the same here is the contact but here is actually stack up the odd path the right node actually so if we do one it will stack the right the left and then right so for DPS path the corresponding right notes list of the deepest path so it's still most cases in your time so that's all for this problem I want to address that for three different tree may have the same pre-order so you see may have the same pre-order so you see may have the same pre-order so you see for one nor two three we got 1 2 3 right 1 2 3 we got 1 2 3 but if you got 1 2 3 like 1 2 3 it's still one two three right or it stays a little here still one two three one two I'm sorry there's no rule here okay so actually this did this what is the one two new ah I see actually each code uses the PFS format BFS to construct the tree you see one two new or three so if you want to put a 3 here it should be 1 2 more 1 2 3 right yeah so even for this one is still 1 2 3 so if you just get the one array of the internet reversal we cannot construct a tree it's not unique so that's what I want to say oh okay so we still have a little time why not we just read we try just do the in your caramel sauce not try you know the traversal okay so let's construct a tree call it 1 2 mm 3 and then 1 4 1 2 3 4 mm-hmm oh there's no space I think ok 2 3 4 5 6 ok this is the tree we're gonna take and let's try to do it with another travel so first we will do it in recursion it's the same basically the same remember we get root we need in order we should be left root right order right so we will walk on the node if it is no of course we do nothing and between the result and now I like this we welcome walk on one but now we have week we shouldn't connected collect it so we will continue walking - we cannot collect it walking - we cannot collect it walking - we cannot collect it no we can't collect it because there is no left no you see there's no left node and then we will collect two and then four right like the right and then come back to one okay so the recursion should be we walked one and then because it has left we walk to that and then there's no left and then no one left so we collected this result and then there might be four right so there still might be tree here and then we walk on four okay so you see the order we just need to modify the order a little I think just like this we walk and until the last one back to we cannot walk to the left right it's no we return and now we collect which is two and then we go to right and then with these three is down so the walk for this node is cos theta and then we collect one yeah so that's it I try to run my code so we are two for one let's see if it is right not death but the tree oh okay so it should be new or level two four one six five three so yeah that's it so we just need to change one liner to modify the order here okay now what about in order to travel so for the preorder traversal for the stacked okay and this is a little more complicated than the pre-order more complicated than the pre-order more complicated than the pre-order traversal if we got the route and then what we get remember deep the push stack the element is pushed and stacked is actually a walk right but now we only collect a result when we pop on top of the enemy hmm for a pre before in order travel so when we get route we need to collect it later so we still need push route in right now could not prove root but right push right in and then push root and then push left right and then what's the next one is we get left out and we push right root and then like the tree here we push one end up with Sri in one end and push to it now we handle it too but still we need to push left in it and left no it's true Bishop put it right in and then root and then left right so the old stack should be three one four two left is new enough so - no one four two left is new enough so - no one four two left is new enough so - no right three one two yeah this is left so you should be disorder left good right and on the right route right yeah for something like this the reason is that we need to push the elements in a stack but we push it because if we get to if there's not a note here we need to handle that first right so we got 2 4 2 1 3 it will become like bacteria 7 so it's 7 to 4 and then 1 3 right okay so there is a stack like this I'll create a push stack awful which is no so when it push all the left node in it so while note please laughs stack push no the first note left no actually this is the Dybbuk liked the result order in a stack it's not like this it's actually it should be in the stack Misaki should be one we got one root okay good you push root and then black and then still continuing left right now we talk we when there is no left like a two week like this lab click this note and push it right left in if there is so it's still good left it's kind of like right and then left well you should we should explain this with the rule tree okay we push that so we now will push good end okay now well now we start popping right well first push will push one two in it because what push in it now we should collect the result okay we pop this new oh we just continue I there should be not new in it so there's no need to check this one okay the puppet we get the first one with no left one no left note so is to we connect the result push top well okay then we'll start working out its right so we push stack top right this is what well call all the function recursively you push for in okay for is in a stack and now where is the last one so four will be popped and then we go to one collected and then pop3 and pop push three push four or five push six and the gland then collected three six five three mmm I think this should work next trap we got okay we got two four one and then six five three yeah that's it so that's all for the
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
978 |
hey everybody this is larry this is day 15 of this summer hit the like button subscribe for enjoyment just because i know you think about getting fun and i'm still in this thing um okay okay i mean it goes up and down and up and down kind of like this even if they're the same um um so yeah if if it is increasing or decreasing right a couple um this is greater than zero and so okay so if this n previous sign is less than zero that means that the signs are different then our streak of contract is equal to zero in this case that street is more than two because uh well increments by one so we start this trick off of one because we skipped the first number first and then yeah there's always this pick up from one um okay now if x is less than p and previous side is greater than zero and of course you can write this one uh should be good one the same as this i wanted previous slime book is like even if you come here so just a little bit but we can do something like this is the same time as something like this but then of course now we have to be careful this doesn't work for about one element thanks and maybe i'm missing that speed a little bit um okay um oh i know that they feel similar but the reason why this is i like just better versus the other side the other way in fact there's much reason is i think this is all right is happening okay it's still wrong though that's all you have to be careful about um um okay so this looks okay that was still i should i just keep forgetting about a i forgot about the right i was thinking about zero case a lot and then i got distracted by messing up another places that i forgot about it so this should be two for the nine and five uh um someone liked it yeah uh so this is um um
|
Longest Turbulent Subarray
|
valid-mountain-array
|
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if:
* 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.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109`
|
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
|
Array
|
Easy
|
1766
|
352 |
good evening everyone today we are going to do the daily read code challenge of 28 January 2023 that is question number 352 data stream as disjoint intervals in this question they have given us a data stream which is having non-negative stream which is having non-negative stream which is having non-negative integers that is all positive integers are there and we have to form a list of disjoint intervals and what they want us to do we have to implement a class there are two things classes and objects and we have to implement a class and classes initializes the object with an empty stream now after that we have to add numbers to the stream by using this add num function and after that we have to add integers and make a interval and interval should not be overlapping we have to think upon that so let's move on with the example and see it better so what they want us to do Suppose there is first is one is there no issue one is also there okay after that one you have three so three will also be added and three will three is also not overlapping so three is also added after that what they want us to do first is one comma one second is this after that when you add 7 is also not overlapping so it will also get added as 1 3 and seven so these are added after this when you add 2 you will say that one two three so one two three is overlapping that is their consecutive so your next and insertion will be 1 comma 3 2 7 comma seven so this would be your next answer so this is what you have to keep in mind that you have to avoid overlapping of intervals and you have to add intervals this is all you have to do so after this when you add six again there is overlapping from six two seven so what we will do next answer Finance next addition will be 1 comma 3 and 6 comma 7. so these all you have to return all these answers one two three four five you have to return all these five possibilities in your answer so how can you do that please try to think upon it is very simple approach if you understood what the question is trying please try to think and then come back to the video so if you thought about the approach what we can simply do is the best approach is we are given numbers 1 3 7 2 and 6. so what's the best thing we can do to make sure that there are there is no overlapping what if we sort them sorting we can do now that is one two three six seven this way we can get the intervals and we can easily push it to our answer but what if there is copies of it seven or six what if there are copies to deal with these copies we can create a set start will only store unique elements and we will avoid copies so what I mean to say is we can simply sort it to make sure they are continuous that is one plus one is two and two plus one is three and six plus one is seven that is when the element is having the difference of 1 that means they are consecutive and to avoid duplicates we are using set to ensure uniqueness that's all you have to do and after that we will create a vector of vector and we will push it to our answer we will push the result in this answer yes or no we can do this we'll push our result into this vector or vector answer so let's see in the code and write the code line by line to see how it is working so let me just zoom it for you and we will start coding so to code this we just have to follow all the instruction As Told in the explanation and the intuition behind it what we will do we will create a global set and we will pass it to we will initialize it in the class because you have to initial class initialize the object so we'll clear the set every time and after that what we simply have to do we will insert the elements into our set and when we are done with this we will create a vector nums and we will pass all the set value inside this nums Vector how can we do that we can simply write begin as T and NST this is the inbuilt STL call which I told you in the previous video as well you can get all the values are set inside this Vector when you have done this you will initialize in 10 is equal to nums dot size so you can iterate our Loop and inside the loop you will also need to create a vector or vector to return our answer that will be result and it will return our answer and we will return result so what's the thing happening in the results we can simply make a loop for but before that we also have to sort it sort num dot begin comma none Dot so if we have sorted it we will we are sure to get our answer and after that we will just run a loop for enter is equal to 0 I less than n I plus and we will initialize our starting index yes so now what I mean to say is in this sorting we will initialize this as left or starting index and when this difference is greater than 1 it will become the end point that's what you have to do you will run a simple Loop of o n that's it so you are running a loop and you are initializing your start as numsai and after that while I is less than n minus 1 because you are quoting this condition that is norms the number plus 1 is equal to nums I Plus 1. that means 1 plus 1 is equal to 2 in this case 1 plus 1 is equal to 2 this is what we are checking and when we are at the second last index we are adding it so we don't want our code to fill that's why it is n minus 1. after this when this is the condition we will just increment our I and when all is this is done and when the difference is greater we will push it to a result bye now we will push our start and we will push our num's I value because this is the value now where we are stopping it that is when we reach 3 plus 1 it is 4 and this it is not the case so we will stop so we will push the 3 because it is the ending index of that set three one two three is the ending index so that is what you are doing and when you are done with this we are good to go so let's run and check whether it is working or not I think you've mistakenly change this function this was void add number yeah it was initially this now it should work so yeah it is running for all the cases let's submit it and check whether it is accepted or not so yeah it is accepted as well so the time complexity in this case is O and login because we are sorting and we are running a loop for n so it is n log n but we can also improve this if we use the inbuilt property of said that they are already sorted if you only used it we can remove this line from here but it is still of time complexity and login because we are adding n elements and insertion take login value so n log n is the time complexity so we can only take set and make it work so let's just sum it and check whether it is working or not so yeah it is also accepted so if you have any doubt related to the question please comment it in the comment box thank you so much for watching please like share and subscribe 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
|
1,293 |
hi guys welcome to algorithms made easy my name is khushboo and in this video we are going to see the question shortest path in a grid with obstacle elimination you are given an m cross an integer matrix which is named as grid where each cell is either 0 that means empty or 1 that means there is an obstacle you can move up down left or right from and to an empty cell in one step return the minimum number of steps to walk from upper left corner which is 0 to the lowest right corner which is m minus 1 n minus 1 given that you can eliminate at most k obstacles if it is not possible to find such a work then you can return -1 you can return -1 you can return -1 in the first example we can reach the bottom right corner in six steps after eliminating one obstacle and in example two we cannot reach the bottom right corner as we need to eliminate at least 2 obstacles to reach the destination which is not possible because the k given to us is 1 and so we output -1 in this particular and so we output -1 in this particular and so we output -1 in this particular case now let's see the first example in detail and also see how we can solve this question so here's the representation of the first example that was given to us wherein we have the obstacles which i have marked with this blocks and this are the empty cells now the k given to us is one that means we can eliminate any one of the obstacle in order to reach the bottom so now amongst the different parts that we can take here are three parts from this one we can reach the bottom right corner wherein we do not have to eliminate any obstacle over here we can eliminate this one or remove this one and reach the bottom right corner and in this particular case we can reach the bottom right corner by removing this obstacle in these the first one takes 10 steps while these takes 6 steps and 6 is the minimum number of steps that we'll need to take in order to reach the bottom right corner so 6 is the answer in this particular case now how do you solve this particular question so over here we are given a few things that we need to take into consideration the first is the condition of moving so we are given directions and we also have obstacles directions up down left and right and obstacles that means we can remove at most k obstacles and still move in that direction so we need to take this k into consideration and we need to take the directions into consideration now once we know the conditions we also need to think upon what is the approach that we are going to use along with these conditions the thing that we are going to use here is bfs because we need to find the shortest route that too quickly so this means that our solution is going to be the combination of bfs taking into consideration these two things in mind now one more thing that we are going to see in this question is optimizing the bfs in order to get around with time limit exceeded error so let's start with our bfs as we know we need a q when we are working with bfs so we'll start with our initial position which is 0 comma 0 and we'll see in what all directions we can go that is we are going to find out the valid directions and we are going to keep adding these valid cells into our queue for further processing now the next question is what are we going to store in our queue so we are going to store three things first is the row and column of the grid cell and the second thing that we are going to store is the obstacle now you can either store the number of obstacles that you have crossed or the number of obstacles that are there with you that you can cross so over here for this video i will be using the balance of the obstacle that is the number of obstacles i can still cross so in our example initially the k given to us was one and so we are taking one in here so it is a array of three things row column and the obstacle balance initially we add zero 0 and 1 which is our base case into the queue and then we'll start processing this so we'll pull this out and we'll find all the valid directions from the current point which are these two why we are not going to take these two because these are outside the grid and are not valid now this becomes our cue after adding the directions in which we can move from our initial position over here you can see that this 0 is the obstacle balance for this particular position because we have used our k to cross this particular obstacle with this we can say that we have taken one step in these directions now since the queue is not empty we'll go again and pop one of the elements out this is the position 0 1 from here we can go into 3 different directions y we can go over here because we still have k equal to 1 left with us for this particular combination now adding these into the queue again now if you would see this position is equivalent to our starting position or the initial position and with this we are actually adding redundant coordinates which will have to process and that will increase the time that we are going to take in order to process all the cells and get the output so over here we can come up with memoization that is storing the visited cells or visited combinations now what all things can we store we can store the combination of these into a visited array and see that if this combination is already calculated we do not need to calculate it further but we can skip it so we'll add i j k into the visited array so that would be a three dimensional array which would be of dimension m cross n cross k or we can take k plus 1 now that's how we are going to store it so we are going to store the trio of i j and k as visited or unvisited if we do it over here at this particular moment we will have all these elements in our visited array marked as true that we have seen these elements this was the initial node this was the step one and while processing this particular element we also visited these two so we are going to add these into our visited array as well and we are not going to visit 0 1 because we already had it in our visited array so this is the current state if we are taking memoization into consideration now let's move ahead and we will take this element out of the queue and process its neighbors while going through its neighbors we will see 0 and 2 0 are still unvisited now we will say that this particular cell was already visited but it was visited while k was 1. over here if you see the k has become 0 and we can still visit this and find another root wherein k is 0 from this particular cell so we'll add it separately and that's the reason why we are storing the trial of these three because this is going to make it more efficient in memoization so let's add these two in the queue as well as in the visited array now we have come to the end of step one and we'll now start processing our second step so we increase the number of steps and mark the end of this particular step as the last element again taking one of the elements out and processing all its neighbors we see that this one is already visited these are unreachable and this is a valid grid cell so we add it in the queue as well as in the visited array and move ahead repeating this for another element which is 1 0 and over here we can go in three valid directions and so we add all those three into both our q and in the array moving ahead over here we can see that these are invalid positions and these are already visited if you see 0 1 0 which is already there and 1 0 which is also already there again moving ahead we have already visited this particular position and these are unreachable why is this unreachable now because the k has become -1 because the k is 0 the k has become -1 because the k is 0 the k has become -1 because the k is 0 and if we are trying to go over here k will become minus 1 which is not possible and so this is unreachable next we again increase the steps and take the next iteration into consideration now we repeat this and for this particular grid we can only move in downward direction and we added in the queue as well as in the visited array and move ahead again we increase the steps and process the next iteration finally we have reached a cell from where we are going to reach our destination so we process this increase our steps and we take the neighbor add it in the queue and also in the visited array now while we are processing this particular position we find it to be the destination position that we were going to reach and so we do not need to process any further but we can simply return the number of steps that we have taken till here which is equivalent to 6 and that is our answer so this is how we are going to solve this particular problem with memoization by taking the trio into the array so let's go ahead and code this out initially let's take a few variables so these are the four things that we are going to need first is m and n second is the direction array so this will help us going into all the four directions third is the visited array which is of m cross n cross k plus one and fourth is our q that we are going to use in our bfs as an initial step we are going to add the initial starting position into our queue so we do q dot offer new int 0 and k now we are going to start with our iteration and before that let's return -1 if we are not going to get return -1 if we are not going to get return -1 if we are not going to get anything out of the q will keep processing while the queue is not empty and over here we are going to take a variable size which is going to be q dot size so this is the basic thing that we always do in bfs and also while we are coming out of this queue we are going to increase the number of steps so for that let's also initialize steps as 0. now over here we'll iterate while size is greater than 0 and will also decrement the size at the end of the loop in which we are going to take the current element that will be q dot pole and this will give me the current cell with the k value the first thing that we are going to check over here is whether if current is the destination return the step so let's see if current of 0 is equal to m minus 1 and current of 1 is equal to n minus 1 return steps otherwise we are going to go in each and every direction so go in all the valid direction so now for this we are going to use the direction array so over here let's find our values i becomes current of 0 plus d of 0 j becomes this and end obstacles becomes current of 2 so this is the next position that we are going to calculate once we have all this with us we are going to traverse through valid cells so for that we are going to write the condition so this is the validity for grid after this we also need to check the validity for the number of obstacles we have and if the cell is empty or not so let's see if the cell is empty so over here what we are going to do is we are going to check whether it is empty and whether it is still unvisited in that case we are going to add it in the queue and mark it visit it so we'll offer new wind and we'll mark it visit it now there is a condition that the grid is 1 and we can cross that obstacle in that case also we'll add it in the queue so let's take that condition so we take whether the grid is 1 and we still have obstacle balance left with us and that particular position is not visited then we'll add it in the queue and also mark it visited so this will take care of iterating over the cell and this will take care of incrementing the steps so now if the steps are not returned over here then there is no way possible we can reach the destination and so in that case this particular statement will return -1 as expected let's run this return -1 as expected let's run this return -1 as expected let's run this code and it gives a perfect result let's submit this and it got submitted the time and space complexity for this particular solution would be o of m into n into k that's it for this question guys i hope you liked it and i'll see you in another one so till then keep learning keep coding
|
Shortest Path in a Grid with Obstacles Elimination
|
three-consecutive-odds
|
You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _given that you can eliminate **at most**_ `k` _obstacles_. If it is not possible to find such walk return `-1`.
**Example 1:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[0,0,0\],\[0,1,1\],\[0,0,0\]\], k = 1
**Output:** 6
**Explanation:**
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> **(3,2)** -> (4,2).
**Example 2:**
**Input:** grid = \[\[0,1,1\],\[1,1,1\],\[1,0,0\]\], k = 1
**Output:** -1
**Explanation:** We need to eliminate at least two obstacles to find such a walk.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 40`
* `1 <= k <= m * n`
* `grid[i][j]` is either `0` **or** `1`.
* `grid[0][0] == grid[m - 1][n - 1] == 0`
|
Check every three consecutive numbers in the array for parity.
|
Array
|
Easy
| null |
1,601 |
Hello Gas, today we are back again and today's question is our maximum number of achiever transfer requests and after all this question building is zero to nine minus one and every building has some employees and what do we have to do? Transfer has to be done from one transparent building to another building and the building which is full, we have to do it in such a way that the net change of the transfer should be zero as you can see, an example is also visible here And if 1% came from building one to building zero, And if 1% came from building one to building zero, And if 1% came from building one to building zero, then how much did it become -1, if we talk about zero, then how much change came in building zero, if we look at what we have, then 2% went, then -2 came 2% went, then -2 came 2% went, then -2 came and the day before yesterday. If we look at Building Ban, then plus one, similarly, if we look at Building Tu, then what is the change in Building Tu, 1% has gone what is the change in Building Tu, 1% has gone what is the change in Building Tu, 1% has gone from Building Gan and the day before yesterday, Building Tu has gone from Building Tu to Zero, so here it has become minus and here If seen, it has become a plus here, now the building has come, so if seen, the day before yesterday, building from here, from building one to building one, it has become a minus here too, so how much has been the net change zero net. Change is zero So brother, if we have to tell this thing, then gas, this is ours and it will not be known the day after tomorrow, we have to show its net change, brother, after all, the one who went every day before yesterday, in so many requests, so how many maximums is that? People, how many requests have we gone through, we have to tell that thing and its net is changing, basically we have to do this by looking at the things, so if we look at it, we have to talk about the maximum number of requests, how many requests must have looked like this, okay, how many? If this thing becomes achievable with us in the request, then to do this question, whenever you see such questions, to do this question, I will ask you that brother, why do you have what you have because what will happen if brother, you have done what you have. Sent it the day after tomorrow but you ignore it because both things are included in it, either you ignore the request, you only get the maximum number of requests, but what do you do, you either accept the request, there are two conditions and whenever there are two conditions. There is such a caste that a request is made brother, either you ignore it or you flood it further, which is the time, what do we do with it, so for this, first of all, what do I make, why do I make Desi Gali, because we have to make every Regarding the building also, I saw that we stored it in a function on each building and saw that after all the requests coming from us, I did plus one and minus one and saw how many people are being transferred from there, that is, in the building. For what we will have to make a vector, for that let's make a vector sum. Okay, and what is its size. Whatever request we are going to make, we will reject it. We are okay for that and finally we will send the building. After completing the request, what do we have to see? Is our next sum achieved? Is our net sum zero? What will we do to translate it? We will check the formula brother and brother of two and tell us whether the building in the camp which we have just made a vector is that particular building and the story is also something other than zero. If there is something other than zero then return it brother. If not. So what will we do, we will check our answer, if it is not the maximum answer, what will we do, if it is ignored then what will we do, we will simply do our helper function tomorrow and we will say brother, we have done your request, if there is no solution then Will not give us alcohol and will postpone our function tomorrow but if we accept his request and we are ok, this is right, this is going right, so many people are coming and we have so much space free, then what will we do? What is ours on the first index? On the first index, we have hit from. So where are we TV coming from? So where are you going to go, brother of Mines. But in the helper function yesterday I did my helper function so I named it as gas which is important to understand. But friend, what have we to do, brother, let us see what the maximum can be, now that we have accepted this request and today's challenge has been completed and have solved one more problem, I am happy with you all, I hope you enjoy. Must have come across this problem and see you again later.
|
Maximum Number of Achievable Transfer Requests
|
maximum-number-of-achievable-transfer-requests
|
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n`
| null | null |
Hard
| null |
503 |
That if suggestion also singh question number ₹5 off That if suggestion also singh question number ₹5 off That if suggestion also singh question number ₹5 off list code scooter element to sources of previously authorized next filter element way this question in this question veer next element of subscribe button pressed next for bo before every element in what is the number is The first number to you should take the example is that see second only and I want to meet you find that in circular hotels point to 300 finishing etc 3123 which is the first number then all the numbers will return minus one but instead of giving this Problem For Straight Understand It's Not A Strong Will Consider Circular Edit Image With Me To Find The Next Key Development In Districts Of Vanilla Tweet Come To Joe Circular Point So Let's List Basic Problem First Position To Fans Brian Adams Stop You Have And Square Solution Format For Every Element YouTube Channel For Next Element And You Will Find A Greater Element 16 Food Causes That Toe Vanish Ka Solution Soheb * Optimized To Approach Ka Solution Soheb * Optimized To Approach Ka Solution Soheb * Optimized To Approach And Gives Strength To Optimize Approach And Give Water And Select The Hard Work Of Toilets F-35 Is Hair Pack Abs that Of Toilets F-35 Is Hair Pack Abs that Of Toilets F-35 Is Hair Pack Abs that is so rocky aa don't have any elemental states so initially I will put them into a stack slide element of this track 39 This phone number is that in this step will strive to find out the first element which is great then and Freedom and elements will remove all the elements from distant land should speak only have element hair soft is not beginning phone hands free demo and at last it will suffice for introspection and similarly it will vote for elementary what you will find the first elements of scripters in Three Special 424 3.4 Surat Mein Right The Short Special 424 3.4 Surat Mein Right The Short Special 424 3.4 Surat Mein Right The Short Question Answer Before End And December Tweet - 1m - 1m - 1m Ki Piane So Now Let's Come To A Mean Sorry For The Retreat - One And For This 349 For The Retreat - One And For This 349 For The Retreat - One And For This 349 Computer Number 256 Number 21 Loot Posted On 23 Nov 16th After Visiting Element Minute Report Subscribe Now To Swift Elements From West To Attend Na Event In The 1st Element Subscribe And Does Not Mean That Sent Is The Answer For 2nd Sure The Like This Is Not Kansa Vadha And Similarly The Evil Spirit Has Great And Vansh Him 102 Bath in Vishwabhushan Might Seam and Square But for Every Element Tributes Were Only Doing Things Were Popping Element and Pushing Element and Once Elements for Kids Cannot Be Pushed into the Element in Any Circumstances and Boys Working Interesting logic behind this reason is that support came from Have currently points under-14 limit show I don't 499 points under-14 limit show I don't 499 points under-14 limit show I don't 499 mirror that Redmi element there light of course is not an answer for development will never be the answer for this left morning time's settings show all active view suite with 1231 not a solution for four Days Will Not Be Seen That Solution For Slaps For Dam Good Will Be The Best Within 100 Probably Approach Time So Now Platform With Synonyms Of Question Sngh Circular Are So Let's Pray What Can You Do To A Comment Circular Is That We Can Use This From Maze Pendant And What We Would Not Give To Technique Swar Hair Fall Element To The With Three Four Three And One Should Be Gone To Fur Element 273 14.15 One Should Be Gone To Fur Element 273 14.15 One Should Be Gone To Fur Element 273 14.15 Win And Points Fakir And Of The subscribe this Video With Just One Do n't forget to subscribe more That This Recovery Doing So Will Repeat The Same Thing And Will Find Out The Answer For Each Show 14.2 Join Branch Indore Right Side 14.2 Join Branch Indore Right Side 14.2 Join Branch Indore Right Side For Monitoring Limelight Side More Than Absolutely Coated So The Widening Of Savings Mode Settings Subscribe And Lots Of Residence And Easy To student size that today one more thing is that we don't sugar 2512 is that we can just width logically suggest the every point is know it is plundering index 2012 three and four three do it is the f-18 know I know the length of the is the f-18 know I know the length of the is the f-18 know I know the length of the president Of birth 8th the president do's and don'ts computer course I will say 5mm percent hai tu fir ashok alag se bank officers 500 war model operator android come to end shifted in tax liability's model with spinach and will be 4th index but when Dinesh Karthik and Greater Than 400 to 500 That Building Modeled on His Face and Will Give Me 2006 Science Gautam Buddha Indexes Subha Only Need and So Let's Do It Hit Films Science Recorded and Frequent Visits You Can Start From Enter e Request You Know It is Not Show Will Not And Land Will Be Third Prize Of The End Surat To * Prize Of The End Surat To * Prize Of The End Surat To * A Flying That One And Soe Kya 2210 Us Point Hai Okay Na It's Shubh Written And Equal To Zero And I - - Mist Behind Girl Has Been Discussed And I - - Mist Behind Girl Has Been Discussed And I - - Mist Behind Girl Has Been Discussed By Not Taking It So Until Early Stags and sea and the element add top best episode top's last little influence or equal to om moist white per cent and no amount of your used in the sentence swiss bank of baroda ten people increase the question should point suraj hotspot of that [ __ ] ajay Bhai photo will decide I will check this that [ __ ] ajay Bhai photo will decide I will check this that [ __ ] ajay Bhai photo will decide I will check this track is not anti definitions of its something time element which falls beta din pradesh dance of I so f9 1020 ki padhai se is the result for high flame par st and but IIM par st and will be decided To Follow On Ki And Jumped Missions Ayala Se 10 Min Us Every Element Takes Over S Dot Push Best Names Of Ki Problem Solved I Am Present Tense Views Available User Name Safai Joone To Take Care Decrease With And Point And Shoot The General Singh I Am Sorry Might Be Adopted In The Confident That Of Them Have Electricity 110 You Have Come From Deluxe Toilet And Will Press OK Ma'am Singa Baithe Ho That A That Only Is Boxing Nuts Tried To World Champion Futa Think To Switch On That Is Later For This Case 166 time so let's submitted and several rates from here on the network so let's go into to digit solid body ray
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
815 |
hello and welcome to the cracking fang youtube channel today we're going to be solving lead code problem 815 bus routes before we get into the problem i would just like to kindly ask you to subscribe to my channel i have the goal of reaching a thousand subscribers by the end of may and i need your help to get there if you're enjoying these videos and you're getting value out of them and most importantly they're helping you prepare for your on sites for those big fan companies please consider dropping a sub the bigger my channel is the more videos i can make and the more i can help you get into fang so that being said let's read the question prompt you are given an array routes representing bus routes where routes of i is a bus route and the i bus repeats forever for example if routes of zero equals one five seven that means that the zeroth bus travels in the sequence one five seven one five dot forever you will start at the bus stop source and you are not on any bus initially and you want to go to the bus stop target you can travel between bus stops by buses only return the number of buses you must take to travel from source to target return -1 if it is not possible return -1 if it is not possible return -1 if it is not possible so for example if we have the routes so the zeroth bus so we can think of this as bus zero oops let me change the color here to make it more visible and this should be green sorry bear with me here change the color green okay cool should be able to see that now so this is bus zero this is bus one so essentially bus zero can go to stops one two and seven and bus one can go to three six and seven so we start at one and we wanna get to six so we hop on at one and we can see that the only bus that we can take there is bus zero right so we started at one and we can go to you know stops two uh and stop seven from here so neither of these are our target so that means that we're gonna have to take either one of these and see where we can go from there so the bus one um will get off at three six and seven so none of the three and six are not any of these values but seven is so that means that from seven we can write it until we get to you know three and then we can write it until we get to six which is our final answer so we would need to take two buses right we got on here this is the first bus we took this bus zero and then we got on um we rode this to seven and then from seven we got bus one which took us to six so that's why we have two total buses that we took so essentially what this problem boils down to if you can't see it already is basically going to be a breath first search of the quickest way we can get from source to target right we want to well if we can even get there because it is possible that we can't actually make that route so essentially what we need to do is do some sort of breath for a search where we start it uh you know our source stop and we try to get to our you know target stop and we want the shortest path between them so if we build a graph and this graph will be undirected uh we know that doing a bfs over an undirected graph will give us the shortest path possible between source and target so and again we're looking for the least number of buses so that's why we're doing a bfs we could try dfs to just try to find all of them but obviously that would be a lot more computationally expensive we want bfs because our search will actually end as soon as we find an answer which will be our optimal answer so the trick of this problem actually just boils down to how we actually build the graph for this problem and do the bfs over it so it's not exactly clear how we might do this so let's take a step back and think about how we might build our graph okay let's think about how we might build our graph here remember what we did when we went through the example was we started at one because that was our source and we basically looked at all the possible bus stops we could go from there and then from there we want to look which bus we could take and then which possible routes it had oops there should be a three and a six so we're going to need some sort of graph structure which contains the information for stops and buses because we're going to need to keep track of which stops we've been to and which buses we've taken obviously it's a bfs there is the potential to get caught in an infinite cycle so we do need to be careful that we don't take a bus multiple times if we've already been on it because we should have already reached the answer if that bus can take us there so what we want to do here is we want to build our graph and what we want to do with our graph is we're going to build a dictionary here to represent the graph and what we're going to do is we're going to have you know as the key it's going to be the stop so you know one two or seven and as the value we're actually going to have a set representing all the buses which stop at that stop so we'll have this set here um you know and this will just contain all the buses and this will be our graph so for example if we built it for this one it would look like okay for stop one what are all the buses that stop there it's just going to be you know bus zero and then for stop two what are all the buses that stop there it's again just going to be zero uh for stop seven what are all the bus stops uh buses that stop there it's going to be bus zero and one and again we're using a set here because if there's duplicates we want to avoid that and what do we want to do uh let's see so we have three and again this is just going to be bus one and then six this is going to be bus one so that's how our graph is going to look like for this example and remember that we need two separate sets so we're gonna say visited um stops is gonna be one set and then we're going to have visited you know buses so the buses that we've taken so far is going to be another set and then you know since this is a bfs we're going to need some sort of cue and what we're going to put into our queue is going to be simple it's going to be the current stop that we're at and the route length that we've taken so far so that way when we reach the target if we reach it then we can simply return this route length and we're done so essentially what we want to do is we want to kick off our you know um our you know bfs from basically the source and you know we've taken zero buses at this point and what we want to do is you know we want to process our q so our q is going to take you know whatever stop we're at so say we're at source uh 1 so that means that you know our q is going to be equal to i guess stop 1 and a path length of 0. so we're going to pop this from the queue and we're going to be processing you know the stop one and you know we have a route length of zero obviously the stop does not equal to target because one isn't equal to six um right so one zero so one doesn't equal to six that means that we need to process it and essentially what are the other buses that stop at this stop for one well it's gonna be zero and we haven't taken any buses yet so far so we wanna add our current bus to it so we're going to add to you know the vis oops visited buses we're going to say we've now taken bus oops should we bust zero and what we want to do is what are all the stops along that route have we taken any of them so we can stop at two and we can stop at seven uh neither of which we visited so we can add them both to our queue so that means that our queue now is going to contain okay we can go to stop two and obviously we've taken one bus so far so it's gonna be one here uh sorry this is we've taken you know one um hop so far uh and then you know we can go to seven and that would also be considered taking one so then we can continue processing so we now get to two one obviously two does not equal to our target so that means we have to continue processing uh what are all the buses that we can take from two uh it's just gonna be zero but we've already seen zero in our visited buses so that means that we can't continue on this route because we will already have explored it's already in our visited set if we did we would just get caught in an infinite cycle so actually this processing ends so now whatever is left in our queue is going to be 7 1 so we can pop that obviously seven doesn't equal to our target six so we need to continue so what are all the buses that are in seven it's going to be zero and one and obviously we've already visited zero so we can't take that bus but we can actually take bus one um so we're gonna continue on that so that means that we're gonna add this to our you know visited buses because now we've taken bus one and what are all the stops that bus one um can actually uh go from here so uh we can look at for bus one what are all the stops it can go to it's just gonna be its original route so it's gonna be three six and seven so we can add to our queue all the stops as long as we haven't already been there so uh actually we haven't been tracking this so far my bad uh so what are the stops that we've been to so we've been to stop one we've been to stop two and now we've been to stop seven so that means that we look into what are all the possible stops for bus one because we know we have to take it so three six and obviously seven we can't go because that would just be an infinite cycle so that means we add to our queue that we can go to bus three stop three and then since we have taken a new bus we can increment our count here so now it's going to be two total and then we can go to six and three so now we're going to process our queue further so you know we have three two being popped now and then from three you know this doesn't equal to our target and what is all the bus stops we can or what all the buses we can take at this stop uh it's just gonna be one which we've already taken so that means that we can't go any further there so that's an invalid path now all we have to do is process the six three so we're gonna pop it from our queue we get six three and we're gonna check okay does six equal to six it does actually so that means that we found our um you know correct route and oops sorry this isn't three this is two um sorry this is two so far we've taken a path length of two so now we can simply return r2 and that is the answer that we're looking for as you can see from the example that leak code gives us so essentially that's the approach that we want to take if this explanation was a little bit confusing don't worry once we go to the code editor and we actually write it out line by line it's going to be super clear and i'll break it down for you and hopefully you should understand a lot better usually the diagrams are a little bit hand wavy and it makes sense to me because obviously i've done the problem i know what the solution is so it's a little bit hard to kind of translate that into a diagram especially when i'm drawing with the mouse but let's go to the code editor it's going to be a lot clearer so i'll see you there okay we're back in the code editor let's write the code the first thing that we need to do is actually double check that our source does not equal to the target if it does equal then that means that we don't actually need to take any buses we're already where we need to be and we can simply return zero because we don't need to take any buses so if source equals target we can simply return zero now what we need to do is build the graph and remember that the graph is going to be for the key is going to be a bus stop and the value is going to be a set of all the possible buses that stop at that bus stop so let's define that so we're going to say graph is collections dot default dict set and then what we need is also a queue because obviously we're doing a breadth first search and we use that and we use a queue to do that so we're going to say q equals collections dot deck oops and remember that we're going to be starting at our source and currently we've taken zero buses so let's now build the graph so we're going to say for bus route in enumerate routes and remember that the structure for routes is that routes of zero represents the zero sorry the routes of i represents the ith bus and then all the values at that ith index or all the stops for that particular bus so we're going to say for stop in route we're going to say graph of stop we're going to add the bus to it so now we've built our graph and before we actually do the bfs remember that we can have cycles here because obviously these buses just continue forever and we need to actually return an answer we don't want to get caught in an infinite cycle here because we're never going to return and we're going to fail the interview so let's make sure that we create visited sets for both the buses and the stops to make sure that we prevent ourselves from getting caught in a cycle so we're going to say visited stops is going to be an empty set and we're going to say visited buses is going to be an empty set now we can actually start our bfs so we'll say while q and we're going to pop from our queue so we're going to say the current stop that we're at and our current route length is going to be q dot pop left and what we want to do now is double check that our stop doesn't equal to our target if it does then we can actually just return our route length because that means that we've reached our destination so we're going to say if stop equals to target then we're done we can just return the route length otherwise what we want to do is we now need to traverse all the buses that stop at our stop and double check that we can actually take them what does it mean that we're allowed to take them basically that we haven't taken it before remember we don't want to get caught in that infinite cycle where we just keep taking a bus over and over so we're going to say 4 bus in graph of stop so basically all the buses that stop at this current stop what we're going to do is we're going to say if the bus is not in visited buses obviously we don't want to take it again we're going to say visited buses dot add the bus so we want to make sure that we don't get caught in that infinite cycle so that's why we're adding it here to our set now what we need to do is for this bus that we're about to take from our current stop we need to see all of the stops that it can go to and whether or not we've already been there so we're going to say four stop in routes oops routes of bus so all these stops that this bus can take we're going to say if stop not in visited stop so basically if we haven't already been to that stop remember we don't want to get caught in an infinite cycle we're going to say visited stops dot add stop so we're going to add it to our visited set and then we need to add it to our queue for further processing so we're going to add that stop and we're going to say that our route length is now going to be incremented by one because we're now taking a new bus so all we need to do is oops run this q and either we're going to return our answer here or our queue will break because there won't be any more processing to do which means that we were not able to reach our target destination from the source so we can simply return -1 as the problem can simply return -1 as the problem can simply return -1 as the problem tells us so minus 1 if it's not possible i'm just going to run the code quickly make sure i haven't made any what did i not close where is this line 30. oops okay cool glad we did that uh let's just okay cool so that seems to work let's submit this double check that it works and great all right cool the first time i tried to record this i don't know what happened but i got a tle um so what is the time and space complexity for this algorithm well for this problem essentially in the worst case every single uh bus will go to every single bus stop so that means that when we build our graph we're going to have you know uh like basically an n by n structure in the graph because every single bus can go to every single bus stop so it's going to be big o of n squared in the time because we would need for every bus potentially to go to every single stop in order to find our solution in the worst case and similarly because we could have that structure represented where every single bus goes to every single route we could potentially have to represent that in our graph so our space is actually also going to be big o of n squared so that is your complexity analysis for this problem um this one is a little bit weird i think it's kind of tricky to realize how you're gonna set up the bfs for this it's not exactly straightforward um but hopefully this solution has um basically made it easy for you i think once you've seen this one it's quite easy to remember how it's done i don't think it's particularly that difficult it is kind of one of those aha moment ones where uh okay maybe you won't figure it out on an interview but if you've seen it once and then you get it a second time like you'll get it like that no problem so if you enjoyed this video please leave a like comment subscribe to my channel if there's any videos or topics you want me to make videos on please let me know in the comment section below and i will be happy to get back to you guys i just need like a topic um you know a lee code problem number or just you know anything you want to leave in the comment section below system design product design anything like that just let me know and i will be happy to make those videos for you guys anyway thank you for watching have a nice day bye
|
Bus Routes
|
champagne-tower
|
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106`
| null |
Dynamic Programming
|
Medium
|
1385
|
1,086 |
welcome to interview Pro in today's video Let's solve the lead code problem high five this question appeared in interviews by Goldman Sachs and Amazon the problem gives the list of students and their scores we have to return the average of top 5 scores of each student let's see this example we have two students student 1 and student and this course are listed like this to get the top 5 scores let's sort this course in descending order so the first student marks would be like this and the average of the top 5 scores of the student will be 87. and then we have student 2 let's sort these course as well in descending order and the average would be 88. we need a data structure to store the sorted scores and also the list of students we can make use of a dictionary which uses student ID as the key so that it would be easy for us to get the list of scores for a particular student and then each student ID key will have the list of scores as value in the dictionary this course have to be sorted in descending order to get the top five uh scores so we have to first get the array of scores because uh the scores is not given in the form of an array in the question so first we have to form an array of all this course for a particular student and then sort them in the descending order instead of using an array and sorting them in the descending order we can make use of a priority queue as well right which sorts the elements as we push this course to the queue and after processing all the records we have to return the average for each student ID like this so the output for this example would be 1 comma 87 that means average of the student one is 87 2 comma 88 means the average of student 2 is 88. in the given example the first input is 1 comma 91 that is one of the scores of student 1 is 91 so we'll create a key for student one and assign a priority queue with the value 91 then the next input is 1 comma 92 we have to insert the student one key is already existing in the dictionary so we just have to insert 92 to the priority queue and since this is a priority queue 92 will be coming first then we'll have 91. as we want the scores to be sorted in descending order we can use our custom comparer and make it store highest elements first so 92 will come first then it will be 91 and the next input is 2 comma 93 our dictionary currently has only key for the student one now we have to create another key for student 2 and insert a score 93 into the priority queue for student 2 then we have 2 comma 97 the student 2 key is already created in the dictionary so we just have to insert 97 into the priority queue then we have one comma 60 so insert 60 for student 1 then we have 2 comma 77 for student 2 65 for student 1 65 is greater than 60 so now the Q will be 92 91 65 and 60. then we have 87 is also greater than 65 and 60 so it is sorted accordingly then we have 100 and the priority queue is sorted based on the descending order then we have 2 comma 100 will be inserted into the priority queue of student then 2 comma 76 for student now our final priority queue and dictionary will look like this taking the average of the first five scores of student one will give us 87 and taking the average for the second uh first five scores per second student will give us 88 since this is a priority queue which is nothing but the first in first out we'll get the top five by dqing so let's see how we can write this in the code this is the problem statement and let's code in C sharp so now what we need is a dictionary but look at this problem statement it says sort result by ID in increasing order so we not only want the scores of each student in descending order but also we want the IDS of student to be in increasing order ascending order so instead of using a dictionary there is another data structure called sorted dictionary which is similar to dictionary but the thing is the keys that we insert into this dictionary will be in the sorted order it will be ascending order by default so a dictionary will have integer as a key and will have a priority queue as the value and this priority queue will have integer elements and the priority will also be specified in integer so this is our priority queue and let me name this variable as dictionary then let's look through each of these items from the given item so for and I equals 0 I less than item start length I plus so we have to check if for example the first in the first iteration will get this array so we have to see if the first element in this array is present as a key in the dictionary or not so if this dot contains keep of items of I of 0 if it is already present we just have to push it to the queue so depth of items of I of 0 Dot and Cube items of I of 1 we have to put 91 into the key so that 91 will be available in items of I of 1. then we'll specify the priority also with the same number now if the dictionary doesn't contain the scheme what we have to do we have to insert this key and create a new priority queue for it so let me create a priority queue for this key items of I of 0 equals new priority Cube of n comma int now we have created a priority view for this item and then we have to push this item into the queue so I'll copy the same thing here you can simplify this code because this line of code is common but for better understanding I am just putting it like this now uh we have created a dictionary with the priority queue so our structure will be for every key we have an array of or a queue of scores now what is our uh what is expected result the result it should contain ID of the student and the average of the top five so to store the result let's create a list of integer arrays I'll name it as result of integer Harry then uh for each of the dictionary key so I'll say where uh student in date so student will now have student ID and the priority queue and for each of the student we have to calculate the sum so I'll create a variable sum assigned to 0 initially now we need only top five so I'll take a loop which will hydrate for five times in this Loop I'll simply add the elements from the queue so to access elements student Dot value dot DQ we have to take elements out of the queue finally once we get the sum we have to add the average so this uh result and the result should be in the form of an array with two elements so let's create an array with two elements the first element would be student dot key which gives us the ID then it's the average so sum by 5. so our logic is ready finally we have to return this result should be in the form of array as of now we have taken this in the form of list but the expected format is array so I'll simply convert result to array using two array the priority queue will sort items in ascending order by default but we want it in the descending order let me remove these comments so in order to make this priority queue sort our scores in the sending order we need a custom compiler so I'll create another class public class my comparer this comparator should be uh implementing I compiler of interface and this entire computer will have a method called the compact which takes two parameters I'll name them Ma a comma B the comparison is made between integers because all our scores are integers right so the parameters type would be in integers so int a and in B would be my parameters uh if a is greater than b we have to return minus one if the value of priority is less that element will be considered as the highest priority Elemental priority queue so if a is greater than b we'll return -1 what happens when I return -1 what happens when I return -1 what happens when I return minus 1 a is considered as the highest priority so it will move to the front of the queue if this is uh less than b if a is less than b this is of less priority so I'll simply return 1. if both are equal we'll simply return 0. let's make use of this comparent we just have to create an instance of this class here and we are done let me run this okay there is a typo here items or typo here as well items let me run again okay there is another typo here the queue the cases are satisfied let me submit this and the solution is accepted coming to time complexity we have n items and we are using priority queue to insert those items into the proper tube so the NQ and the DQ operations of priority queue will take the login times and for uh processing all these n items it would take n login times then we process through each item of the dictionary and also each item of the priority queue so this operation will take bigger of n times bigger of n plus bigger of n log n which would uh give us the overall time complexity of bigger of n log n coming to space complexity we are using this dictionary and priority queue to store n items so the space complexity is going to be Big O of N I hope the solution is clear if you like the content please like share and subscribe to interview pro thank you
|
High Five
|
divisor-game
|
Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` _and their **top five average**. Sort_ `result` _by_ `IDj` _in **increasing order**._
A student's **top five average** is calculated by taking the sum of their top five scores and dividing it by `5` using **integer division**.
**Example 1:**
**Input:** items = \[\[1,91\],\[1,92\],\[2,93\],\[2,97\],\[1,60\],\[2,77\],\[1,65\],\[1,87\],\[1,100\],\[2,100\],\[2,76\]\]
**Output:** \[\[1,87\],\[2,88\]\]
**Explanation:**
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
**Example 2:**
**Input:** items = \[\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\]\]
**Output:** \[\[1,100\],\[7,100\]\]
**Constraints:**
* `1 <= items.length <= 1000`
* `items[i].length == 2`
* `1 <= IDi <= 1000`
* `0 <= scorei <= 100`
* For each `IDi`, there will be **at least** five scores.
|
If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even.
|
Math,Dynamic Programming,Brainteaser,Game Theory
|
Easy
| null |
4 |
foreign welcome back to my channel and today we guys are going to solve a new lead code question that is median of tools or date arrays so guys just before starting to solve discussion please do subscribe to the channel hit the like button press the Bell icon button and book Marti playlist so that you can get the updates from the channel so guys let's read out the question to solve the question so the question C is given to sorted Aries number one and knocks to of size M and N effectively return the median of the tools auditories the overall runtime complexity should be o log M plus n now guys let's understand what is this whole problem means the problem is here is that we have to check out the median and if you guys do not have idea about what median is so median is the center value of the array if this is R then we can simply say it that give me the center value of that even and if it's even then we can just merge to array and one two three four so two and three uh we will be adding these two values and we will be dividing it by 2 so that we can get the median of the array so if it's odd then it can be simple but if it's even then we have to just divide these two centers value of the array so guys we will be first merging this to array to sort to solve this question out so let's start to quote this first of all I will be creating nums is equals to nums one plus nums two this will uh just merge these arrays so let's write simultaneously uh the values which we'll be getting in example number one we will be talking about so array would be one two one three two actually uh 132 will be getting after merge so in median we have to sort means it should be in an ascending order so we have to sort this array now sort which will give us uh one two and three this is the these are the values you will be getting after sorting now let's target the length of whole complete this array we have created now so we will be saying that land knocks which will be getting the uh length of the array so this will be giving the length of the uh list nums that is uh three if we three in example number one all right guys so now let's move further here and let's create a function let's create a loop actually in fact not a function has already been created we have to create a loop uh to create a loop we have to iterate to create Loop we have to create it for iteration so let's create a loop for I enrich length so we have to iterate it through this lens so we have created it create a low for I in range length now we have to check two things here first of all I have to check whether it's an odd value or if it's an even value to check for alt I can see that if length mod 2 is not equal to 0 if it's not equal to 0 then it's are odd it's an odd how uh let me explain to you that if I say that this is this means that this created and odd condition now which will give us the code AS now if we just uh see here uh guys that this is the array we will be getting one two three this whole array now let's move further here and see that this is the condition we are talking about if it's odd then example number one is the perfect suitable example we can talk about here because its length is odd one two three is an odd number so if its length is odd we can see that return me return nums length floor division two because the center value we will be requiring uh you can see that we need a sector value of this okay to require a center value we can say that length is 3 mod sorry three floor division will give us the center value that is at index 1. so now let's move further and as the second condition would all uh we already know that it's if it's not odd then it would be even so for even we will be returning nums now uh nums actually I will be creating first a parenthesis and I will divide it by two and now here I will write something nums length division two minus one plus let's put some extra spaces so that the code is clear uh now nums length mod 2 sorry floor division two minus 1 plus nums length to uh so we will be adding these two values so let's write this condition uh this array here let's say we have example number two as one to three and four so this is the array we will be dealing with so here is two values you will be dealing so this one this two would be just this one and three would come under this and if that's the case then just divide it by 2. okay right we have to divide it by 2 because we have to get the center value so it would be between 3 and 2 so it would be somewhat 2.5 so that's all we have to do here now 2.5 so that's all we have to do here now 2.5 so that's all we have to do here now let's run it and check for an answer so see it has been running successfully so if you guys have any doubt ask me in the comment section thank you guys for watching this video and see you next time
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
141 |
Jhal Hello Bhai Students To A Question Only Interact Directly In The Cycle Protection Basically To Identify Weather On Cycle Allu Is Presented In The Recent Pst Flash Lights Of Ban Gaye Mail Address Mintu Return 000 Se Cycle Internships Others Neetu Aka Mintu Later Billion Rising Separate Question Understand Giver Is The Head Of List Date Amazon Like It Is The First Model Listed In The Next Day That With Her Internship For This You Should Know It Index Note 3 Snacks Point To That Was Not Near Parental Notification Give The Basically It's Italian Budget Which Indicators What is the connected to Delhi - 110 No What is the connected to Delhi - 110 No What is the The Been Transferred To Right Under 16 Travels Gourmet Indicators A Has That Was Going To Happen When Every Cycle OK Soviet Examples For Example Tuesday Recycle Switch Off To The Self 2010 - School And Back To Wear Coming Self 2010 - School And Back To Wear Coming Self 2010 - School And Back To Wear Coming Back To From School 100 Cycles Similarly They Could See Them Example To Be Recited For Example Arrangement 99 999 9999 That Aunty Goku VS We Live With No You Same To You That Vinod Settings One By One Intercept And They Want To Take Off But Not Appointed President Tight Slap To Understand This Usage Examples For Main Tujh Se Exam Par Baad Hum Bhagwan Das Language Should Be Doing This Website And Display Content Not Important To Note That Will Always Put Not Develop Into The Links From Ubuntu Note Key Value Alarm 200 Grams White Select Lift The Video then subscribe to the Page if you liked The Video then subscribe to the two Already As A Is The Means Itihasa Hard Cycle Aur Skin Problem Salary For Good Health Not Want To Go To Ok Khud Pitta Adi Subscribe It's a good example sentences with note clearly ok but didn't want to go to two to three do subscribe 999 9999 ko one needle just VPN counter anal ku ka agenda the list and not final repeated note key Sugandhi inayat ki nazar that note side and off mountain mode switch fuss were positive present and set in that case answer subscribe that a question and till it coding part important point note on front foot servi robbed 2.1 not inside set an order values for Looter Ke Se Mode Turn Over All They Are robbed 2.1 not inside set an order values for Looter Ke Se Mode Turn Over All They Are robbed 2.1 not inside set an order values for Looter Ke Se Mode Turn Over All They Are Not in This World To Others Like This Or Video Not Printhead To Loot In Race Set In WhatsApp To Visit In Sports Day To Be Set Right In Front Hand Sidewise With You Find The Satanic Verses Noun Pt. 1 That And Figures From Head To The Next Month In Every Situation Okay Only No Like Subscribe And Means Definition Of This In Unwanted Sample Test Case And See What Happens Ki Saugandh Accepted Test Summit On That Her Nature Suspect Tips Sexual Harassment Complexity While Were That Should b c the interested tha apne nails am in terms of time complexity traversing between not want to no deposit ready time complexity of any story and want * * * find the total of notes2 want * * * find the total of notes2 want * * * find the total of notes2 is assigned to next day special squad has prepared the equation specially for using and safe Right away from this question we shifted to all the best known for it does not belong to the evening through evening through evening through torch light show more cold to variation in vicious scored in the soil of today thank you and stay connected for devotion list a
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
211 |
alright so today's second question is 211 add and search word it's a data structure design question we need to design a data structure that is efficiently supports to operations add a word and search word the search word can search for that row or you can search for a regular expression and the only wild card that we are supporting that this dot up means that it can match any one letter so example we have we insert bad dad mad we remember that we have seen this three words so then we ask you to search for WordPad it doesn't exist and we can tell that based on just based on the read first letter we don't have a word that starts with P so it's false and bad which is first a word we return true then we do this pattern search for dot a D either one of this three matches that pattern so we return true and in the real and we have B dot so the bad much is that pattern we return true so the question is asking us to come up with a structure that can support these two things effectively so this in this knit comes naturally to the search fee kind of data structure and for this particular once the tried a perfect Street data structure if you don't know that you can still probably come up with a good solution if the interviewer hinting you that to you my you know sort of a constructor tree to the base to do this problem so just think about how would you use a tree to store the words that being inserted one at a time right you have some kind of lute note and for the first award it's bi d you just splits out off branch was the first uh character in there and then the children to that particular node will be just a node with letter A in there and the only child it has no base value D and you can also because it's we are reaching the end of the word we use a kind of a boolean flag to a flag that to indicate that this is the end of word so if we need to search for the word bad we literally just go through the pass for this word within the surgery once we exhausted the characters in the input search of string and we find that we do have a flag indicating it's an actual end of a word that we know we return true so if we have one cat we can just search for the all the possible children's on that particular level corresponding to that level let's say that we also have di D here this wildcard it's just that we will put this two notes on the stack or acute depends on whether you want to do DFS on BFS and just keep tracking whether either one of the paths if we can successfully reach the end and get a terminal flag then we just return true so you can see that every you know we basically translate the you know horizontal you can see word into a vertical pass into the tree and we have a one position to one level kind of a correspondence between the carpet allocation in the word and the levels in the tree and so this is the perfect tree or idea structure and even you don't know that you might still come up with this solution in the end so just a little bit worried about the little bit analysis about the time and space complexity so for insert it sort of an imposed time and space let's let M be the length of the word so we are looking at the time and space complexity for every single the single operation of this to a single time for this operation and every if it's a search the perfect time the most the simple case is a result wildcat that would be linear in time and because we just literally just works through one pass and the space is going to be at one because we know where we come from and where we go to it's a it's determined there is only one way if we have a fixed input here note with no locality well the cop if we have well cut the worst scenario is da right that would be so for each of the level we need to pretty much fly all the possible nodes and the worst case is just the total number of words total I will nodes in the tree in data structure and the space it's roughly depends on whether you do DFS or PFS I guess so but the Jared's gonna be if the worst case is gonna be a linear somehow linear with respect to the total number of nodes in the data structure that's what we that's the worst case and we don't want that right it's time side the notation looks a strange that's pretty much what this is so little bit details about this individual node here so for the for every given node you will have a we can pre-allocate like a 26 locations here pre-allocate like a 26 locations here pre-allocate like a 26 locations here for every node because it has 26 possible Fulop character after you know after that location we can pre allocate that or we can dynamically using a hash map right so the hash map might save a little bit space but the continuing is actually good because if we want to search for the dot we can just search for a dot with the because the memory for that 26 is actually continuous there might be some benefits in that I'm not entirely sure so don't quote me on that yeah it was not we just gonna try to code this question up with tried enough structure so we need a node that node object I know that we can just use dictionaries but you know object a class helps us to organize things a little bit better and it's actually quite a simple one every tri node has only two things the children's and a flap so this is a definition of a node within this tree kind of data structure and when we initializing this data structure we're essentially doing is just grabbing a root node single root node here and then we cut this outward operation which is iterate over the characters in the input word and populating new node if necessary and also flag the array last a node in the end yeah so this is because it's a default dictionary if the character at any given location is not existed in the data structure you were just a child construct a new node with that value so that's basically constructing a path through the in the data structure to represent the word and also flag in the end that's a terminal location for forgiving those that we know and they search who be they search which is B the traversal service data structure let's just go down recursive implementation of this search let's call it find Equis and we'll have we always start with a node and end up with a note so any given time that doing this process what we need to know is the current node and the you know the position of the word the character position of the word that we are searching bad so there are going to be two inputs to this function which is the ice location in a word and the current note that we are operating on if we reach the end of the word then we just return whether the node has a terminal flag or not otherwise we will just grab the character the eyes character in the word in the input world and the based on where whether it's a wild card or it's an actual letter this is going to be slightly different if it's a you know wild cat then we search all the possible 26 possibilities or actually we can just search by the children's the keys in the children's here and for every possible key possible Obama catch wild cat matching and we just recursively do this find operation on the next location so the call is going to be the this is grabbing the child node and this is a increment the location in the process of the searching if it's a successful we just return true meaning that if we find anywhere we can also always return true if the other possibility end up fruitless and this one cat matching is going to result to failure in the end if it's not a wildcat then there are two possibilities whether it's no character here yeah well the P is in the child or not and if in Union so based on this we can just return false otherwise it's similar to this situation here it will be char and plus one so the search is just gonna call this method was the root node and the zeros location in a word so yeah that's yep so what kind of search is this whenever we match a position we if it's a dot and then we try all the possibilities and this function is going to call yourself so it's a DFS try to go to the end of a path as pasa before it tries at the other alternatives so it's a DFS search so if I have time or the interview requires I can change the code into a iterative approach implementation so but I guess the recursive one can show the logic Apatow I sure so let me quickly check if Y if I have arrow seeing here this is a definition of node it's the children's are the key value pairs with the key be the ice locations character and de varios be the nodes and each node has a terminal flag so in the custard you initialize a constructor we just create a rule node empty rule node we inserting a node inserting a word we add that we add a node for each character in the data structure and in the end we flagged our very last node to be true okay and the search operation yet basically trying to traverse us through the data structure if it's a known character if it's a character and not the one that we have in that particular level then we fail otherwise we've try to proceed to the next level if it's a wild card we try all the possibilities so it looks good to me I try to submit this okay we have an arrow oh okay so it said it snowed here let me change this all to note so it's more consistent that's why again yeah this time that works all right so that's the question for today
|
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
|
946 |
hey everybody this is larry this is day 16 of the march leeco daily challenge hit the like button hit the subscribe button drum and discord and everything that you want i suppose uh and i yeah well i'm a little bit off today anyway today's problem is validate stack sequences okay so given push and pop you trip distinct value return true this could be a sequence okay um let's think about how we want to do this right well i mean obviously pop can only be done if there um there was a push so i think we just have to be very greedy about it because is that true yeah i mean because um because there are really only two scenarios if you want to uh for this one right meaning that for example if you want to pop five in this case um like is there a case where we want to save four to pop later well if not really four is the first ring to be pop so i think that should be good here to just do it in a greedy way which is that keep pushing and then if you have something that matches the top you pop as much as you can um yeah okay so let's do that so let's say we have a stack and then now you have a sequence of um yeah so let's just say and uh nsu go to it's the same length right yep i just want to double check um and then now it's just for item in pushed then we uh we go stack dot append item right and then while um let's just say we have some index for pop well index is less than length of pop and popped of index is to go to stack negative one the top uh which i guess we have to also means that we have to check that this is greater than zero um yeah so while this is the case then index increment by one um yeah and then at the end we just have to check if index is equal to length and i guess this is just n so yes this doesn't change uh so then we just have to return where this is you go to n at the right and i think that should be good i don't know if i'm really articulate on this one four five one two three okay four pop and then five it's good and then we next we put in the five uh five and then oh i didn't actually pop that's why whoops i was like huh i thought this would be good to be honest but it's very sloppy uh just woke up from a nap and i feel a little sluggish but that's okay that's an excuse that looks good uh i think we should be good let's give this a minute oh wow previously i did two wrong answers but i have okay yes beat you past larry uh from a year ago maybe i was very fast but yeah um so what is the complexity here right i think this is actually a good one to talk about complexity a little bit um i think it's very common to you know see these two for loops i mean i know that inner was a while loop but though in certain languages you could certainly write in a for loop you could see these two for loops and think well there's two follow-ups two law loops um follow-ups two law loops um follow-ups two law loops um this is n square right but if you think about it well each item in pop will only be looked at or each item and probably only be popped once right so that means that each item on average will only get looked at twice but at most once oh sorry on average twice but at least once for popping um so that means that this is going to be linear time and this is going to be a linear time algorithm because each number can only be popped once and if you're on the top of the stack you can only get looked at n times right at most uh and get you know incorrect so or like and not matching right so yeah so this is gonna be linear time and in terms of spaced uh space it's going to be linear space just because you know you have a stack adverse it's going to you're going to push everything in there and that's going to be linear time uh cool i think that's all i have for this one though i do want to see what past larry did uh for x and push oh huh i think i in the past it seems like i made it more complicated than what the wow more complicated than it needed to be um and then the final thing is what we have now anyway essentially so that's weird maybe i'll watch i'll see what i did last time then maybe but yeah but this is a greedy album so it is a little bit tricky sometimes to see it um but another phrasing is just like an invariant type problem where well you can't um like if the pop order is uh afterwards that means that you know you keep pushing until you see this element because that's just by definition you can't pop any everything else before so you pop this as soon as you can um to unblock anything else i think maybe that's the way i would look at it uh it's a cute problem i don't remember it but apparently i did better than last time which is you know uh oh it's good to hear uh you don't want to be worse than last time but anyway um that's all i have with this one let me know what you think uh yeah stay good stay healthy to good mental health take care of yourself and i'll see you later bye
|
Validate Stack Sequences
|
smallest-range-ii
|
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._
**Example 1:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\]
**Output:** true
**Explanation:** We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
**Example 2:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\]
**Output:** false
**Explanation:** 1 cannot be popped before 2.
**Constraints:**
* `1 <= pushed.length <= 1000`
* `0 <= pushed[i] <= 1000`
* All the elements of `pushed` are **unique**.
* `popped.length == pushed.length`
* `popped` is a permutation of `pushed`.
| null |
Array,Math,Greedy,Sorting
|
Medium
| null |
528 |
hi everyone it's sorin today we have a problem when we are given an array of integers which represents weight so for example in this case it's a one and a three for the zero index and the first index and we need to implement the function pick index which randomly picks an index from our array and returns it so but the most important part of this question is that the probability of picking an index we are not just randomly but the probability of picking the index is the weight divided by the sum of the all weights so for example let's take this example right we have two values one and three so the probability of picking the first index is 0.25 because 1 divided by Sum 1 / 1 + is 0.25 because 1 divided by Sum 1 / 1 + is 0.25 because 1 divided by Sum 1 / 1 + 3 which is 4 so it's 0.25 and the 3 which is 4 so it's 0.25 and the 3 which is 4 so it's 0.25 and the probability of picking index 1 3 right is 3 / 4 1 + 4 which is 0 .75 so what's is 3 / 4 1 + 4 which is 0 .75 so what's is 3 / 4 1 + 4 which is 0 .75 so what's that mean it means that when if we called our pick index function right this function on average so if we call it let's say four times it should if we call four times once it should return our zero index because probability of 0.75 and three times it should return 0.75 and three times it should return 0.75 and three times it should return our first index because the probability of it 75 okay let's take one more example and work on it let's say that we have 10 here we have two and we have three and the indexes are zero index first index and the second index the first idea comes to mind is just when we are calling this method we should randomly pick the index and return it so that would be wrong because if we are doing that it means that the chances of returning 10 and the two and three are equal but they should depend on the weight so dep our probability of returning zero index should be 10 divided by 15 because the sum of the all elements are 15 the probability of returning second element is 2 divided by 15 and the probability of returning third element 3 divided by 15 so what's that mean it means that if we are calling this function 15 times 10 time it should return a zero index and uh twice it should return us uh first index and three times it should return us second index so on average right on average this should be our breakdown so how we are going to solve this problem the way we are going to do that we are going to use here prefix sum so we are going to go over our array and add the elements so add the previous element to the current element so for example the first one would be 10 in the prefix sum the second is 12 and the last one is 12 + 3 it gives us 15 so last one is 12 + 3 it gives us 15 so last one is 12 + 3 it gives us 15 so when we are choosing an element so we are not choosing between zero and two we are going to choose between 0o and we are going to choose in our case between zero and 15 so we are going to choose between 0 and 15 because in this case let's say that we are choosing seven right we are choosing seven if we are choosing seven it means that we are going to return zero index what about let's say we are choosing nine again we are returning zero index let's say we are choosing randomly 13 right in this case we are going to return first index and uh how about uh let's say that the 13 we are going to for the 13 we are going to return 15 Index right 15 so which means at the second index let's say 11 right for the 11 we are going to return first index so it means that the from 0 to 10 it is we are returning Z index from 11 to 12 we are returning first index and from 13 to 15 we are returning first index we are second index first and zero index that would be correct because in that case it would depend on the weight right it would depend on the weight of our index so that is the first part the second part is let's say that we have much larger array and uh let's say that we have in how we are going to do the search in that case so our first step is we are randomly picking from 0 to 15 we are picking our Target number right and after picking that we need to find in our prefix some array we need to find correct index so for example let's say that the we it's nine so we should return our zero Index right if it's 11 we should return our first index and so on so in order to do that we are not going to do the linear search what we are going to do a binary search in our uh in our prefix sum array first thing that we do here we are initializing our prefix sum array of integer which is the size of our weight array of integer and we are setting for the first value we are setting the value of the weight zero and for the rest of that we are populating our prefix sum and when we are calling our pick index method so what we do first we are choosing a random number between our zero and our last element of our prefix sum let's say that in our um in our case from zero and the in our if we consider our previous example right from 10 to and three so between 0o and 15 so we are choosing our Target number and then we are doing our binary search we are initializing our left pointer which is zero our right pointer which is the last element last index of our prefix sum and we are doing a binary search so we are selecting a mid element if our value in the prefix submit if it's less than our Target so we are searching on the right side of the array for our value if it's less than then we are searching on the left side so we are moving our right pointer and at the end we are just returning an index um so what's the time and space complexity time complexity we can we should calculate the time complexity of these both of these cases for the um for our Constructor the time complexity would be of and because we are going over our array only once and for the peak index the time complexity because of the binary search it's a log of N and the space complex taking um is determined by the prefix sum which is of n okay um hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
|
Random Pick with Weight
|
swapping-nodes-in-a-linked-list
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Linked List,Two Pointers
|
Medium
|
19,24,25
|
455 |
he would so guys Nick white hear you talking coding stuff on Twitch in YouTube check the description for all my information and I do the leak of premium problems on my patreon and you can join my discord reach out to me try and get back to everyone this problem is called assigned cookies it's a pretty easy problem assume you are an awesome parent you're awesome parent who wants to give your children some cookies alright but you should give each child at most one cookie okay each child i has a greed factor G of AI which is the minimum size of a cookie that the child will be content with and each cookie J has a size of s of J where if s of J is greater than or equal to G of 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 I'll put the maximum over okay what this means is we're given an array these are the greed factors and these are the you know sizes of the cookies so we have a bunch of cookies we have an array of cookies and then we have an array of children and the children won't be happy like they're gonna like cry or something like you know get mad or throw a temper tantrum or something if they don't get at least whatever the greed factor is so we have three children this is the array of children in this case this is the array of children so the sizes don't have to be like certain size or anything these also are not guaranteed to be sorted I'm pretty sure and yes so we could see what is the minimum um what is the maximum a number of content children we can get with the cookie sizes we have so you know one show one person is gonna be happy with one cookie so we could give one you know cookie of size one to this person and they're gonna be happy we can't really make these little people happy I mean we could combine both these ones and then make this kid happy because one plus one is two you know you give them two cookies each size one he's happy with that but it's still just one show Durin's we might as well it's give it to this kid so it doesn't matter what we do but the max is one in this case we have one two three cookies and we have two children and if we look we can give the first kid this cookie because he wants that exact size he'll be happy with it and we can give the second kid this cookie you know he'll be happy with that and then the third kid you know there is no third kid so we just stop with two because that's the maximum our children so how do we solve this problem I mean there's a few ways to solve it they're all pretty lame honestly if we loop through so I guess here's the worst way brute forces okay look through look at the sizes so you're looping through the son the size the greed factors and say okay this kid needs a cookie size one then you loop through this whole array and try and find a cookie size one and then you repeat that process for each grade factor or whatever so that's you know pretty crap solution but I think the best solution is to make sure the arrays are sorted at the beginning and if the arrays are sorted which they're not guaranteed to be sorted in this problem it would say that they're sorted then we can just loop through with two pointers to a two pointer approach loop through each the greed factors and the sizes at the same time and then just if the greed factor requires a bigger size just increment the pointer for the cookie sizes until you find a cookie big enough to give to the greed factor because you know it'll be the smallest one so let's just start doing it yeah just sort both the arrays so they sort the Crede factors you sort the sizes of the cookies set up your pointers so we'll give a pointer is equal to zero B pointer is equal to zero and then we'll do a well a pointer is gonna be looping through the children in the greed factors so while it's less than G dot length and B pointer is less than s style and because that's the one that's going to be looking through the cookies if the greed factor at the current index so this is the smallest if we're sorting them so we're going at the beginning so the smallest possible greed factors are at the beginning so that's the best way to optimize the maximum kids because we want the smallest careered factors cuz then our cookie sizes you know we can that's the best way to optimize it is the small you don't want to go from the back if we started with three you know we're screwed we can't even give you know in this case if it was just a three you know we couldn't even satisfy three with what we have so we want to start at the beginning of a sorted array so we have the smallest curried factors this problem is funny because it like deals with greed and it's like a greedy algorithm kind of approach where you're kind of going with the best possible scenario at the each current step so okay if the current greed is less than this current size that we're at so size of B pointer well then we're good like we have the correct size of a cookie to satisfy this kid so we can just inca runs both pointers and yeah we're good we can just keep moving through the iraq and if it is not if we need a bigger cookie we'll just increment the b pointer because it's sorted so incrementing the B pointer will get us to a bigger cookie until we hit this condition and when we get to the end by the end of this we will a pointer will increment to give us the maximum number of children we can satisfy so you just return a pointer and it's an N log n approach because of course sorting is a n log n but then just a linear loop after that so that doesn't affect the runtime so it's a pretty good solution it's just you know one of those things sometimes you have a problem and it's just like oh I should just sort here like you just got a no one to sort and this is a perfect scenario of knowing when to sort because you want the smallest agreed factors and then this is just an easy two pointer proach let me know if you guys have any questions I think it's pretty straightforward this if you want to know how this a pointer is what we return it's incrementing the maximum size because like I said the smallest grade factors at the beginning and we're looping through and if we satisfy a greed factor we increment a pointer only if we satisfy it the B pointer you know the world going through all the cookies they're doing all the work but satisfying the children is where we you know that's once we have one satisfied kid it's gonna increment this so whenever we have a satisfied kid that's like adding one it's not only incrementing the in the array but it's also giving us the number of children that are satisfied with their cookies so that's pretty much it let me know we just think a pretty decent problem but yeah I don't know I mean haven't been pote I didn't post today that much I wanted to make a video because you know I was editing a lot today I'm at posting one of those like longer edited videos trying to get good at those too so well let me know what you guys think and that's pretty much it see you in the next one
|
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 |
883 |
cool 883 projection area of 3d shapes and an N by n grid we place one by one keeps that access a line on the with two XY and z axes each by UV u goes to quit I J represents a tower of three cubes placed on top quits hours i J now we read the projection of these cubes onto the XY Y Z and said explains we turned the total area or three projections okay seems maybe okay there's some like well it's okay because you could simulate it I think because it's just 50 right so I can take your job it's like actually a lot of things related to points in a plane and like stuff like this well see just a lot of stuff about Cal Expo and the other thing like when Doyle diagram would Delaney I don't know if I'm saying them and Delaney triangulations and stuff like this but a lot of fun class a lot of it and the thing with that class is that you learn a lot about different ways of doing things because they're like 808 good algorithms to do like comics homes and they all have like a little bit different way of thinking about it and that's why it's kind of cool actually but uh anyway okay yeah if we're here I think you could just project it everything it's less than 50 wait so you can actually just manually yeah you just manually kind of want a phone look through it okay let's to expires using 0 XY Y Z that X is y 0 and then W my areas for those things and then now maybe I could even get smaller and a little split this one is less than 50 maybe I could do if I could be smaller about it so this is no okay actually I think I'm just going to do something like you just take the max of in a way based on the axis all right what are these three things oh I guess this is what the top one is easy to top on you is just a number of non-zeros top fun inside okay so non-zeros top fun inside okay so non-zeros top fun inside okay so the top one is easy no that's yeah I think this is just a case of cooking it down a little bit like case by case a little bit I don't know Java helped here because I mean because this is like any this could right now it could be a dying language been a Shu chok I did not take anything of Shu Chuck's know I do probably not I took I've come to show geometry with someone call professor I think Joe Mitchell I want to say something Mitchell it's been a it's been 15 years let me google him yeah so yeah way a good way kind made very patient and then for the other ones actually for the other ones I was going to say something like you can maybe do the like store in a way to hide mapping actually just do it and that's just the max of the heights in the X element or the Y element okay I went to a Stony Brook in New York on Long Island it's a very small school like I don't know if it's more anymore I think but it's not only well-known schooner maybe that's only well-known schooner maybe that's only well-known schooner maybe that's what I meant to say okay yeah it says but I think in Java is this would be one and then we go so go with the other way yeah I'll just play another loop you can find putting the same dope actually they really well I mean was way good when I was there I mean not to be like waiting his Pete okay so I could do this we have without it was good in a sense that they were dead I mean I was there as an undergrad but they had a good grad program so I started taking classes from before from it so II knew I took a lot of classes it was fun well yeah I don't know if it's oh you're going to slowly Oh midnight it's I'm I didn't scroll up so you're still in high school well congrats and good luck in Stony book yeah I enjoy my time there it's a little bit of nowhere now unfortunately but uh but I depends on where you're coming from if you're like you know like you can it's a quick hop to New York City is what I mean to say in the weekend so it's a little bit quiet but it's alright this is right YUM oh cool Congrats yeah no I like Stony Brook yeah I remember my I'm just flashing back was it the wife pond and people swimming in it well people tell you not to swim in but people swim in a smelly yeah a long time ago unfortunately no yeah Oh or the other job once it's faster okay oh really huh they used to I don't know if they still do but I used to pump water into the pond when it gets low so it is fresh for their kind of anyway ah cool so yeah so this is a I think yeah so this is an easy problem or like it's just as easy but no tricky I don't know why I had so many downloads so it's not that kind I think the I think some of is that like given though I've been talking about this problem so they allowed me to yeah looking into problems so that it allowed me to kind of really think about what I want to put I think I didn't really articulate this very well to be honest I think well first of all yeah like he 86ed I had to look at to see what the inputs were but this is the vertical yeah to keeps on top so you basically can the top view which is why this works I mean I think this is obvious hopefully course yeah that's just a number of spaces occupied from the top and in here from the side wheel I look at each like form of certain position I just take you know you only see what's sticking out the most so you take the max of that and then just sum it up and then that's one of your faces and then the other face is the same way but you do your follow up the other way right so that so you look at from the other direction that's a little hand wave even that's the essential idea but you look at it in terms of a matrix well okay these are bad examples oh I didn't predict not bad inputs just like not inputs that it that's mean Illustrated but basically my idea is that ups like giving it away like this one add some numbers but yeah but from the side we're going from this direction you only go see the max of that row in this case so that's gonna be five this is gonna be - this is gonna be doing so is gonna be - this is gonna be doing so is gonna be - this is gonna be doing so that's the logic and the same thing from there columns so example this is - you can only see the max and so is - you can only see the max and so is - you can only see the max and so this is maybe Bank said well so yeah so then you just kind of sum up all these numbers which is what the problem asks is you and that's how you sound is easy uh yeah I mean I don't know if this is it I guess is easy enough to gain and give you a question I don't know I mean it's not too hard and it's just like a cover for loops you could pry doing one folder big you would take okay if your little clever of you know safe a new trade space for time that way but it's only an additional pass and obviously this is o of n times n ok but yeah obviously of n square because you only go for the loop the entire way three times I mean you could technically combine them a little bit but it's not a big deal and obviously constant space so it's space optimal and time optimal you could do and fewer paths if you want bread but then you trade some space for it I think notice is there I mean there's a uz problem so I generate say most easy problems and this is really hard yeah and I'll point those out you know you could assume it's fair game just goes like it so easy and you could do in three four loops do you to be set up easy for loops then like you know it's about saying and this one I think is it good like you know you can get far enough you just have to actually like sit down focus I think is one of those well but yeah
|
Projection Area of 3D Shapes
|
car-fleet
|
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes.
Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`.
We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes.
A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side.
Return _the total area of all three projections_.
**Example 1:**
**Input:** grid = \[\[1,2\],\[3,4\]\]
**Output:** 17
**Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane.
**Example 2:**
**Input:** grid = \[\[2\]\]
**Output:** 5
**Example 3:**
**Input:** grid = \[\[1,0\],\[0,2\]\]
**Output:** 8
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] <= 50`
| null |
Array,Stack,Sorting,Monotonic Stack
|
Medium
|
1902,2317
|
1,595 |
hey what's up guys this is sean here so uh so today let's take a look at the last problem of this week's weekly contest number 1595 minimum cost to connect two groups of points i think this is a good hard problem you know i struggled a little bit yeah i struggled on this so basically you're given like two group of points where the first group has size one point on the size and the second group has size two points i mean the size one the group size of size one is greater equal greater than the size two but i think this is kind of uh not that relevant but okay let's just put it there and then you're given like uh a 2d cos 2d cost list here which the cost i j means that to connect the ice node ice point from the first group and the j's point from second group what's the cost of that okay and then it asks you right to connect basically our end goal is to connect any for any group from each side of the group it has to at least connect to one of the other groups okay so which means like let's say if you connect one and uh the first point on the second first group and the second i know first point on the second group then both of the both of these two points i mean are connected okay and it asks you to need to find out the minimum cost uh to connect the connect groups which means to connect all the points of each to the other group okay so for example the first one right the first one we have uh basically we have these four options here right and then the best of the best strategy which is basically to connect one to a and two to b okay so and who's and the total cost will be 17 and example two here right so we have like many ways of connecting that right it's gonna be a three times three which was going to be a what uh 27 possibilities right and then among all those 12 20 27 possibilities we have we use this one so the best way of connecting is this one okay cool so uh i mean this is like kind of like you can think of this one as a dp or like um or like a dfs right basically the dp or the top down dp is actually is essentially a top down dfs okay and this problem is exactly that one of those problems but uh but to be able to use dp okay you need to uh have like this kind of dp status right the dp here so you need to maintain like two uh the state of the state uh the state of the uh the status of current state so in this case the state of the current status is what is the uh is how many basically is the connected points are from group one plus the connected points from group two okay basically at this point i mean what are the connected points on the first group and what are the connected points on the second group okay those are the i mean the stat the 2d the two status of the current dp state here okay but the difficulty for this problem is that i mean it's a list basically right the first group and second group there they're all a list let's say we have a the first group is this we have a 0 1 2 3 4. that's the first group and the second group is this like 0 1 2 3. okay we need to find like a way of basically to efficiently store this current state of the connected status of all the points here on those two groups we cannot use set or list why is that because you know uh at least in python right at least in python if for the top down you wanna if you wanna like store a use store that key uh basically you cannot put either a set or list into a hash table because it's not hashable it has to be a primitive type like the integer or a top or something like that so that's the basically the a little bit difficulty for this problem and to be able to do that you know uh if you scroll down here you check the size okay you see the size is 12. so what does it tell you tells you that it's within the two to the point of 30 32 okay that's the length of each of the group here so which means we can use a bit mask okay we can use a bit mask to tell us which one i mean uh if this point is connected or not so what does it mean it means that let's say we have this five points here right so which means at the beginning right everything is zero three four five okay so it means that if the first uh if the first point is connected then we just change this one to one okay and then if the third one is connected we also change this one to one okay basically we just use a bit mask so to compress a list into an integer and this will basically we can use that one to uh to track to check that okay so that's how we track the uh the connected points and now what's the what's our strategy okay so what's our strategy of connecting the points here i mean a brutal force wave is what we can try um obviously we have to from group one right we have to try to connect group uh each point to all the points on in group two basically we need to try all the possibilities okay which means for example this one for one uh for like uh for point one from group one we have to try to connect to a b and c okay once this is done uh once we have tried all the possible ways there that we need to move to the uh to the point two here for two we also need to try both a b and c first three also three two oh we also need to try both a b and c and so for the first i mean this is the second basically our first uh status of the dp here is the status of the uh of the first group of first connected group i mean since we are trying all the possible way scenarios for group from group one here i mean we can simply use the index to track the status basically the index eyes means here from zero to i we have connected all the points okay because once we finish connecting the current point we're gonna move the eye going forward to from i to i plus one so that i mean a single integer i here can represent the state of the first group which means it's already been from zero to i all the points have been uh connected and from i onward not nothing has been connected okay so that's the first the group and then for in terms of the second group right for the second room we don't know because we're trying all the possible ways right because one can connect to either a b c or two same thing that's why for the second group here we need to use a bitmask okay basically every time when we decide to connect uh the current i to either a b and c we're gonna set the bitmask of the second group accordingly so that we the speed how basically this is how the beast mask is being used here and once the uh no once the i reached the end of the first group okay it means that okay so everything from the first group has been already connected to the second group now what's next and we just need to check if there's anything that in the second group that has not been connected which means if anything from the second group if uh has like the bit mask equals to zero okay so for those like for those points we don't have to try all the possible what we don't need to try all the possible connections with one two and three here anymore right because we know because we don't care about the group one at this moment because all the points at group one they have already been connected so all we need to care is it is our ourselves basically okay so basically at this moment the best strategy will be uh let's say for example if the after i reaching the uh the last position of the group one let's say if b is not connected then all we need to do is that we just need to find what's the minimum cost uh fro from b to connect to any point in the group a right and we just need to use the that one we just need to use the uh that the minimum cost to just to connect the b to the first group and to do that we just need to do a pre-process pre-process pre-process and we're going to do a pre-process and we're going to do a pre-process and we're going to do a pre-process based on the cost so we're going to have like a minimum cost two basically two means for the group two th this uh this here it stores all the uh the minimum cost for each of the points in group two that uh connect to the group a okay cool yeah i think that's that all right uh all right okay let's try to call these things up here okay so um so first uh we need a size one here right size one equals the length of the cost and size two equals the length cost zero okay and then like i said uh we need to pre-process the minimum cost we need to pre-process the minimum cost we need to pre-process the minimum cost uh to connect uh each point from group two to group a okay so that i'm for to be able to do that i'm gonna do a cos2 here equals to a uh system max size and the size will be size two okay and then for j in range size 2 for i in range size one okay basically i'm doing an acid for loop here so for each of the group for each of the point in group two here i'm going to loop through all the points uh from group one i'm go i just need to i'm getting the minimum amount of among those okay so here's going to be a j here right cos2 uh j and the current cost i and j okay yeah so that's the pre-process and then yeah so that's the pre-process and then yeah so that's the pre-process and then uh like i said we're gonna define like the dp here okay like the dp uh dp the first one is the i because that's in that second one is the mask okay and here in the end we simply return the dp uh 0 and n0 okay so 0 means at the beginning oth other points have the bit value at zero okay so i mean since it's a top down i'm gonna use like uh this like the cache helper cache setup here in the python so this thing it means that i mean it will automatically returns the values whenever the whenever it sees the same input the same i and mask so basically this one is easy equivalent to like manually maintain like a memory the memorization hash table okay yeah basically this is just like a short card of doing after eliminating a few lines of code here you can of course manually maintain a memory hashtag hashtables i mean it's fine i'm just uh taking a shortcut here so and um like i said since we then we're gonna have like two scenarios here right the first one is the i is equal is smaller than the side size one okay so this one this thing this here means that i mean we're still uh connecting we're still in the process of connecting the points from group one okay then the answer is okay yeah sorry so like i said the answer is uh max size okay uh yeah and this one is minimum of the uh the current answer plus what plus the uh so we need we have connected the current one sorry here so to be able to connect to the current ice point which we need to loop through all the points in uh in the group two here okay size two and yeah here it means that at this moment right we are connecting the j's point from group two with the ice point in group one okay and the i plus one means that we have already connected the current ice point but how about the beat mask here so for the beat mask the way we're doing the mask is we are marking the jace point the j uh position in the beat mask to one okay so here it's going to be how do we mark that we just do a or with the mask and the value of the cur the js is to mark the json we have to basically move uh one to the by j position right so here i mean let's say we have zero here i mean in order to mark uh to mark this position two to one how do we do it we need to uh we need to get the values of zero one zero okay and then we do our so how do we get the uh the value of zero one zero we just need to mark uh move this the j by two here so basically the this one will become this one okay we do our work because we don't want to affect all the other uh bit values of the in the original mask which means only the value in one here will become one here okay yeah and it's also possible that i mean the mask though here it's already it's really one it's already been marked to be one but it doesn't really matter so one or a dual uh a bit or is also one so we don't care we just try to set this one to one cool and then don't forget to add the current cost okay so the cost is the ing okay so that's when we uh try to set up connect the current ice point okay else what is the house else means that uh it's not actually out so this is like the normal case basically the uh the house case is just like the base case okay so the base so what's the uh what's going to be the ending point the base case how can we how when should we stop this dp right i mean for a dp you only you always need like a base case so the base case is we have connected to all the uh to all the points from group one so the base case is this base case is when if i is equals to the size one okay you know what actually i'm gonna we don't need this anymore so let me just do this so when i is equal to the size one then we know we have connected to all the uh all the values from other points from group one we just need to check uh if there's any points in the group two that has not been connected before so how do we check that we just need to check if there's any point uh any bit values in the mask that still has zero okay so let's do a four j in the range of size two okay so the way we're doing the check is that uh similar like the or here now we need we just need to do an end here okay basically if because you know if any parts uh if any uh bit value is zero it means that uh the total value of that is also zero okay let me think yeah so basically you know to be able to check if this current value the current bit of positions is zero we need to do this we need to do a like the mask do a end and like what uh same thing here okay equals to zero okay then it means that position is like it's zero so why is that because you know let's say we want to check if this position is zero or not so how do we check we need to get one zero okay this is what we get from this uh move this uh the one uh bit movement right to the left by three so why is that because at this moment right only the uh everything else except for the current beat is it's definitely going to be zero because we know once we move this the all the other bit values there they're all zero so it means that when whenever we do a end here there will be all zero here okay so the final result of the last js bit position they're all zero and we just and now we're only checking if the one here so now the bit value we want to check is it's have the other part is one now we just need to check if the mask is zero or one because if it is zero and then everything is zero then the value is zero it means that okay so that bit value is zero if this is one it means that in this case it's going to be eight basically which means it will not be zero okay that's how we uh how we use this bit mask to uh to set the value and also to check the value okay just remember this it's a very useful trick here okay so and base at this moment okay we know the js point has not been connected before so we just need to return the answer yeah we just need to return oh i think oh i'm sorry okay so here let me do the return here and we just need to return the uh actually so okay can i do answer here like uh i'll do answer two here you know the answer two is one it's zero okay here since we're going to accumulate right we need to accumulate that answer to plus uh the minimum cost two of the j okay and then here we just simply return the answer to here yeah so that's the base case basically whenever we reach the i here now we just and now it's time to return but what value we need to return we just need to return the rest points the rest of the cost from connecting the unconnected points from the group to yeah i think this should just work let's try to run the code here oh sorry class 2 here accept it let's try to submit it yeah so it's accepted i mean okay so what's the time and the space complexity right let's see uh um so for top down dp the time complexity will be the combination of the i and the mask here so it will which means it's going to be the length of the size uh let's see this is m this is n so the combination of this one is like the m times n okay and how about here uh let's see so here let's say uh i think this is not accurate because you know i think the state you know so the top-down dp top-down dp top-down dp uh time complexity is going to be the state the number of state plus the cost for each state so the cost for each state is m so this is m right so this is m so we have m here but how about the total states is that so here the first one is n right so we have a we have n here and the second one is the mask here so the mask uh the total possible values in the mask is we have zero okay that one so the total combination of the mass is going to be 2 to the power of m yeah because at each position we can have either 0 or 1 so in total we have a two to the power of m combinations of the mask here okay so yeah so basically the total time complexity for this solution is m times n times 2 to the power of m yeah that's that and the space complexity is it's the it's basically the size of this it's the size of the uh of the state here which is the uh which is the n times 2 to the power of m okay since you know since we're doing like a little bit improvements here basically you know at if it's we're using like a real brutal force way not a brutal force way i mean we can we could have also used another beat mask to track the uh to track the statement the state of group one here okay i mean we can also do that right i mean if we do that i mean the uh the time complexity will become what will become the uh 2 to the power of m plus n okay right and then times m okay right because in that case i mean the combination of the first property will also be a 2 to the power of n in this case but here we're only having like n here so basically we're improving uh from 2 to the power of n to end here okay by uh by only using like the uh like the index here instead of another beat mask okay cool uh yeah i think this is like a great problem i mean the dp in the dp idea is not that hard but i think what i learned at least from this problem is that how we can use the uh the beat mask to uh to mark the stat status of a list of the elements okay by using an or an end and then we and then after that we just need to come up with a like a strategy of connecting all those points okay cool guys i think that's it for this problem thank you so much for watching the videos and i hope you guys enjoy the videos and stay tuned see you guys soon yeah bye
|
Minimum Cost to Connect Two Groups of Points
|
minimum-cost-to-connect-two-groups-of-points
|
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`.
The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return _the minimum cost it takes to connect the two groups_.
**Example 1:**
**Input:** cost = \[\[15, 96\], \[36, 2\]\]
**Output:** 17
**Explanation**: The optimal way of connecting the groups is:
1--A
2--B
This results in a total cost of 17.
**Example 2:**
**Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\]
**Output:** 4
**Explanation**: The optimal way of connecting the groups is:
1--A
2--B
2--C
3--A
This results in a total cost of 4.
Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
**Example 3:**
**Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\]
**Output:** 10
**Constraints:**
* `size1 == cost.length`
* `size2 == cost[i].length`
* `1 <= size1, size2 <= 12`
* `size1 >= size2`
* `0 <= cost[i][j] <= 100`
| null | null |
Hard
| null |
215 |
hello everyone welcome to learn overflow in this video we will look into another liquid problem that is the kth largest element in an array okay let's see what the question is like also it's a medium level question not so hard not to tough let's look at it further so it says like given an integer array nums okay we have an array nums over here and it says like an integer k that's the k given first like we need to return the kth largest element in the array note that it is the k largest element in the sorted order okay uh not the k distinct element i'll look at the example and let's understand further say we have a number like three two one five six four and a k being two that means the second largest element that's what we should return if we just look into the array we find the six being the largest element we have over here right and the second largest that the two being the cape so the second largest element is like a five right so that's the what we have and thus we can see the output is actually five does we need to uh return the second largest element by depending on what the k is given to us like if k is fourth then we can find that there's six there's uh five then there's four right so that's the fourth largest element we have over here so we can understand like there can be uh multiple values as well right so uh by normal intuition the like the first thing that comes in mind okay we have an array sort the array in a proper fashion and return the particular value out here right so yes that can be a solution for us but remember if you're sorting the error that taking uh like a lot of time to sort the array and then you are calculating the value for it so that's another cost time cost for it like there will be higher time complexity for it so we need to look for better solutions or better ways to uh find the direct okay like find the particular value because like if you look carefully the num length is actually 10 to the power 4 so when you are like sorting an array of such a big size it will cost you a huge time okay so uh that's what you need to remember and you need to check over here so we need to find some better solutions for that the next set of solutions that can happen is like uh we can use an uh priority queue paradigm in the sense we can use an um okay min hip in the sense let's uh store all the values i like not using the limit here at the first let's use a maxif in the first instance okay so if we are using a max heap then like we added all these elements into our massive one by one and then like we can have like the maximum value will be our this value and then we will remove that and then after like uh like k minus one removable we will find the next maximum value we have at the top of it right so that will be our final answer so that can be a massive approach to it but remember what's happening exactly we are adding these values one by one to our maxim it will take a long time kind of a login time yeah and then we will be like removing one by one the all the k minus 1 events another login time right and then we will find our perfect solution for that right so that's not the like the optimal solution we can go for the next one we can think of is like a min hip concept what may hip is look carefully if we have 3 2 1 5 6 4 then we can add like uh we need two elements okay like we need k is 2 so in the second largest element so what let's do say we added three in our min hip and we added two so uh in that case two will be at the top like that at the min hip dot top or mini dot p or the top most element and the three will be below it right so that's how the minip will be formed after insert two elements and when we insert one the one will be like at the it will come at the top uh so i'm just drawing as it is uh so one will be coming at the top and then the min hip will have a size of three but uh look here what we can do at here we need only two elements so we know that when it's a main hip the top most element or the we have the lowest smallest sized element now when we have got three elements that is the uh k plus one elements are greater than k elements we can actually remove one because this is not the one we need over here we are considering the largest element so like anything like uh the largest element greater than like the smaller than these values we can remove that then we got five and we insert the five at the top right so uh five got inserted so five won't be at the top because like it's a mill hip i'm sorry like five will be at the like bottom over here right so we got uh five got inserted and now see we are finding the second largest element in this particular question so we have confirmed that two cannot be like the at the top of the meaning we have two right now so two cannot be our answer in any case right so we can remove that element and then we'll add six will again be the like at the uh end of the main heap at the lyft nodes and then we find that if the size is again exceeding our current uh k value then we know the three like the top of the min here whatever we have it cannot be our answer right so that's true now we got four so four will be somewhere at the top okay uh it don't go down the line so we've got four so we got four and now we sure that when we inserted four this also cannot be uh at the top because we need only two elements so we know that like you said main hip so forth is the minimum value we have over here and we are exceeding the number of values we should look for so four cannot be in our main head just because uh its size is exciting or like it starts extending and it's at the top of the list so the minimum element we have over here okay so we are safari after the whole uh elements like all the elements being added we find that we are left with only a million for five and six now if we just pull like uh just take out the smallest element out of the main here then we find that okay we have only five let's say the simple instance we can find out that five is there and that's the second minimum value we have over here so this is the basic idea of using a min hip and see how what happens you were just inserting the values and immediately removing the lowest elements we you have over here right so that's the idea you have so thus you can see like it is a bit much faster or more much lesser complexity than the other two we discussed further so in this video i will discuss about this particular code we have over here and another approach is there so another approach is there that is exactly you can say uh we have like uh what do you call a quick select okay so that's a quick select approach and this quick select approach is like more like using uh like selection algorithm like it is like related to the quick sort sorting algorithm so this is the fastest approach and this is you know this is like the this is a particular algorithm that is used to find the case smallest element in an unordered list so this is the best case solution we can have over here and it's more like the quick search so i want to discuss more into this uh solution actually quick select solution so you will find another video uh just after this video is getting uploaded uh sometime after this video that in that video i will discuss how this quick select algorithm works and what exactly uh we do to find an uh solution like this right in a quick solution so we don't have much like much lesser time complexity when it comes to quick select so that's what we will do in our next video so in this particular video we'll go ahead and write our min concept answer for this particular question okay so we'll use a minute okay so uh this is the more or less the solution we have over here the main idea is like we use a min hip like a priority queue and then we added all the elements you know array in like order of n like all the elements being added that's like minimum offer and then you find that once uh we find that this particular main hip like is the size greater than k so we simply uh pull our minute like we take out an element from our main the smallest element we have over here so many will give us the smallest element and then after the whole loop is run we just uh like return our final smallest element you know how many so as i discussed in the whole thing so let's submit this uh submit this question and then see what the output is all about is it works yes it works it takes more or less a six millisecond timeline right but remember we can reduce the timeline further if you use like quick select so quick select is actually used for that purpose uh but let's uh go ahead and in the next video i'll discuss about that in depth about how this quick select works and all so uh that's all about this video guys thank you all for watching this video i hope to see you soon in my next video with the quick select approach thank you
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.