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 |
---|---|---|---|---|---|---|---|---|
645 |
foreign mismatch in uh JavaScript um well I'm going to use a hash table to do this so what I'm going to do is create a hash table and then when we're creating it we'll be able to see if there's duplicate in it and then after that so this will get the duplicate and then after that what we'll do is we'll search in the table uh for the missing number all right okay so uh we're gonna use that with the map data structure so we'll start out by going send let map equal new map like that and then we also are going to want to create a duplicate number and missing number okay so now we'll create our actual hash table here with for Loop and so what we're going to do here is going to say if the map doesn't have the value then what we want to do is we want to set the value like this so if you're not familiar with maps I highly suggest learning about these they're really useful um and then otherwise we know what the duplicate number is because we're setting this as one right when we go through this map and we're going okay if it doesn't exist if num's eye does not exist set it as a value of one otherwise we know that the duplicate is that uh is that value so let's double check that we have a map set up correctly and we can just do that by just console about logging out our map data structure this map we'll run it doesn't like what I type wrong here oh there we go it's numbs let's run this again Okay so this is our map data structure and we can see that the count here is the second one that we've done value of one first one is the value so we have one two and four and we're missing the three uh just as an aside here you can add the other way to use this or I guess the other half of using this pattern here is you would basically get the value and map down here in the elves and set it with an increment here and that way you could actually populate out how many numbers are in the data structure so you could be like oh there's two twos in there but we don't need that for this algorithm okay so now that we have a map we're going to initialize account equal to one and this is why I like Maps we can use uh we can use this for Loop to get the key in the value of the map so we have key and a value that's why I like them better than just straight up objects because you get all these awesome ways to access and check things in map and what we can do we'll just console log out count so I can show you that so if map Dot get count okay so what we're doing here is we're checking to see if count exists inside of here and if it doesn't and then that's the missing number otherwise we're just incrementing count because we know that one two three four five six seven eight right that's just incrementing inside the array over here so we know it's going along that path so all we have to do is just check for that and all we have to do is check for that uh inside of the map structure there's no three so uh if map gets does not get count does map get count here yes it does it's going to get this one too because it's going to find this two and every time hit hits us else we're going to count so did we find the one yes add on account run the loop again did we find the two yes okay add account run the loop again do we find a three we don't find a three so that's the missing number right there um then all we need to do this goes up here there then all we need to do is just return these values so we can return we have duplicate number and a missing number let's run this uh it doesn't like ah duplicate number try this again okay and then we can submit it and we get right there so let's uh see if we can make this bigger so you can see the whole thing okay that's that problem
|
Set Mismatch
|
set-mismatch
|
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number.
You are given an integer array `nums` representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return _them in the form of an array_.
**Example 1:**
**Input:** nums = \[1,2,2,4\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[1,2\]
**Constraints:**
* `2 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
| null |
Array,Hash Table,Bit Manipulation,Sorting
|
Easy
|
287
|
371 |
hello everyone welcome back and today we are looking at question 371 which is sum of two integers so we are given two integers a and b and we want to return the sum of these two integers without using the plus and the minus okay now so example one is saying a equals one b equals to two one plus two equals three now example two is saying okay we have a two we have a three and two plus three equals five now we know how to add numbers but the challenge is we want to do that without using the plus and the minus operators so how can we do that well let's go to the blackboard we will explain exactly how can we do this we will explain the approach and the intuition and then come back to lead code to code the solution out if that sounds interesting let's get straight into it okay so to start this question let's go to the basics on you know we want to add some numbers so we have for instance 2 plus 3 we know that two plus three equals five four plus four equals eight now eleven plus nineteen what do we do well one plus nine equals ten so we have a zero and we have a carry right here then we say 1 plus 1 equals 2 plus 1 equals 3 so the answer is 30. now it's important to note that these numbers are in base 10 means that all the numbers that we are allowed to use go from 0 all the way to 9. now that's why in this question right here when we say 1 plus 9 when we know that the answer is 10 but since we are in base 10 we are not allowed to use this number because it does not exist all the numbers that do exist in this base are from 0 to 9. now 10 is greater than 9 so it does not exist that's why we have the carry over we put the 0 then we carry a 1 and then we continue normally okay so this is important now this is base 10 so let's look at base two these are the binary representation of these numbers for instance two is one zero three is one four is zero one zero and so on so forth okay now before we um tackle this it's important to note that whenever the question wants us to do the basic arithmetic operations for instance we want to add subtract uh multiply or divide right whenever we want to do one of these without using the sign it's always bit manipulation now this question once had to add two numbers without using the plus sign so of course it will be bit manipulation now when we say bit manipulation we will be dealing with bits and we know that the bits are zeros or ones so that's why we are dealing with base 2 in base 2 means that there are only two numbers allowed in this base which are zeros or ones and that's it now the idea that if we add two numbers and the result is larger then you know the biggest number in the base we will have a carry over same thing here if we add two numbers and the result is greater than one we will have a carry over that's why in base two it's always good to keep in mind these two numbers two and three the binary representation of two is one zero the binary representation of three is one it's important to keep these two numbers in mind and i will show you why so let's start with two plus three two is one zero three is one now what is zero plus one well it's a one now what is one plus one well one plus one is two but again we do not have two in this base so what do we do the same thing here we will have a carry over now we see that two in binary is one zero so we will take the zero we will put it right here and we will have a carry with a one right then we can add you can imagine that we have zeros right here so one plus zero equals one now two plus three equals five and one or one is five in binary okay that's why i said it's important to keep these two numbers in mind now let's go to the next one well zero plus zero is zero one plus one is two we don't have a two so we will put a zero and we will carry a one and one plus zero is one and indeed four plus four is eight and this is the 8th in binary now finally let's go to the last one so we have 1 plus 1 which is 2. so we will put a 0 and we will carry a 1 plus 1 is 3 but we do not have three in base two three is equals to one so we will put a one and we will carry the next one which will be right here now one plus zero is one and of course zero plus one is one now this number in binary is thirty and indeed eleven plus nineteen is thirty so the summary of this section of the video is that the addition in any base is the same we add numbers and if the result is greater than the largest number in the base we will have a carry over okay so this is the summary of this section of the video now let's continue okay so once you understand that now what do we do well to solve this question we said we need bit manipulation now which bit wise operators we need to use now when i say bit wise operators they are operators that work on bits and thus the name bit wise operators now we will be using three of them which are exclusive or we will be using the bitwise and operator we will be using the left shift operator now why we will be using each one of those well i will explain in details but let me give you an overview now the x or the symbol for xor is like this bitwise and is like this and now the left shift is like this now why we will be using exclusive or well keep this in mind exclusive or is used okay to simulate addition without the carry so exclusive or is used to simulate addition without the carry with no carry all right now the end and the left shift both of them combined are used to simulate this carry okay so these are used to simulate the carry now why and how do we do that i will show you exactly um what to do now to start with let's have a small review of the exclusive or and the end i will have two numbers a and b okay and i will put them into a table and i will put all the combinations of these two numbers a can be a zero it can be a one okay b can be of course zero under one so we'll have these if we have two numbers we will have four possible combinations zero one now let's do a exclusive ord with b now in this in the exclusive or the only way that we can get the one in binary is that if a and b are different in this case 1 0 1 a's and b's are different this will we will have ones right here 0 a and b are the same we'll have a zero one and we are the same we will have zero okay i will come back to this to show you how this will simulate the addition now let's look at the bitwise and we have the same thing the same table right here so let's copy that and let's space it right here and we will change these okay now in bitwise and the only way to get a one is that if a and b both are one in this case only this row right here one and one will leave us one the rest will be zeros zero and zero 1 0 and this is the same okay well we said exclusive or is used to simulate addition without the carry now i say with no carry you might be confused why is that the case i will show you just bear with me we will see that zero give us zero one zero give us one so what do we notice well it is simulating addition zero plus zero is zero one plus zero is one zero plus one is one plus one is weight one plus one is not zero one plus one is two but remember the two is equal to one zero and now when we added these look at this here right here one plus one we said it is a two we put the zero and we carried the one and that's why we said exclusive or is used to simulate addition with no carry this will only give us the zero but it will not give us the carry okay so that's why exclusive or is used to simulate addition with no carry now let's look at the um bitwise and we see that it only give us one when a and b are one okay so let's look at a quick example we want to add seven plus seven which will give us we know fourteen okay so let's do that seven is one so we want to add it with one so let's see what happens so we will have this um and now i will show you how these can work together one and we have the same here one but now with the bitwise and now here i will show you the addition one plus one okay so now starting with exclusive or well exclusive r will give us a one if a and b are different here all the you know all of them are the same which means that this will give us three zeros now let's look at the end the only way we will get a one if that a and b are the same in this case all of them are the same so we will have one okay so let's try to add seven plus seven in binary well we said one plus one is two so zero and let's carry a one right here now one plus one is three we will have one and we will carry a one so one and let's carry a one plus one is three so one and let's carry a one and one plus zero is one and this is indeed fourteen now what do we notice well we know that each number of those will give us you know each addition here will give us a carry and that's why the exclu the exclusive or gave us all zeros because it simulate addition with no carry so that's why we are missing all the carries but let's look at the end is giving us all ones because a and b are the same well one plus one will give us a carry so look at this the bit twice and always tells us the position that will produce a carry when we see a one here this means that this position will produce a carry when we look here this position is telling us hey this will produce a carry we have a one here this position will also produce a carry so you see this the exclusive or simulates addition with no carries the end tells us the position where we will have a carry so now when we add these numbers what do we see we have the carry right here you see the end gave us three ones and now we have the three ones right here but they are left shifted one position to the left now why is the case let's go back here and look at this when we said one plus one give us two we said zero and we have a carry we put the carry one position to the left let's look here one plus one is two we have a zero and we carry a one position to the left let's look here one plus one is two zero you carry one position to the left one plus one is three we have a one and we have a carry one position to the left so we always apply the carry one position to the left and thus we have the left shift operator so the end will tell us which position will produce a carry once we know that position we will shift it to the left by one so that we can apply the carry okay as you can see um the and gave us the position where we have a carry we took this number we left shifted to the left by one position unless it's starting from here not from here and we just add the carry and we will have the result and that's how we will do the problem one we will put the exclusive or the two numbers which will give us the sum without the carry then we will apply the and then the left shift so that we can have the carry that we will add to the result so let's do one example to see how to do this then we will go and cut the solution out on lead code okay so let's try to add six plus six we know six plus six gives us 12 and 12 in binary is one zero so let's see how can we um arrive to this number without using the plus sign well we said we need to compute the sum using the exclusive or without you know um worrying about the carry so we need the sum and we said we also need to check the carry so we will have two variables one for the sum without worrying about the carry and one just for the carry okay good so we said six plus six now six in binary is zero one zero of course we will add it to itself so zero one zero so we have these two numbers well one we said we need to simulate the addition without the carry so we will take the exclusive or the only way to get a one is that if both of them are different zero and zero the same one the same zero are the same so this give us all zeros so this will be stored inside of the sum now let's look at the carry well we said we need to do the and operator then we will do a left shift now in end we need both of these numbers to be a one to get a one which means that zero and zero is zero one and one is one zero and zero is zero so this is the arm carry but we need to left shift this number to the left by one position right which means we will have this number right here zero one zero as you can see we have the same number but we left shifted to the left by one position so this is will be the arm carry okay so now we have the sum and we have the carry and we did and we left shifted to the left so the carry is ready um to use now what do we do now well of course we need to add the carry to the sum what is zero plus zero one zero well we said to do the addition we use the exclusive or zero and one is one of course zero exclusive on with the zero is zero so here is the answer zero one and what is this is 12 in binary okay that's it now there is one last thing that we need to look at but we will explain it when we write the code um but an overview of that thing is the following when we compute the sum when we compute the carry then of course we add the sum to the carry in this case we got the result but remember whenever we add two numbers right there is a chance that we will produce a carry so when we add the sum to the carry there are cases where this addition will also cause a carry and we need to keep doing this we can think of this as a loop that we will keep doing until the carry is zero so that we can return this sum it's okay if that sounds a little bit confusing let's go to look at the code and i will explain to you um exactly what happens okay so let's try to write the code for the you know for the solution well we said we need two variables we need the sum and we need v carry this sum will be used um from the exclusive or so that will be the sum without worrying about the carry so the sum will be the first number which is a x or with b okay now we need to look at the carry well we said that the carry is basically we need to take the first number and the second number apply the and operation this will tell us the position of the carry then we need to lift shift one position to the left so to make uh to make the carry ready to use right so a so we'll be using a let's end it with the b and finally left shift one position to the left so now we have the sum and now we have the carry and yeah so now we said we need to add the sum to the carry to have the result but we also said that whenever we add two numbers there is a possibility to have a carry so this sum plus the carry might produce more carry overs right we need to keep doing this loop until the carry hits zero so we will have a while loop and we will say hey while we carry does not equal zero we need to keep looping but let me ask you imagine if we are adding two and three two plus three equals five and what is the carry would be zero so we go here hey while the carry does not equal zero in this case it is zero so we break from this loop and we just return this sum now let's look at the case where we have a carry in the previous example we said six plus six equals twelve okay so here we computed the sum using the score the xor here we computed the carry and now we need to add them right so we said okay this sum will equal some exclusive or with the carry again when we need to add two numbers we apply the exclusive or we need to add the sum with the carry so we say some exclusive or with the carry and we will update our sum but we said this might produce a carry so what need to do well we need to check that carry we said okay the carry let's copy and paste it's the same equation the carry but now we don't have a and b we have the carry itself and we have the sum right we need to add the sum with the carry we apply the exclusive or but this might produce a carry so we take the end between them and then we left shift one position to the left so we have the sum we have the carry then we go to the while loop we check is the carry zero if yes we break we return the sum if no we continue but here there is a small problem which is the following when we say sum equals sum exclusive or with the carry and we update this on okay now when we want to check the carry we can't say carry and sum this has changed this is no longer equal to this so what we can do is that okay no problem in temp we can have a temp variable to store the sum then when we update the sum okay we just say sum and with temp and that's it we compute the sum we compute the carry we have a one loop to keep going until the carrier hits zero at the end when it does when the carrier is zero we break we return the sum so now let's run the code and let's submit as you can see faster than 100 so now let's look at the time and space complexity starting with the space complexity we did not use any extra space so it's big o of one constant space now what about the time complexity well we are trying to add numbers and it's important to know that each integer is 32 bits so anytime we will do this program we always are applying on the operations between numbers that are 32 bits this is a constant so the time is always big o of one the time will always be the same we have 32 bit integers so the time is always the same big o of one i hope you guys enjoyed the video best of luck to you and i will see you in the next one
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
130 |
hi everyone so let's talk about surround regions so you are given um by a matrix so containing x and circle capture all regions that are four directional surrounding by x so all so a region is captured by flipping o z uh oo into x in the surrounding region so for example if you have uh three or uh three o inside a uh thrown by the x you have to convert to the x and if not if you are on the boundary i mean if you're almost older then you don't have to change but you can still i mean if this is circle then this will connect the entire region that will result circle for the final project of final board because it is connected so this is pretty much like content iron so this video is going to talk about how you actually do in that first search so what will i do is i going to check for every uh every cells when i equal to 0 j equal to 0 when i equal to lasso j equal to lasso to see if there is a circle or not if there is a circle i'm going to go for different direction up down left side to check if there's a neighbor there's a circle then i'm going to mark these cells could not be an x for the final board and at the end i would just leave the cells to the circle if those if there's if the cell is not it's if the cell is supposed to be a circle at the end so what i do is i'm going to try verse so before i traverse i'm going to say i'm going to declare m and so n will be the board that length and n will be become for zero that length and so i can traverse so for i zero i less than i plus and for j equal to zero j less than n j plus so i'm going to check the boundary rat so check the boiler so check the border i equal to zero j equal to zero o r i equal to n minus one or j equal to uh n minus one and at the end i have to know at least cells has a neighbor which has a circle or not right so i'm going to pass in a helper function so it's going to be void and i'm going to still using software inside my argument i have a board i have a j so i'm going to call it soul or i j okay so now we pretty much just um going to check if my i j and i mean i j cells which is outside border is circle right so um i'm going to say if board i and j if that is equal to x we don't want to continue always so we don't want to continue for a rest so just return but before that we need to know if i is in the boundary or not right if i less than u or i could equal to both the length i return and also if j is less than 0 or j will equal 2 for the 0 length this is pretty standard stuff then i will return so what if there's a sales that is supposed to be um that is supposed to be for example if this cell is supposed to be a circle called a final board i need to change the circle to something else so i'm going to say for i j equal to let me say little star then i would know this cells is definitely going to be not changed then i would just traverse its neighbor so i plus 1 j so for i minus 1 j so for i j plus one so for i j minus one all right this is how you actually do it but if there is a cells you already tried birth and you change the symbol then you also need to return right so board i j equal to star you need to return and uh just making sure you can actually put these three is if statement into one but for re readability i would just do at least and after you traverse every single cell on the border and you expand it if there is a cell that is circle and you follow us for the middle one for the middle border something i mean full of borderlands inside the board then you need to know this could be not be possible b circle right the cell could not be possible be circular say so you have to know you need to change the circle to x so what will i do i would say um for i equals zero i less than m i plus standard traversal for the 2d lsn ig plus so if board i j is equal to star we already know this shouldn't be uh x y so both i and j will remain oh everything else you know right it's going to be x then we don't have to return anything this is the entire solution it's a void and let's just see if i have anything that is not clear okay pretty good all right this is uh pretty easy so it's pretty much like counting iron so let's talk about timing space for the time in space it's going to be m times n and for the m for row and for the column so n for the time and n for the space why because you have 2d ball right i mean technically you don't need extra space but you need a space for the ball there i mean which is all of m time n and space is all of n times n because twofold right and that will be the solution and i hope you get it and this question will be considered easy if you do the counting iron and if you have a question leave a comment below if you liked the video please leave a like and i will see you next time alright peace
|
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
|
795 |
hey everybody this is larry this is the 17th of june uh on the june lead code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem uh and it is loading number of subways with bounded maximums so usually i uh solve these live so if it's a little bit slow just hang out for a little bit or watch it on 2x the technology exists uh anyway we're given an array numbers of okay and a positive two and three we turn the number of contiguous subarrays such that the value of the maximum of element that separates at least left and at most right okay i mean this is the link with num okay and this um the max the value of the maximum array element okay let's see right um so this is going to be some sort of at least my guess is some sort of um two pointers or a sliding window if you will um so what happens right is that when you slide the number of subarrays well there's only two situations one is the condition is being met and then the condition is not being met um and the conditions being met then it's just you know the number of separate ways is just the window that we're given and if it's not being met then we have to keep on adding numbers until it is being met um yeah and then we have to figure it out because i and once it goes so there's only two conditions right where it's not being met um or okay i guess there's three conditions all together one is that the maximum number of the sub array is less than left i don't know why they call it left and right they should just call it min and max or something i don't know maybe that's confusing though but in any case yeah if the max is less than min then we keep on greedily keep adding if it's within that bound we just keep on slowly sliding from the last point of possible possibility and then otherwise if it goes over right then we have to start over so i think that's basically the idea yeah because once we pass right then there's no possible sub arrays that includes this number right for example if the max is 3 4 cannot be in it no matter what so it has to be it splits the way into these chunks and then within those chunks you just have to figure out how many of sub arrays have at least the minimum element right okay so let's think about it how do we get let's say we always split up the array right then we just do itself on the number of and then they become independent problems and for each independent problem it uh then it should be sliding window right yeah you start zero you slide your slide it's good then that means that everything before and after is good um so you can even do some sort of math right because okay let's say we already delimited uh by the maximum number so we kind of put it into independent forms so then you basically have let's go over it for a second so let's just say we have a bunch of numbers let's just i'm just going to call it um trying to visualize it a little bit better but let's just say we have three different three types of number right um a is equal to just smaller than left b is between left and right inclusive yeah and c is larger than right so now you have like some string of things uh that's way too long for something like that right and essentially what you're doing is you're delimiting by the c so now you have a problems of just a's and b's right because no sub array will cross boundary um for this definition so now you have just something like that say uh maybe even a's in the middle and then the problem becomes um almost like a reverse like so you can do some sliding window math to get uh the number cam for sure but another inverse way of thinking about it is now that you're given this um the array must contain at least this chunk so that means that they're only not possible arrays are the prefixes and the suffixes right so that means in this case you have these three that means that the possible arrays are just like six or something right because three times two do we choose to just we choose two six i don't know anymore something like that right um and then the suffix also have some you know let's just say a little bit longer um no uh six choose two right um because that just is the number of uh is it three choose two yeah it should be right it's three plus two plus one so yeah anyway we could do the math maybe it's not reaches two uh but in this case it you know the three strings that are not possible well maybe more because you have from zero index of zero you have zero one you have zero two you have one two and then two right so is that 3 choose 2 i'm getting my note oh getting my notation incorrect maybe because that doesn't sound like we choose to but it's actually um n times n plus 1 over 2 right so yeah so i'm a little bit wrong in this one so it's should be but you get the idea right that's just the number of possible substrings or sub array and inside here so then now we can take the total number of sub arrays which is again n times n plus one over two minus this and the suffix so i think that's the idea so you can actually do this with a lot of just straight math and intuition and i hope that i'm right because otherwise i'm just explaining a lot of things that are wrong but you know what you signed up for that's the risk i'm solving it live i'm sorry if i'm wrong if i'm right i'm still you know you do what you can so okay let's do that then um so yeah so i'm going to abuse group by uh should i definitely could abuse goodbye but let's not actually so then now we just have a um count sub maybe i don't know of um left right let's just say index one index two i usually go left right for my indexes but this is very awkward uh all right let me just relabel this if you're watching at home note that i did relabel those so uh watch out so then now we count is equal to the number of things so and this is inclusive so that means that it is uh let's just say n in this case is equal to y minus left plus one because it's inclusive and then count is equal to n times m plus one over two and then now we're looking for the prefix and the suffix so yeah left prefix is equal to um let's just say zero and then we do a while loop while left is less than or equal to let's just do if they um yeah if num sub left is greater than max then we break otherwise we no yeah no oops if this is smaller than min then we continue so let if this is greater than or you uh we break right otherwise left plus um yeah left no this is whoopsie something like this maybe and this will give us the number of digits that this is true for and then count we subtract from left prefix times left prefix plus one overdue maybe we should put this in a function but it should be fine for now let's at least get it right before we do uh right suffix oops so right suffix you go zero so let's just say right it's still greater than left um well i guess if count what happens if this goes over right then this is equal to n so yeah okay so if count is should we just return zero um otherwise we do the suffix as well because that means that we don't duplicate so yeah with nums so this is given um a contiguous part that is good right so wish there were more i mean we could set up our own test cases it's not that big of a deal but yeah um okay so then now we just have to divide it so we go um previous is to go to zero maybe for index in range sub n i know that the two ends but that's okay i think um so if num sub index is greater than uh max then we have to start splitting it to the left and the right so then we go okay let's also have a total of zero we add this to the counts sub from the previous to index minus one that's also just for six if left is greater than right return zero because wait i guess this is not true if this is equal if it's equal we might have to do it loop once because it may have one away um one element um previous is equal to index plus one yeah i mean i think this is a flea right if number if the last number is not greater than max then we have to do it um maybe i should have just used goodbye to be honest uh maybe that's fine but in any case if the last number is less than max then we have to trigger it one more time so yeah so this is a little bit yucky uh n minus one okay let's kind of see how it goes a little bit i'm i mean the implementation might not be right but we'll see um because i think the idea is right but everyone here knows that my implementation has been kind of bad lately 50 000 so it should not overflow that's the other very 78 okay let's just try this but i had a couple of i was going to i say sex spit all right let's see and of course we do have the cheating ability of looking at the expected answers so we are more confident than we would be than in a contest for example for contests i might split it up a little bit more and or write a don't write a way of verifying this n is very small so you can actually write an n square um you know you could check every possible ends or maybe n cube even um just to kind of verify your answer um so for small cases so that you know uh but now i don't even have to but if i was in the contest and i'm still feeling as unconfident as i am now um that's maybe what i would do um yeah let's just add a couple more but it seems like this is okay let's do one with the pre where it's cut off in the beginning or the end i guess yep okay so let's just give a submit hopefully this is right oh yikes why is this wrong so maybe like i said maybe i'm off by one somewhere i thought i tested a lot of cases though so that's a little bit sad hmm because i quote a lot of etched cheese stuff but well okay let's see i upped 23 but it should be 22 69 so okay so one thing that i do for debugging is just try to get in another case where i'm wrong which is slightly easier to read so let's try this one what do i get so i still get the wrong answer which is good because it eliminates uh some of the possible reasoning but it's under that of my logic is wrong oh my logic is missing something that's right i thought yikes i'm just really sloppy lately that's my fault um so the answer is that okay given the notation that we had before we have let's say now we have an inner thing of behavior i just got lazy and said that this could is n times you know whatever but this is not right of course because and it's very obvious so i don't know why i'm doing it because you have like a for example in the middle where that's not true so you have to kind of figure those out as well um so then now it becomes delimiting not just by left prefix but now you're doing a second delimiter um going further away um yeah so let's do that so yeah so i did it with the left prefix and the right prefix but you have to do it for the inner side as well i'm just really sloppy today like i had to i okay i mean i didn't have the right idea but i mean i had the right approach but i didn't take it to a logical conclusion because i didn't really think it through um and that sometimes happens when you rush rings a little bit and i definitely uh maybe watch things a little bit here um so yeah so then now we delimited and this is where maybe using group by would have been very helpful um because it's just easier to write uh okay but basically what you would do is you would do the same thing here where you just go left to right and then try to do it um yeah basically you're delimited by the b's and then trying to find the insides and then subtract them uh for each independent one i'm going to just cheat a little bit now and then using goodbye um what is goodbye basically goodbye is a thing in python that allows you to split essentially in a way into i mean there are things to do go about it but you basically um yeah you spread it a thing into things that you can group by um and then you use that in a way and one of the ways you can do that is so goodbye numbs um forget the syntax actually so maybe there's a good it could observe uh other tools i think so i'm just reading up the api real quick okay edible and then key oh yeah okay so the key is you could is that the name of the yeah okay i was just making sure the name of the parameter name so basically for an x we just group by whether it is bigger than uh the max sorry friends i know that this video is a little disjoint i'm a little bit tired just too tired today in general uh but hopefully this makes i mean the algorithm makes sense i just been very sloppy about it so yeah so four what does this return this is for a key and a group in this uh yeah so if key is false so if not this because so what is the key is it takes this function and then it groups by adjacent groups adjacent elements together by that key so and because here we choose the key to be greater than mx meaning that so now we could buy group together or adjacent elements where it is not the l and it is not it is smaller than uh the maximum thing or equal to so then that's why i chose if not then we do this thing where um let's just do count sub array uh i don't know how to call these things i don't know my brain is not really working today my apologies but we can just pass in this error tool uh let's make it a list because it is an iterator by default so let's make it back into a list and then yeah we can just define this let's return zero and print it out because just in case i am even sloppier than usual i have my confidence i don't know i just been doing some playful test uh coding all day and i don't know maybe or something a little dehydrated to be honest but this looks good right uh for one and five but this one like it's intentionally to show yeah so everything looks good so yeah um and then now like we said um n is equal to the length of uh og um total is equal to n times n plus one by two or divided by two times y is a mod and then now i do four k g again and now we could find by the other thing um which is if it's greater than or equal to huh what is our delimiter oh yeah the limiter should be now bigger than so now we just want to count all the smaller numbers so we use this as the delimiter meaning now we have numbers that are no good right so if these are lower numbers we subtract it by concept away two um and i think that should be good and that's why i remember i don't know if this group five thing is more readable that's why i didn't write it this way um but i but it the other code was pretty yucky as well so yeah so that's why i didn't like it okay now let's give it a spin okay so everything's good except for this one why not i mean this one's good all the other ones are oh no this one's not good either did i might have off by one on the eco signs so we are smaller we should subtract from it okay oh man i have to convert this into a list what am i or fine i am now curious i mean it's probably just off by one but so we add these two oh no we subtract by this and plus is this formula 1 so if it's 1 it should be 1 times 2 times 1 so that's right so why is that wrong i don't know if this subtract one is from the same now it should be from the same why am i subtracting one again oh yeah okay typo that's uh the scoping thing is a little bit awkward i probably should have been better okay now everything's good so let's remove our debug things run it again and yeah it looks good so my album is still mostly right but my implementation again failed me why am i such a bad coder these days i don't know maybe i just need more sleep it's been a crazy month uh okay so what is the comproxy here right well for each even though this looks very confusing and there are a lot of for loops and stuff like that um each element only gets looked at each um each element only gets looked at uh a constant number of times right um you know if this is if each number is bigger than max it gets only looked at like once or twice and then here yeah again so basically each number only gets looked at like three or four times so this is actually even despite how it looks like is the linear time in terms of space you can definitely do this in linear space if you're not silly like me and you're better at bookkeeping which was my first attempt the way that i did it we construct a lot of lists well not that many actually because each we construct constant number of uh elements for each list each we put each element constant number of times in new lists so it's linear time linear space that's what i'm trying to say uh as you can see i'm struggling for some reason allergy is still kicking me but i have a lot of excuses but uh no this is linear time linear space so yeah but if you had did it if you follow through what i tried to do in the beginning um you can get that in all of one time or sorry you know one space i know of end time but instead the way that i just linear time linear space but it is much easier to write and much cleaner and even the debugging only took like you know a couple of seconds so yeah that's all i have for this one uh let me know what you think it's kind of long video it's a little bit sloppy but the idea of sound uh i don't know hopefully i mean hopefully you get to understand how uh to attack a problem with my way or something i don't know uh anyway i will see you later hope y'all have a good uh rest of the week as the weekend is coming up and i'll see you later to good mental health bye
|
Number of Subarrays with Bounded Maximum
|
k-th-symbol-in-grammar
|
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,1,4,3\], left = 2, right = 3
**Output:** 3
**Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\].
**Example 2:**
**Input:** nums = \[2,9,2,5,6\], left = 2, right = 8
**Output:** 7
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= left <= right <= 109`
|
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
|
Math,Bit Manipulation,Recursion
|
Medium
| null |
304 |
hello guys welcome back to tech dose and in this video we will see the range sum query on a 2d matrix problem which is from lead code number 304 in this problem given a 2d matrix handle multiple queries of the following type so calculate the sum of the elements of the matrix inside the rectangle defined by the upper left corner lower right corner and you will be given two apis so num matrix initializes the object with the integer matrix so this is kind of a constructor and then you will have a sum region where you want to find given a box what will be the area of this box starting from r1 c1 which is the upper left corner and going to r2 c2 which is the lower right corner okay so let us look at an example in order to get a better understanding now in this case let's say that this is the given matrix now in this matrix if i ask you about finding the area of the green rectangular region you can see that i have marked a green rectangular region so in this case the upper left corner is 2 comma 2 i mean 2 comma 1 right so this is the upper left corner which is 2 comma 1 and the lower right corner which is 4 comma 3 okay so what is the area of the rectangle enclosed by these two points this question is asking about the sum of this rectangular region so one simple process can be to just iterate through all the cells and keep adding all the values and then you will get an answer so you will get 1 plus 2 plus 5 plus 4 plus 1 and so on till 3 you can do that and in the worst case you will have to traverse all the elements mn and if let's say you have q number of queries then we will be iterating m n that is the entire matrix q times and that will be m and q this will be the time complexity of your simple approach now we can optimize the approach because we are adding all the values right so we are adding 1 plus 2 plus 5 then we are adding 4 plus 1 plus 4 and so on now you can see that it is a combination like we can assume a 2d matrix as multiple 1d matrix right and you already know that if you want to query range sum on a 1d matrix without any update then we can use the prefix sum for calculating it in one time now in this case if i want to add 1 to 5 if i had a prefix sum for this row number 2 then i can easily do 11 minus 3 and get the sum value of this entire range which will be 1 plus 2 plus 5 will be 8 11 minus 3 will also be 8 due to the use of a prefix sum okay now we can calculate the prefix sum for all the rows how do you do that you find the cumulative sum for row number 0 one so you have written one plus four is five you have written five plus one is a six you have written six plus two is eight you have written it and so on right so in this way we can calculate the prefix sum for all the rows and once we have found this now we can calculate the area of this rectangle by not iterating through all the elements of the rectangle but only the last column of the rectangle you can see that i can just go to the last column of the rectangle and do 11 minus 3 which is 8 then 9 minus 0 which is 9 and this 9 minus 1 which is 8 and add all these values so this will be 25 i guess 8 plus 8 16 plus 9 is 25 and in this way i can get the area of the rectangle provided i have pre-processed pre-processed pre-processed because there is a preprocessing involved for converting the given simple matrix into a prefix sum array i mean the prefix some 2d matrix right so the preprocessing involves you to go to all the cells so this is a mn process and after the preprocessing is done you can just go to the last column and calculate the entire sum of the rectangle so the last column will be in the worst case you will have to go to all the rows a column will have elements equals to the rows so this is a m by n matrix where m is the number of rows so in the worst case a query can take order of m time and since you have q number of queries so the time complexity will be mq so after preprocessing is done each query can just be served in order of m time as compared to the brute force technique which took m n time okay so this will pass on lead code as well but there is a better approach which will solve the queries in order of one time so let us get an idea for that approach now in this case if you look at the first figure if i ask you what is the area or what is the sum of all the values or maybe just take it as an area what is the area of this region r you can calculate it in one way that the area from 0 to let's say r 2 c 2 what is the area from 0 to r 2 c 2 from that you subtract the white region and you subtract the green region as well and you will see that this particular box was subtracted two times but it occurs only one time so you will have to add this region let's say this is r1 c1 so you add the region from 0 to r1 c1 once i hope this is clear so in order to find the area of region r you will have to take the area of the entire rectangle from 0 to r 2 c2 and from there you subtract the white marked region you subtract the green marked region and you will see that wherever the white and the green regions are overlapping those were subtracted two times but it occurs only one times so you have to add one time this rectangular area in order to compensate for extra deduction okay so you will have to add the area from 0 to r1 c1 if you look at it as a coordinate so this is your region r and if you want to find the rectangular area r or you want to find the sum of all the elements in this region then you take the entire sum from 0 to r 2 c 2 which is this one from 0 to r 2 c 2 and then you subtract the white region from 0 to r 1 c 1 i mean from 0 to r 1 c 2 so 0 to r 1 c 2 and also you subtract from 0 to r 2 c 1 and this region was subtracted 2 times so you have to actually add it once in order to compensate for an extra time subtraction okay now this is the entire logic for finding the area of regener now if you look at it we are actually including the cell r1c1 and this will not be included in this first matrix okay and even when i say that this is the first area the white region when i talk about the white region the coordinate here is not r1 c2 but it should be r1 minus 1 c2 because r1 c2 is included in this region r okay so we have to go one row up in order to get the row which is not included and the same goes for this one as well we will be at r2 but we will not take c1 because c1 is included in this region r so we have to go to the previous column which is c1 minus 1 so if you solve the problem you will get the understanding about it that's why i did not write it but i have written it here if you want to understand it clearly okay now we have to fill all the cells of the matrix with the rectangular area from 0 to that cell so i will show you how to do it let's say the given array is this one this is a given 2d array which is given as an input for your problem now we have to do certain preprocessing and this time we are not doing the same preprocessing we did like the prefix sum array it is a different preprocessing each of the cell like this is a pre-processed matrix now each of the pre-processed matrix now each of the pre-processed matrix now each of the cell here will denote what is the area starting from 0 to that cell so when i see this 1 this means that the area starting from 0 to this cell 0 is 1 when i see this 5 this means that the area starting from 0 and ending at 0 1 will be 5 which is 1 plus 4 and if i talk about what is the area ending at this cell 0 2 starting from 0 i mean by area we mean that the addition of all the values in the rectangle okay so that would be 1 plus 4 plus 1 which will be 6 and this is how it is going right i hope you understood the first row and the first column why did we take the first row all as zeros and first column all as zeros these are appended so that our formulation always works okay if you don't append it you will get segmentation fault if you use this formulation you may try it out otherwise you will have to write multiple conditions to not go out of bounds rather than including multiple condition it is always recommended that you append one row and one column wherever it is needed okay in this question it is needed what will be the area starting at 0 and ending at 1 0 it will be this rectangle right which is 1 plus 5 that's why i have written 6 what is the area of the rectangle which is ending at 2 0 and starting at 0 that will be 1 plus 5 plus 3 which will be 9 that's why i have written 9 here so i think you understood the first row and the first column how they are filled now for any internal value like why i have written 13 here so it is all about if i am given a cell and there is a point 0 then what will be the area ending at this point which is r 2 comma c 2 that will be equals to whatever is this area this will be some area let's say the top area and then whatever is this area this will be some area this entire thing will be some area let's say the down area or maybe the left area whatever the top area and the left area you just add them up and you subtract the part which was added two times you subtract it and then you add the current value of the cell in order to get the area of this entire matrix okay so in this case the top area and the left area you just take the top area and the left area so the top area is 5 left area is 6 that is 5 plus 6 equals to 11 so you get top area and the left area as 11 now you have to subtract the common part how do you get the common part it is just the diagonal point which is the common part so subtract 1 from it and you get 10 and after that since the current element has to be included in the current matrix ending at the current cell so you see the current value which is 3 so 3 will be added to it and that's how it is thirteen okay now let me give you an example uh so let's see an example for this five comma four okay let's see an example for five comma four so if you map it here five will become four and this four will become three because i had appended an extra row and an x and an extra column okay so i want to find an area i mean i want to find this entire area okay this rectangle area and whatever is stored here 49 is the area starting at 0 and ending at this cell which is the bottom right corner and the value should be 49 how is it calculated in this case i will first see the area which is already pre-calculated so the yellow already pre-calculated so the yellow already pre-calculated so the yellow region shows the top area and this has been already calculated as 40. this is the top area okay and then you take the left area so i'm marking it in green whatever is marked in green is my left area so i will take the left area here which is already calculated as 34. now there is a common region so this entire part is a common region right so this entire part says that the common region box is ending at 3 comma 2 so this is just the diagonal so you add 40 34 which will become 74 and then you subtract 28 from it and you will be getting 46 here so once you get 46 then you have to add the current element which is 3 so 46 plus 3 will be 49 and this is how you calculate what is the area of this rectangle ending at this point 4 comma 3 so this will be 49 that is how i have written here 49 so this is how you do pre-processing it so this is how you do pre-processing it so this is how you do pre-processing it will be calculated for all of these cells and this is the formulation how you do it and this is an example okay so i have written the example as well as the formulation so this was the same thing whatever we have explained here the same formulation as well so after this is done if you want to find any area that can easily be done in this case let's find the area from 1 to maybe 3 1 2 3 so how can that be done so we will be finding this rectangular region area 1 2 3 1 is the top left corner and 3 is the bottom right corner now in this case if i show here then i will be basically finding this region so this should be the last one okay four comma four which is actually your three comma three if you map it then what i will do is i'll take 40 what is 40 is the entire regions area starting from 0 and then i will subtract this 8 from it which is the top area which is unused and then i will subtract the left part which is this one and this will be 9. so how much do i get it is 40 minus 8 is 32 and this 9 is 23 but this region was a common part which was subtracted two times so i'll take this one and add it so this becomes 24 so the area of this region will be 24 this is how we calculate and this is the mathematical formulation for all this you can see that it is just a mathematical expression if you have already preprocessed your matrix and so it takes order of one time for each query so if you have q number of queries then it will take order of q time for queries and for the preprocessing it takes order of m into n time because you have to traverse all the cells so the time complexity is mn plus q and if you look at the prefix sum technique then that would be mn plus mq okay and this one is mn plus q and this is the fastest one and the space complexity for this is mn which is the extra space we have taken in order to contain the area for all the rectangles starting from 0 and ending at that cell okay i hope you will be able to implement the code link will also be present in the description below if you want to join our course then you can connect us on whatsapp and get the details if you like this video then please hit the like button and subscribe to our channel in order to watch more of this programming video see you guys in the next video thank you
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
791 |
hi everyone what's up all good so today we will be solving the question custom sord is so let's see what is this question saying so as you can see from the name that custom salt anding so like we do need to we might need to do some sort custom sorting on a string okay so let's see what's the question you are given two strings order and S and all the characters of order are unique and were sorted in some custom order previously okay so we have two strems order and S and all the characters of order are unique and they were sorted in some custom order previously okay form the characters of s so that they match the order that order was sorted so we need to arrange the characters of s so that they match the order that order was sorted so that they should match the criteria in which the order was sorted okay more specifically if a character X occurs before a character Y in order then X should occur before y in the permuted string so in what order the order was sorted that if a so in what order we need to sort the s that if a character X is occurring before Y in order then it should also occur before Y in s so we just need to do this thing let's see from an example as here you can see that we have order CVA and SS ABCD so we need to arrange the S so how we need to arrange that if C is occuring before B and S so in s as well C should occur before this B should also occur before a and a should be after both of these characters and what about the remaining characters we have formulated a b and c but what about D we have not given any information about the remaining character so we can just put them after these characters in any order for this question if we have been given some conditions to permute these characters as then we need to permute them in that order but now we have been given just that we need to permute the characters in the way that if x is occurring before Y in order then it should also occur before y in the permuted so this will be our output you can see here like CB a okay let's see the second test case that b is occurring before all these characters so B should also occur before all the characters in the output then C then a then the remaining character T so we just need to arrange them in this order okay so like as we have given that we need to do custom sorting so can be just write that salt s. begin and S do n based on some comparator function and we can like Define this comparator function yeah we can do that so let's see here I have already in the comp custom comparator for you that we are sorting this X based on some comparator and what this comparator should be it should just return the character it should just return whether that character is occurring before that character or not right here you can see that we have passed two characters and we should deter the character which is occurring first in the order then on that basis we will be sting our s simple we have just written our custom comparator for that condition so what will be its complexity it's complexity will be n log as the complexity for sorting a string is n log and what will be space complexity as internally the space complexity for the S function is B of log so this will be the time and space complexity for this one but it is not linear so can we reduce this time complexity to linear okay so let's think if we can reduce it to linear time complexity so as you can see we need to keep the track of the characters of s okay if that character is an S and we then just need to add those characters in our answer that number of times let's see what I saying let's say we have kept the track of this character a 1 b 1 C1 and D let's say there are two C's for better understanding let's str s is a b c d okay now we can alate order okay let's see C we are let C okay yeah c yeah C is also here in this so yeah we can add C to our result but how many number of times the number of times it is in the map because all the C should occur before b and a all the C not we are not talking about single C all the C which are there in s should occur before b and a so we that's why we have kep kept the track of frequency here okay very good and now we are at B so yeah B is also in s so simply add that b in our answer stre now a yeah a is also in this so yeah add that a to our answer yeah now we have exhausted over string so then simply add those remaining characters in any order so yeah very simple so as you can see what we have done here is we have just kept the track of all the characters with their frequencies of s and then simply iate order to find if that character in s then we can we will simply add that character to our result that number of times yeah simply so simple we have just permitted existing is so let's see how we can code it so first of all we just need to create a map keeping the tag of frequencies of all the characters of s so I say s and i++ and it will just frequency of s and i++ and it will just frequency of s and i++ and it will just frequency of s of i++ and then what we will be doing we i++ and then what we will be doing we i++ and then what we will be doing we will be just are creating our order to check if that character occurs in s or not let's take care our string result here okay yeah now we need to add that characters till the frequency is greater than zero so if the frequency is greater than zero just a second just like yeah then we will simply add that character to our s string okay simple yeah now we will I create our map again to see if it still that frequency is greater than zero then yeah we need to add that character to is Str okay so here also we need to use the while loop because frequency can be greater than one as well so we need to add that character to all number of time so now at the end we will simply return our this so let's try on this what missed yeah order okay just a second it will be I first yeah cool let's try submitting this what I have done here sorry frequency of order of I think now this T case should also pass I don't know why I'm doing SL SS yeah just a second yeah now let's try submitting it again yeah it's working fine so now we can so this was all for this yeah now let's discuss each time and space complexity so as you can see we are just using this to for storing all the frequencies in all the characters in the map and then we are using we are just adding all the characters to the side so it's overall time complexity will be of N and it's overall space complexity will be B go of 26 as we are just storing Al characters in our map and characters can be only 26 so it is equivalent to Big of one so now we have reduced our time complexity to Big of n okay so this was all for this question this was a very easy intuitive question so I hope you get it if you still have end you can post in the comment section I will surely try to answer them okay then bye-bye guys see you soon in the then bye-bye guys see you soon in the then bye-bye guys see you soon in the next video bye-bye next video bye-bye next video bye-bye oh
|
Custom Sort String
|
split-bst
|
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**.
|
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
|
Tree,Binary Search Tree,Recursion,Binary Tree
|
Medium
|
450
|
995 |
hey everybody this is larry this is me doing a bonus question for extra practice one that i haven't done before by using a random thing hit the like button hit the subscribe button join me on discord let me know what you think about this method do you have a question do you have a problem uh let me know in the description or just come to discord if you have a request or something like this let's see a lot of premium questions haven't done before because they're premium and i have not paid for it but i am trying to do a little bit more practice a little bit bonus practice so let's see oh there must be a okay there we go one that i haven't done before and today's problem is a hard problem minimum number of k consecutive bit flips okay so you're given a binary num away k and k is choosing a sub array of length k from nums and simultaneously changing every zero to one and every one to zero we turn the minimum number of k flips such that there are no zeros in the array so we want to flip everything to one okay and this one i believe the answer will be greedy because if you think about real decisions right that's this is the way i'm thinking about it is that if you're thinking about real decisions then you're for if you're going from left to right say and you see a zero what happens well when you see a zero that means that you have to flip this right if you flip it before in the left that's fine and that's a one um and then of course this greedy will i think would work and if you already get to the last k element and you can't flip anymore it doesn't matter then you can't flip anymore anyway it's just one dimension and you only have one real decision is that when you see a zero you flip it to a one and then the question is you know n is very k is very big so you can't simulate it and then the idea is that we have to be basically um we have to be very careful about how many like i guess we just have to do the flips and then just keeping track in her in a better way right because if we do for every end and um you know and then we look at every next k well that's not going to be fast enough because um that's not going to be fast enough because uh that's going to be n times k and that is 10 to the fifth square so i think one thing that we can track and this is something that long time viewers will know that i do is that these this idea of like defense based thing where um yeah you just have like an idea of flipping on and off at a given time and of course that is predetermined otherwise so all right so let's just say flips is equal to zero and then maybe we have something like for i x and nums or enumerate nums and then the idea here and i'm trying to you know do it live is that if okay and also current is equal to zero meaning no flip side right um so now if x is equal to zero um it's the initial thing meaning that x zero we want to flip it but we also want to do x uh x or current is equal to zero this means that we flip the x bit to from a zero to one or whatever because this is the current modifier that we have right so if this is zero then we actually want to flip the current one we want to flip the current one and then we also want to make sure that when we flip this we unflip at i minus k right because we flip at i and then now we want to um unfit at i minus k or whatever um and we can maybe put it on a yeah we could put it on a deck or something right we could put it on a hashtag or like a look up as well but that's fine i think the deck makes sense here no actually let's just do it on lookup table right so flip is you go to force or like or unfit maybe you want to say so he goes to flip that then basically here we unfit by uh flip of i plus k is equal to um true right and we can't do it multiple times anyway so yeah um and also we have to do if i plus k is greater than n then we return negative one because that means that we reach the end we can flip we can unflip so that's basically the idea um okay and then at the very end we are good except for that now we have to kind of uh get back here which is that if flip of i is true then we then current we have to do this for flipping and i think that should be good um yeah return frips because i think that's a pretty much a steady state maybe i could do some visualization here a bit um okay and maybe i can be right um let's see did i do this well i think i me the only thing that's possible that's wrong is like stuff like this so we flip at the beginning of the next one so this goes to current this goes to oh because we try to flip the last one so if this is equal to n it is okay but now if it's greater than n this is an awkward way to do it but i think this should be good okay well i forgot to uh keep track of these flips so of course it's wrong so yeah here we flipped once so we flip we keep track of the flips okay so that looks good a little bit sloppy aside the greedy algorithm is right and let me give it a quick summary hopefully this is right for us maybe missed some edge cases to a lot of edge cases okay there you go it's good but yeah but basically the idea is that okay so i mean i would say one more time because i don't know that i think a lot of this stuff is in my head i didn't really explain it well but let's say you some um a number or switch is zero right well the only two i mean they're more than two but let's say the only two places to flip it one is that if this is the left hand n and then the other is if it's in the middle of a previous frame well it was in the middle of the previous flip to flip this then there's no decision here right so the only decision is whether you flip it here and then there's this idea of like a forcing function of okay if you get from left to right and you haven't flipped it from the previous before then you have to flip this you have no choice because if you're sliding a pointer goes to the right of this element well then you can flip this element again right so that's basically the idea here and this is going to be as you can see linear time yeah linear time linear space you can probably do slightly better on space but with i this is of n space you can make it all of k space by using a deck like i said but i didn't make that optimization um and i think yeah and that may be the yeah that's pretty much it uh yeah let me know what you think let me know if you tried this problem let me know how you did it and what's your logic oops uh that's all i have for today if you're doing the contest later st good luck stay good stay healthy take your mental health i'll see you later and take care bye
|
Minimum Number of K Consecutive Bit Flips
|
minimum-number-of-k-consecutive-bit-flips
|
You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the array_. If it is not possible, return `-1`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,1,0\], k = 1
**Output:** 2
**Explanation:** Flip nums\[0\], then flip nums\[2\].
**Example 2:**
**Input:** nums = \[1,1,0\], k = 2
**Output:** -1
**Explanation:** No matter how we flip subarrays of size 2, we cannot make the array become \[1,1,1\].
**Example 3:**
**Input:** nums = \[0,0,0,1,0,1,1,0\], k = 3
**Output:** 3
**Explanation:**
Flip nums\[0\],nums\[1\],nums\[2\]: nums becomes \[1,1,1,1,0,1,1,0\]
Flip nums\[4\],nums\[5\],nums\[6\]: nums becomes \[1,1,1,1,1,0,0,0\]
Flip nums\[5\],nums\[6\],nums\[7\]: nums becomes \[1,1,1,1,1,1,1,1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= k <= nums.length`
| null | null |
Hard
| null |
103 |
Ajay Ko that welcome back friends today we are going to solid code problem 103 liner district level and driver surf he start looking details about this problem and its implementation just want to mention that if you really don't solution videos in java and java j2ee interview related Helpful Material 100 Please subscribe The Channel 34 Subscribe to Help Channel So Let's Take a Look Into This Problem Finally Bigg Boss Subscribe Right To Live For The Next Level And Internet Between Please Like Share And Subscribe 10 Days Think In This Direction Soft Ghoshal This Thanks for hearing all like this and alternative like it will go from yagya like this value can see you have to return country superintendent traversal tight s in this case the return 3000 without lupin you hear about cars example share what you know will explain nov22 subscribe what Will be doing what is this basically facebook like this is not created strs endowed for example in all wave labels force wing to this guest channel it's 11111 will have another level enemy meanwhile sweetu note side 90 show will give thiswar level-2 level-3 notice as you can see here a that and this last one will be 1118 will have all like it not seal basically choice after but if you can just to explain you better about like how they are going to solve this super dr traversal Problem Solve Will Give Winners For This Is Must Try Then Routine To Our Q And They Will Strive Processing Cute Level First One Should First You Will Love You Know Loot Late Se Hui Ras Hai He Clear And His Chest Even Imagine This Is Active Result So You Can Put Them Into Love You That Internet Iteration Will Calculate Like U Will Get These Three Out Of The Giver And They Will Put Its Children Died Soon They Will Put 90 Key Word Swift 90 Why Into The Next Level Of Interaction Red Solve Wear Like It Rating this level to you know what we will do it is the color of the so there always put this like water level note swift hui police in ali slideshow in this case hui first free write in to-do list ratij acidity show write in to-do list ratij acidity show write in to-do list ratij acidity show will Just put three nine will take off the like ou will not and shyamdutt cubes and will create and list from liquid 928 so let's do things that 215 earliest and early stage 09-01-2014 level and you have to put its children early stage 09-01-2014 level and you have to put its children early stage 09-01-2014 level and you have to put its children into the curious polling How To You Will Put Children's Day You Can See Ways To Reduce 0080 Have To Tear 2424 And 2812 Food Or The Right And You Have To Fight With Child Is 15th And 72825 215 And Seventy Art Show That Swami 10000 Cute So After The To Were In Superintendent Order Will Just Maintain Of Plant And When Applied This Rule For Example In The Beginning The Flag Isru So Let's Say This Is Applied A Reader Flight Variable Print And Program Swim Trees True I Don't Have To Do Anything And Will Clean This Playlist Listen For This Level The Flag Comes Once We Are Creating List To How To Create This List And Have To Reverse Playlist At The Rate Vanshu Yaar Done Processing This Level Will Just Reverse This List Sunao Then Will Revert Sonam Instituted Of Nau0 Pt An0 Ko Switch Must List Using Collections Reverse Order So Lets You Quickly Into The Implementation Also At The Same Time But They Are Doing Collections Tuesday List Airplane Adhir Who Have Done 2014 Ki Agar Hui Hai Woh Change The Flight From Falls Tutu Sorry Arnav Forms Of Bomb Proof The Flight Is True And Will Again What Do You Mean Equal These Things Like All This For Elements In Next Depression Request 407 Swift And Videos From At Least 100 Tubelight 24 Joe Hair 1028 Hands On Fifteen Global War Calling Of The Elements From The Guy But They Are Creating Least Now in this case we don't have to do anything because this flag is proof will just leave the list acid and where falling off of these elements din you have to you know push the its children for example in to the queue right som is superhit concluded Polling And 24th Have To Sprung 3132 * Incomplete 24 This Is Not To Sprung 3132 * Incomplete 24 This Is Not To Sprung 3132 * Incomplete 24 This Is Not Enough Space I'll Just Write Down Hair Oil Software Just Like 3132 So To The Why Tight And In This Will Go In For Reprint Rights Kuberpur 3334 Thoughts It's Children 100th Death Anniversary End Third Floor Into The Why For Centuries Just Time Writing Because You Know I Don't Have Enough Space Clear And In 3536 Sure Winners By On Third Year Of Baroda Ki Will Have All These And Elements Guest 80 Bowling Again Into This Level For Where Processing Level For Var Flag Comes For Research In That Case Hui Call On This 3138 Element And Have To Reverse Element Site Like It Sony C Robert Blake 3837 Option 1000 Reverse Elements Sudhir Varsh Elements I And Flight Vikram School Reversal Element Software Flying Beast Rule 10 Rush Hui Notary Yearly Flag Comes With Reverse Gear Fly Streams Will Not Reverse Navami Aircraft Flight Vikram School Well Organized List 349 Approach That Then Going To Implement Used A Traversal Soldiers Viewer Implementation Data Have Done So Is Created First Hui Need To Return List Of Interior Space Create And monitor new are list here and in force which give the roti equal to news don't have to do anything it's like you can't do any troubles will just returned empty list is ok and will create a why after in that and they will put the root * Till you hear your data offer will * Till you hear your data offer will * Till you hear your data offer will and Drut in to the key and Yash Vaibhav and they created for everyone to true first year arts and wide open will that basically our on the fire brigade first reversal software hour till who is not attempted keep doing so Will Basically One Five Walk Acid Process in Depression 111 Basically Types of Cost You Will Read How Many Elements of the Ring to the Why Growth Rate Zero Haze Elements Who Want to Process Write in From Fear From the Q &A Creative They Riched the Earliest and &A Creative They Riched the Earliest and &A Creative They Riched the Earliest and New year going to whole middle live one element from the why share and they are going to put 2 sediments left and right side *person bride for example if you were side *person bride for example if you were side *person bride for example if you were falling in the year when will put 24th and 28th right into the curious that soft drinks Air Tight Schedule Today What and What Have You Ever Loved You Have Failed You Means Hui Stuart Broad Were Going to Edit in To-Do List Right The Going to Edit in To-Do List Right The Going to Edit in To-Do List Right The Value of Birth Hui and List Centers and Width Values in To-Do List Width Values in To-Do List Width Values in To-Do List Suitable for All Elements In that level for example for any level to do you will oo have 90 in to-do list right hand ear will keep 90 in to-do list right hand ear will keep 90 in to-do list right hand ear will keep checking our flag just like this falls into river at least the alternate route alternative lips he also has drawn has to do anything so Can remove were slept on it always have to cherish reversal east flat gift morning sorted arjun otherwise added skin and result and its tune change is the flight from drought flood control room in iterations udaipur distic also very important for dixit traversal advertised that Returns Result Height So let's create and share the two examples of wave exam like flying should unite for how the example that you have just been reduced with example airplane 920 820 example that created and this is another example software rock on Trying to execute now our code for both of you for example is alarm set the first to 1000 settings uber example that uses of software testing cars 1080 3837 sure your getting correct result care what they are expecting hair tips and result so let's submit code last two Vowel Code of Kiss Getting Accepted We Thomas Third Iss 1371 Maharana Ne Merit Certificate Actually 134 The Way You Can Solve Pimples and Driver Solution Fashion Cube in Java So Lets You Know of Creativity and Solutions in Java As Well as You Know IS Creator Videos for Java j2ee This Interview Related Material and Equations Please subscribe this Channel Subscription Really Help of Tourists to More People Please Do Subscribe and Thanks for Watching the Video
|
Binary Tree Zigzag Level Order Traversal
|
binary-tree-zigzag-level-order-traversal
|
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102
|
131 |
welcome to me tim solving legal problems this question is called palindrome partitioning all right given a string s partition s such that every substring of the partition is a palindrome we turn all possible pound partitionings of s a palindrome string is a string that reads the same backward as forward so what does it mean to partition well essentially we're trying to well it's literally that partition like put in a break in between these strings but what we want to make sure is that every single substring in here is a palindrome now notice that we'll always have at least one answer which with each individual character is going to be a palindrome in itself right so a is a palindrome a is a condom b is a palindrome so that'll always be an answer whatever string we're given will have at least one answer there but what we want to check is how else can we partition this up to make every single one of these substrings pendulums so we can see aa is a palindrome so one of the other answers would be aab now if this was also i don't know a b then we can probably see aab also being an answer or a and then b being an answer so on and so forth so i think we can intuit here that we can probably write a recursive function to do this notice how the constraint the length is only 16. so probably we don't need to worry about optimizing or dynamic programming solutions we can just do this straightforwardly what we can do is say that we had question aab for example we're going to write a function that takes in the starting position this would be let's say this starting position here uh and we're going to check from this starting position every single substring going on to the end of the string isn't a paladin or not so we know at the very beginning a is a palindrome right so what we'll do is now recursively call moving this up to the second position is this a palindrome and that also is a bondo so now we go to b that's also a poundable so that's going to be one answer but when we go back here to the second recursive call we want to check hey is a b also a palindrome here we can see that it's not a palindrome so that's not going to do anything but when we go back to the first recursive call now we check a is a palindrome right so now we move on to b and that is a palindrome so that's an answer and finally we want to check hey what about aab is that boundary it's not so that would end our recursive call so really no reason to over complicate this let's just start with getting the length of s as well as the output which is going to be an empty string we are going to write a function that takes in the starting index as well as a partial list of what we're building up so far that's going to be these answers here right so let's close that up a little bit first thing what's our base case well our base case is if this starting position the starting index if it equals our n then we've reached the end of the string and that means we've been able to partition this string up so we'll get our um what am i doing here this shouldn't name that something we'll call that so far and we'll put that into our output so far now otherwise if we are not at the end of the string what do we want to do well we have to check from this starting position every single substring all the way to the end right so that will be 4i in range of from the starting to the end what do we want to check we got to check is this a pound room or not so how do we do this if s of i um no i'm sorry not i the starting position that's always going to be the same and i plus one if this equals the same reversed so we can just do this check so this is basically checking is this a palindrome right it is pound girl because if it's not a pound room there's no reason to continue there's no way to partition it at this point so what we'll do is if this is true then we're going to call that first search we're going to pass in i plus 1 as the new starting position and take whatever we find so far and add this substring here so this would be s start i plus 1. otherwise we just continue our loop to see if there's any other palindromes all the way to the end and that should be it so we'll just call our depth for search we're going to start the zero index pass in an empty list and return the output so let's make sure this works one all right i gotta put that into a list let's try that again you can also add it to a temporary list and then pop it off like do a backtracking thing here but i always prefer to do it this way um okay there we go seems to work submit that okay so there we go accepted it's a little slow but i think this is partially because they changed the test cases so it's not actually this bad i believe there's a few things you can do to optimize a little bit but overall it's really this is the accepted answer time complexity is going to be 2 to the nth power i believe uh so it's exponential so it's not great but given our constraints and given the problem i think this is probably the best way all right thanks for watching my channel and remember do not trust me i know nothing
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
128 |
welcome to june's lego challenge today's problem is longest consecutive sequence given an unsorted array of integers nums return the length of the longest consecutive element sequence you must write an algorithm that runs in o event time but let's forget that for a second uh say that we had this list of numbers what is the longest consecutive element sequence it's going to be one two three four right 100 and 200 aren't involved in any consecutive sequence so therefore we're going to return a 4. now if we didn't care about time complexity the approach would be fairly simple right we would just sort our array and then we would go through it and try to find the longest consecutive amount so let's begin with that all we can what we have to do is uh sort our nums but we also need to get rid of any um repeating numbers because if we add all ones we don't want to count all the ones because they're not consecutive right so what we can do is just say make this to a set actually make it into a list set numbs and we'll make this right here then we'll just go through it and say uh we'll keep track of the lengths so far as well as our final output which is going to begin with one and we'll say 4i in range of 1 through the length of numbers let's check to see if the number coming behind us is equal to minus 1 so if nums i minus 1 plus 1 is equal to numbers of i okay that means we should increase our so far by one otherwise we need to reset it let's say so far should equal one here and each time we're going to store our output to be the max of output and the so far that we calculate finally just return our output now one edge case is if not nums then we don't want to return one so we'll say if not nums we'll return zero instead now this would work it's probably the most straightforward approach and actually does get accepted even though it's n log n time and i think the reason for that is because these sort of sorting algorithms are very good in python but say that we want to solve this in oven how could we do that well how many approaches are there to um figure out how to sort this in over time well we can certainly think about bucket sorting but it's just not really viable here because we have such a wide range of numbers as well as the fact that we have repeating numbers so pitching hold pitching holding these into like n minus one buckets isn't really going to tell us anything unlike that gap question so what else can we do um well what if we use the hash if we use a hash for all these numbers is there a way that we could go through it and only care about the consecutive elements count those up and if you think about it there actually is like say that we're trying to find any consecutive length right here we don't want to do that like n squared and check every single number here like the only numbers that we care about are the ones that begin the consecutive sequence so that would mean like for instance one because we see that's the beginning of a consecutive sequence the way we can tell that is just check to see if n minus one exists in our lookup because if zero exists that means we can we should start from zero to count up how many consecutive elements there are not one right and there's only uh here we see one uh 100 and 200 would be the potential beginning of any consecutive sequence right and all we want to do is just iterate then increasing that number by one see if the next number exists in our set and we'll count that count those up and that actually ends up becoming open time because we're only going to be caring about the very first element inside of our sequence okay so to do that let's begin by first creating a set we'll just say um nums equals a set of nums and we'll store our let's see outfit to begin with zero now for n in nums it doesn't matter how it's sorted uh we're going to check to see hey just n minus one existing nums so if n minus one is not in nums we know that this is a beginning of some sort of sequence or potentially right so what we'll do is have uh some sort of temporary number we'll say start so while start is in nums we are going to increase our start by one and once we find that there's no more left we are going to calculate our output to equal the max of output and what would it be it would be whatever the start is well this would actually be the end now at this point minus the n that we're calculating finally just return our outputs and that should be it so let me make sure this works looks like it's working so submit it and there you go so this looks like it might be n square time but actually isn't because of this condition here we're not going to ever go into this while loop for numbers that come in between some sort of consecutive sequence we're only going to care about the very beginning one so this is o event time we do use ofn memory because of our set but kind of unavoidable there are some other solutions involving like radix sword and union fine but i found those too complicated uh really to be worth it so we'll stick with this solution okay thanks for watching my channel remember do not trust me i know nothing
|
Longest Consecutive Sequence
|
longest-consecutive-sequence
|
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Union Find
|
Medium
|
298,2278
|
247 |
hey guys how's it going this is JC who is not good at algorithms in this video I'm going to take a look at 2:47 strobo I'm going to take a look at 2:47 strobo I'm going to take a look at 2:47 strobo dramatic number two a stripper chromatic number is a number that looks like the same we rotated 180 degrees look it up upside down find all this trouble chromatic numbers at the end of it well I think we have done the basic problem before please search on my channel if I interested so first we need to analyze what our struggle chromatic numbers right start for all the digits 0 ok 1 yes and of course if one and two now three four no five no six and nine yes seven eight so yeah this is the struggle right all the struggles so with this is what 0 1 we could actually get a pair can talk more pairs right 0 it is 1 yeah 8 yeah and then 9 6 cool so now if we're getting that getting the end of 1 of course you only have three options 200 0 1 8 right you forgetting to well it's a little different right - it's a little different right - it's a little different right - it should be some of this 0 is a 0 Z 0 or 1 or 8 or not 6 9 or 9 6 right now what if we have 3 4 3 digits at the center the digits in the middle is a lot right it doesn't have pairs so it must be 0 1 8 based on this so and for this 0 1 8 we need to push this put this pair in it right so we put a 0 here or one put the one to the head at where you put 8 or this so these what generates the 3 right if this for we need to put the extra pairs and 2 right to the combinations at the end with 2 so the idea becomes clear to us is that all the combinations of a debt if n is aa it means at like we say this is pairs this is singles if it is our where we could each pair 2 and minus 2 all combinations at n minus 2 right if n is even oh yeah even it's the same so if n is 1 singles all right if n is 2 pairs and then for 3 above we just put pairs to the N minus 1 right because if it is a Strobel pair the head and the where it must be struggle so yeah this is it there is something called n minus 1 mmm we need to calculate the 2 n so n minus 1 is still needed no actually because we were Plus pairs if it is odd they will start from one if not if started with - ok from one if not if started with - ok from one if not if started with - ok cool so let's start so these basic case could be defining with cost right so singles you say it's 0 singles 0 1 8 past pairs 0 1 8 6 9 6 ok now let's determine nessa Terman costs start okay the bass sea bass because if n is odd which means we start from singles if not we've got start from pairs Oh Paris not Paris sorry I really want to go to Paris it's espares now so we will now do what we will add to n right so let okay so the cut of the result and base result equals okay we just use Center result singles slice Paris slice this club / 0 cool so we got the base which is a result so while result then smaller than and we've already chose the right okay right base so this will not fail oh okay we stop issues end when the result has the exactly same and then exact meant a ten mm-hm mm-hm mm-hm so by do you just push the pairs in into the current combination right well how we do this we will put every time we will get it again get the elements out and just and then push them back in well rather than a shift we carry it but shift is not fast enough I think we were just to do a map thing and create a new array yeah it's so I'll use let so result equals result man for each item which is the string oh this is pairs right oh god this is right this will be I will join it up hmm ma'am I am joined cool now so for each combination what we do we'll push okay no steer up to use map okay I'll say cost new Acosta how they appended empty so let me let combination of result and we will push the pears in it right so for that care of pairs then day to push here 0 plus pair oh I don't need to join man we could just use 0 so join is always some time okay I don't need to join now could just use that director that's access with the index I'll set up a spare one right let's say they say we get in for the first get two and then for each zero we would push the push a zero in it and one in it and 818 it six nine in it all right pair 0 plus pair net it should be combination yeah push it and after this is done we update the result to go right in equals new open it cool and then we return the result so if this should be right 1000 we got hmm so actually this is a special case if n is zero to return empty cool it's why the code run answer what and 0 is not hmm ah so the numbers couldn't should not start with 0 uh-huh ah I see uh-huh ah I see uh-huh ah I see so this is not possible but for single zero is okay I see so this is right aha this is tricky this is a mecca the event is the teaching land is not the result man let Ned supplement if necessary we updated while sickles - but actually did these let's sickles - but actually did these let's sickles - but actually did these let's see what happens - forth there's a see what happens - forth there's a see what happens - forth there's a problem with zero actually so you I need to add in Oh No why and let pass you I am so stupid - this should be right but it stupid - this should be right but it stupid - this should be right but it should fail actually yeah we got this but you see we don't remove the 0 but 0 to use and is actually that it at the beginning so the only problem is that when we are upend the pair we should not upend the 0 it's in it right so if here equals to 0 just continue it's your right cool let's try submit hope it works man yeah the 0 is nasty okay I'll say I do it very nasty I'll say this these the pairs and we couldn't remove this but here's a special case is special for 0 if n actually happened to be good as here too it's even and the attention to our shift Oh the result oh we only push two pairs this end I need to shift 0 right and then for each pair will add them so this should be right great that's right code I see we got one answer yeah why ah yeah I see so uh I'm stupid he actually did condition it's different and I thought we conditioners we only append the non-zero pairs if this is not the last non-zero pairs if this is not the last non-zero pairs if this is not the last round right so if pair is 0 and if it is not 0 if this is 0 and it is last patch sewn L plus 2 equals to n if this is a special one we continue we don't add we don't atmosphere so if your first four for the even case this is not good anymore I think this should be empty right this is better so for the even case it should be 0 right now we get 4 2 will just append this in but this is not padded so we keep this for but for you forgot for when we get to this is valid mmm this should be right submit again cool yeah we're accepted ah this is not easy this is not simple and I thought man I didn't find the right logic here the right logical amazing is 0 is actually this should be not add to the outermost right almost but almost round of appending so this is the case if this 0 is 0 and this is the last round then we ignore rather than this is fine to attend fine to add it and I also made a mistake that I took the base case from take this as the base case for even numbers but it turns out that the empty string is the base case so it will help we figure mean this now also that's all for this one so the time there's nothing just okay that's just and I sometimes complexity well if the time actually becomes how many pairs are they right wow it's a roughly you be roughly okay it is even every time it will be Oh like a n it will be a four even I'm even numbers a n minus two times 5i for odd numbers a n equals a in twice two times five so roughly it will be for n e to a Phi to the power of n space we use an extra Ray to store the singles and pairs but basically we don't use auxiliary space so it's custom cool so that's all for this problem hope it helps see you next time oh we're faster than 100 wow this is first time I saw this let's try to take a look at the detail wow we're really fast compared into the next one alphabet dependency what are these guys doing Wow of this one actually do what we did do what we do and it's uh yeah okay so that's all for this one hope it helps see you next time bye
|
Strobogrammatic Number II
|
strobogrammatic-number-ii
|
Given an integer `n`, return all the **strobogrammatic numbers** that are of length `n`. You may return the answer in **any order**.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** n = 2
**Output:** \["11","69","88","96"\]
**Example 2:**
**Input:** n = 1
**Output:** \["0","1","8"\]
**Constraints:**
* `1 <= n <= 14`
|
Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
|
Array,String,Recursion
|
Medium
|
246,248,2202
|
3 |
hello everyone welcome to the channel today's question is longest substring without repeating characters we are given with a string we need to find the length of longest substring without repeating characters so let's jump to the pendant paper and let's see how this example work and how we can find the solution for this particular question so the question is asking us to give the length of the longest substring without repeating characters so for that we need to find out the substring which do not contain any repeating character and out of those sub strings I need to find out the largest one and then I need to return the length of that particular substrate for this question brute force solution will be I will take out all the potential sub sayings and then I will compare all of them I find out the larger substring that do not have any repeating character but problem with this solution is of n cube which is pretty expensive and not code because for that way I need to take out all the potential sub strings in this way I will take loops then I will take another look to check whether it contain any repeating character or not and then I need to find out the length so what can be a better solution if I will start from a and while moving forward in the string I will keep checking whether the character I am at right now I have seen it before or not so what do I mean by this is suppose I am at a so I'm seeing a for the first sign I will add 1/2 mile and then I came sign I will add 1/2 mile and then I came sign I will add 1/2 mile and then I came to be B is also coming for the first time I will add 1 again I come to see she is also coming for the first time I will add one more to my length then I will come to a but we have seen a before so for that so as I was moving forward I will keep taking my starting point and the index I am right now so whenever I will encounter something which I've seen before I will increase my starting point by one so now my starting point to start from B and my eye and set a so this particular technique is called sliding window technique so we will use sliding window technique but now again the question arise how will gonna take care of but now the question arise how will come to know that whether this particular character we have seen before or not so for that we will use another data structure and we will use dictionary for that so while moving forward I will keep checking whether this character is in the dictionary or not and if that's the condition I will increment my start point by one and at the end and I will take out my length by I - start plus one take out my length by I - start plus one take out my length by I - start plus one so I will gonna be my index I am right now start will gonna be my start point and I'm adding one because I will be taking a for loop with range so our range start from zero so that's why I am adding one so let us write the code I am pretty sure after saying the code you will be more clear with the quotient once we will be done with the code we will do alright and for that particular code so let's write the code first of all let's check the base case if length of string is zero then we will simply return zero and we will take a dictionary by name of map and let us take the max length and start point both will be pointing at zero for I in range the length of s if si in map and start is less than equal to value of Si then start will gonna be map si plus 1 and max length will be max of max length and I - start plus 1 map equal to and read things we will return next what I'm doing here is I first took our dictionary then I did two variable max length and start then I looked through the string as then I'm checking whether particular character is in the dictionary or not and if start value is less than or equal to the value of that particular character in the string if that's the case then I am increasing my value of start else is that's not the case I'm taking my max length which will be the max of max length and my new length which is I - char plus 1 so how I'm which is I - char plus 1 so how I'm which is I - char plus 1 so how I'm calculating this is I'm at pike position - the start point but I am adding 1 - the start point but I am adding 1 - the start point but I am adding 1 because rain start from zero not from 1 and at then I'm just returning it back its work perfectly fine if you will copy the code and paste you to the blade code it we're going to definitely work you can find the code in the description below let's do what Ryder I have written the code and I have taken the example and I have the dictionary with me so I am at a I check whether the a is in the dictionary or not so that's not the case so I came to else so I will calculate my max length so my max length is 0 initially so I'm calculating between max of 0 and I which is 0 - it should be of 0 and I which is 0 - it should be of 0 and I which is 0 - it should be minus start which is zero plus one now my max length is one I came to be I checked whether Bay's in the dictionary or not so it's not so I will again calculate my max length and that will come out we do and I will come to see I will check whether sees in the dictionary or not so again it's not in the dictionary again I will calculate slant then this time it will become three and I will put C into the dictionary then I came to a then I check whether a is in the dictionary yes it is then what I will gonna do I'm gonna set the start equal to value of si which is zero plus one start will be one now instead of zero then I come to be that again checked it's here now my start will become two then I will again come to see it's there now my start will become three and in this way I will keep calculating my max length and I will keep incrementing my start point and at the end I will written the max length so I hope you understood the question if you liked the video please give it a thumbs up and if you have any question you can email us thank you so much for watching the video please don't forget to subscribe
|
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
|
465 |
hello everyone this is official sendo today let's look at the problems uh lit code for cd5 optimal account balancing if you like my videos please subscribe my channel and you can find the complete proper list in video description below let's move on the problem so in these problems um we are given a list of transactions then we need to uh set up all the depths in the minimum transactions uh let's directly jump to the examples so to understand problems so first example is very straightforward uh people zero need to give people one ten dollars and the people two need to give people zero five dollars so there's not any uh optimization we can do so we're directly using the uh two transactions to set up the depth as given by the input the more complex part is in example two uh here uh i make this make a direct graph to this great province person zero need to give person one ten dollars and one need to give zero one dollars and uh person one given person to five dollars person two to give them person zero five dollars so um i think uh once really straightforward idea pop out to kind of uh so simplify this graph is we have a table for each person right so then we can fill the table based on each transaction first for example we start with the first so uh person zero give our person one ten dollars so we are making the positive numbers as the dollars uh the person need to give out so uh if you look at the graph so person zero will give out ten dollars receive one dollars and receive another five dollars so eventually we'll receive uh oh sorry he need to give out four dollars and person one he will receive ten dollars given one and uh give another five eventually he will receive four dollars and person two uh receive five and give out five it ends up zero dollars so based on this table we can easily find we only need a person zero given four dollars two percent one then we setting up the total depth so the minimum transaction will be one so let's look at how we utilize these uh naive ideas to come up to the final solution as we're talking before so at first we can generate this table back given the examples here and we can generate the total tables right just iterate all the transaction let's see how we end up uh in the final one um so at first step or person one to give person uh zero need to give person one ten dollars and present zero positive ten percent one minus ten um then come to the next person zero on need to person wanting to give person zero one dollars so person zero since he's received one dollars it becomes nine and the person one give out becomes minus nine then after we finish all the transactions we will end up present zero need to give out four dollars and the person one need to give minus four and the percent to zero for this example is pretty straightforward to figure out however um for some complex uh input you can come up with very difficult tables which we need a step two uh in step two here uh we do the deferred search um for this balance list so here is examples uh person zero need to give us three person one two seven persons two need to put five um person three to receive seven um person four need to receive eight dollars so the way we uh do the debt research is we start from the first index then we are looking for the later index uh which value is the negative side of the current counter values so here we have minus seven minus i and we're trying to uh make current peoples as zero uh total amount um so basically is change the total status of the balance sheet uh for these ones if we change to zero which means we be giving the three dollars to this one so this guy will become minus four or we can try uh for these guys become -5 um for these guys become -5 um for these guys become -5 um then of this guy becomes zero we can move to next one and the next one and until the whole sheet four becomes zero we can calculate the total transaction let's look at the how we cover the formulator whole search trees by trying to order the way to finish transactions so when we first start of course our transaction right now is zero now we trying to make first people say zero so here is we given the uh minus seven three dollars so it becomes minus four and uh all we can try even the last guys three dollars become minus five here we all take transaction one uh let's go next uh given the time and space limitation i just uh skipped this part but we are reached the end of those branch of the solution so we come to the next right so um we try to make this seven as zero so we can either give minus seven or given minus five so here we give us minus seven so minus seven become zero here if we given seven dollars to the last guy it becomes two so at these steps we are spend two transactions and for this direction we only have two nonzero values so we just give this five to the last one eventually we will settle the depth um so for this one uh we start from five here so there's only one have negative size here so we only need to give 5 to -7 so this becomes -2 5 to -7 so this becomes -2 5 to -7 so this becomes -2 and then we do another transactions with a second depth so when we search all the solutions for depth research there's usually optimized way to pruning the branch so based on the one uh key observation we can put in this branch which is that um we are also kind of those like if we give seven to minus seven here both two people become zero right so this is definitely the uh optimal solutions we setting the two people depth to zero in only one transaction so this is why we want to go into this direction but we want to pruning this direction so it turns out the minimum transaction is also in this direction but not in the directions we are already pruned next let's look at the code um so when we start we have uh implement the first step on which is to generate the balance list so here we have a hash map here to for each peoples we calculate what's the total depth you need to either to give out or receive and then we formulate the balance list by using hashmap since here we decide new variables uh data container here so space complexity can be called for n we here we complete all the balance list since we need to iterate all the array so computation capacity becomes bigger of n after we complete the first step we will start the second step which is definite search so uh so the kind of difference was that i described in the slides before which is from the top to bottom so here that first implement is more based on the bottom to top way which is the backtracking so in gears when the index go to n we just end the whole um defer search which is the end condition of the backtracking or the location condition um then if the balance list value equal to zero of course we don't want to use this uh to balance other people's value since this guy's always zero so we directly jump to the next one so next we come to our for loop iterations we figure out all the later value which has negative sign of current value then here we update our minimum transactions based on compare with the current local minimum and the compile with the minimum transaction of later plot which is the bottom to top a way to do the backtracking here we plus one because here's the cost of one additional transactions um then next we if we find the current um the way to balance the sheet r is equal to zero uh that means we can approach nato solution right as i mentioned in previous videos so we directly break here because we already find the uh the minimum transactions for these statues um here also uh please pay attention so um previously we changed our status by um using current um balance solutions then here we need to recover it back so this enable us to find the other solutions so this is the basic templates for that first search uh backtracking version so eventually we finish all the iterate all the values in the sheet we directly return the minimum transaction how we estimate the computation complexity for developer search i think one way you can consider like as these so uh for to make order status think about arrays binary array either one or zero we need to make some numbers from one to zero or zero to ones so this comma two of two power of n total status right this is the search space of the problems and for each um solutions we also need to do the big of n to complete this solution to compare these four loops in worst case right for each status and we have big of n for loop iteration so eventually the worst case of the default search complexity will be 2 power n and then multiply n then the total uh computation capacity is uh we take the maximum big of n and the big of two power multiply in so that will be bigger of two multiplying my plane yep okay so that's the uh what i want to talk about today and please left your comments and suggestion as below videos and see you next time
|
Optimal Account Balancing
|
optimal-account-balancing
|
You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`.
Return _the minimum number of transactions required to settle the debt_.
**Example 1:**
**Input:** transactions = \[\[0,1,10\],\[2,0,5\]\]
**Output:** 2
**Explanation:**
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
**Example 2:**
**Input:** transactions = \[\[0,1,10\],\[1,0,1\],\[1,2,5\],\[2,0,5\]\]
**Output:** 1
**Explanation:**
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
**Constraints:**
* `1 <= transactions.length <= 8`
* `transactions[i].length == 3`
* `0 <= fromi, toi < 12`
* `fromi != toi`
* `1 <= amounti <= 100`
| null |
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
| null |
217 |
hello everyone welcome back and today we are looking at question 217 which is contains duplicate the question is straightforward we are given a nums array and we want to see if this array contains any duplicates if the answer is yes the output should be true but if all the numbers are distinct then we don't have any duplicates and we just return false okay so example one gives us one two three one we can see that we have one here and we have another one here so we have duplicates so the answer would be true now example two gives us one two three four so all the numbers are distinct which means we don't have any duplicates so the output should be false and in example three we can see that we have a lot of duplications going on so yes the airport should be true now let's go to the blackboard and see how can we tackle this okay so i have created an array that contains two three one and we can clearly see that we have duplicates one here and the one there looking at a slow approach a brute force solution would be something like the following at each number we want to check if we can see this number again in the array in order to do this we need a pointer to point at the number that we are at and we need a pointer to move through the array and check if we have a duplicate so for instance we are starting at 2 and the other pointer will be here is 2 and 3 the same no this pointer moves here is 2 and 1 the same no this pointer moves again here is 2 and 1 the same again no this pointer reached the end so this is time to update both pointers now the green will start at three and the blue will be next to it at one so is three one the same no is three and one the same no again we reached the end so update the two pointers now the green will start at one and the blue pointer will be next to it is one the same as one the answer is yes so we have a duplicate and we just return true this approach will require two for loops one for loop for each pointer so we will have an instead for loop and the time complexity would be big o of n squared where n is the number of elements in the array this approach is extremely slow and now let's look at how can we optimize it so for the optimization we don't want to use two pointers we only want to use one and we only want to move to the right without going back and forth and back and forth so let's imagine we have a big box right here and this box will contain the numbers in the area so at each number we want to ask the following question does this number appear in the box if the answer is no we should add it so in this case the box is empty is two in the box no so we add it now we advance the pointer is three in the box no so we put three in the box and we advance the pointer is one in the box no we add one then we advance the pointer is one in the box we check the box yes we find one and we return true we have duplication so what is exactly this box so let me remove the box word and write hash set this box represents a hash set is basically a collection of unique elements in other words a hash set contains some values but it does not allow any duplication why is this hash set so important for us well because one the searching function takes constant time two the insertion also takes a constant time so using a hash set we can make our algorithm extremely fast and the main two functions we will use are called contains this function is used to see if an element is in the hash set so it contains and to add something to the hash set we use the function add now let's see how can we do this okay so as we said we will only have one pointer and now we will ask ourselves does the hash set contains two no so we will add two to the hash set now we advance the pointer does the hash set contains three no so we can add three to the hash set advance the pointer does the hash set contains one no we're going to add one okay so now advance the pointer does our hash set contains a one well yes it's right here so now we can say oh so we have duplicates if we try to add this one we will have duplicates so we just return true and we exit from the function now if you ask what happens if you try to add a to the hash set for instance let's try to add another one the hash that will simply take the duplicates override it and add this one so in the end we will only have one and no duplicates now let's see how can we implement this in lead code okay so we said we need the hash set and our hash set will contain integers since the array contains integers so we need the hash set as we can see our hash set contains integer so hash set and i will call my hash that set new hash set and now we will loop through all the numbers in the array so for int none inside of nones we will ask ourselves one question does our set contains this num we said the function is called contains so if set dot contains none we have a duplicate so just return true okay but if this is not the case then we don't have this number in the hash set and we need to add it so set dot add and when this for loop finishes and if we did not return true then at this point we have been added all the elements in the array in the hash set and just return false since we don't have any duplicates so return false let's run the code now let's submit okay so let's look at the time and space complexity starting with the space complexity we see that we use a hash set and in the worst case we don't have any duplicates so we need to add all the numbers in the array inside the hash set assuming we have n numbers in the array the hash that will contain n numbers so the space complexity would be big o of n now let's look at the time complexity we said that the contained functions require constant time and the insertion function also requires a constant time but we use the for loop to move through all the numbers in the array assuming we don't have any duplicates we need to move through all of those and numbers so the time complexity would be big o of m i hope you guys enjoyed the video best of luck to you and see you in the next one
|
Contains Duplicate
|
contains-duplicate
|
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
|
219,220
|
424 |
so initially a b served as a potential candidate of my substream later on it was replaced by Babb which become a lot which became a longer substrate so the intuition which I'm trying to talk about is this is the core formula which you have to use so today let's talk about this question called longest repeating character replacement it's a very interesting question on the application of sliding window algorithm I've already covered a bunch of different questions on sliding window um the playlists link will be in the description so please check it out I've also covered the theoretical aspects of sliding window how do they work and yeah let's begin so let's try to understand what this question is talking about so we have been given a string s and an integer K we can choose any character from the string and change it to any uppercase English character so the string is having all the uppercase letters and this changing of character can be performed at most K times like upper limit is K maximum K times you can of course do it less than K also but maximum you can do K types after doing this you have to return the length of the longest sub string which contains the same letter which you can get after performing the above operations so the operation that we have to do is choose a character and change it to any other upper case and do it two times or three times whatever the K value is so and do it at as many number of times as K is given like maximum is that much which we can do so if we do that uh after doing that we have to return the longest substance if you take a look at this example a b k is 2. so if we change n the 2 is to 2 B Because K is 2 so I can change a to B twice I will get the longest substring with all the B's B will be four times so that is why the length of the longest substance will become four it can also be happening vice versa like you change the two B's to 2A so you get Four A's in the second example so if you notice this up string if we change B to a I'll get all four A's so the length will become 4. if you notice this substring b a b if I change this A to B I'll get another longest substring b a b or if you see this substring a b if I change all the uh the B to a just one and then I'll get Three A's but of course the length is three but we've already seen a longer substring so then I'll return the longer substrate so this is the entire gist of the question we have to change the letter to something opposite some other letter but the constraint is we can do it only K types now let's understand what is the thought process to solve this question so what can be the thought process to this so what I was saying is imagine this being a substring or these entire thing being a substring or even this being a substrate if you notice when I was saying that I have a b I'll change this B into a and I'll get 3 is and that becomes my current length and I'll store it in some Max and I'll do a math.max and get the Max and I'll do a math.max and get the Max and I'll do a math.max and get the maximum depth so I just told this I got it Max is 3. so the thought process behind doing this is something like this so I will take three variables mainly what are the three variables one is I want to see my current window length where am I right now so in this case a b my current window length is 3. second thing I want to see is maximum repeating character so in my current window length which character is repeating maximum times if we consider only take the substrate a is repeating twice so what is the maximum repeating characters count is two window size is 3. and what is K given to me is one can I say that if I have the window size and from the window size I will remove my maximum repeating characters 3 minus 2. if I do that I'll get k can I say this if 3 is the size maximum repeat is 2 3 minus 2 I'm getting 1. okay let's see another example I have this string b a b window size is 4 maximum repeating characters count is B 3 what is k is again one I get one here so the point I'm trying to make is If I subtract my window size minus Max repeating count I am actually getting a certain expression which I can call so what I'm saying is if I do this window size minus the max repeat I will get my number of non repeating characters which need not be K always it is K over here but it need not be always so what is the expression I'm trying to create window minus Max repeat gives me the non-repeating count what I have to check non-repeating count what I have to check non-repeating count what I have to check is my non-repeating count has a upper is my non-repeating count has a upper is my non-repeating count has a upper bound of K so in case this becomes greater than k then I have to slide the window so those who have done at least two three questions on sliding under will understand what thing I'm trying to talk of well if not please watch sliding window basic videos and then come to this little Advanced question so if the non-repeating character count becomes non-repeating character count becomes non-repeating character count becomes greater than k i Slide the window and adjust it but if the non-repeating count if the non-repeating count if the non-repeating count exactly equals K which is in this case my non repeating count 3 minus 2 it is exactly equal to my use case what I want so I'll consider this and put it into my max length available so initially a b served as a potential candidate of my substring later on it was replaced by Babb which become a lot which became a longer substrate so the intuition which I am trying to talk about is this is the core formula which you have to use you have to take the window size you have to take the max repeating character count and subtract it and check if it is greater than K Slide the window if not you just take the maths the code and everything is already given in the GitHub description the code and everything is already there in the GitHub repository is there in the description I'm not going to put the code I'm talking about the thought process over here we'll also do a diagram to understand what I'm talking about so this is the input that we were talking of and K is equal to 1. so uh what was the expression I so let's do a let's talk about the approach step by step and we'll do a diagram also this is the input this is I've already written the expression which I was saying is taking the window size minus the max repeating count will give me the non repeating count and then we'll see how are we using it so let me write step by step what are we doing the first step is you have to initialize the variable so we'll have a Max repeat is equal to 0. and you will also have sliding window right so you'll have the pointers left which will be 0 again right which will be again 0. so all the different initialize the max length you need everything will be equal to zero now we also need a hash map in this case we'll initialize a hash map why do we need hashmap because we need to keep a track of what is repeating okay so this is the step one of all the initializations is done then we will run a loop we loop from I equal to 0 to n so I'll call this the right pointer and then what we have to do is first we'll take the current character and add it to hashmap you'll have this hash map and I'll take my current character like a I have and add it to hashmap this is going to store my count and this is going to store my character so I'll have a hash map of uh character and integer okay so I've added to hashmap now how do we calculate the window size will be denoted by the two pointers the left and the right pointers this is going to be right minus left plus one so if I have two characters like this 0 1 what is my window size is two so my left pointer will be here my right pointer will be over here so right minus left is 1 plus 1 is 2. so this is my Windows X this is how I will get my window size so that is fine next is I have to get what I have to get the maths repeat count where am I right now wherever my right pointer is it is a loop it's a for Loop which is running so where am I right now my right pointer is wherever my right pointer is I'm in there so the character which is pointed out by this can be the character which is my current character which is C URL let's see this is my current character so max repeat count is nothing but your hashmap dot get you're going to get from hashmap whatever your count of this character is or it can be the existing Max repeat count it's like uh if I write the exact expression into something like math dot Max of your max repeat count or you'll get from hashmap whatever the count you have as of now whatever your current character is that counts so it's like is your count of the current character more or the maximate count which you already have stored whichever the case may be so I need my window size I got the max repeat I got now I'm just trying to get the mat dot Max and get the max repeat count goes what is the final thing I have to do non repeat now to calculate so I've already told window size minus Max repeat next step is now you have to see like if or uh it's like uh while kind of a condition while why they are non repeat as long as it is greater than K I don't need it so just slide the left pointer if I write the expression of doing that it is something like so to sign the left pointer so what it means is from the hash map you have to remove that entry or not remove that entry I'm so sorry from the hash map whatever character is being pointed by your left pointer left to just reduce it by minus one okay I'm not discussing the code over here so we'll slide the left pointer it need not be a while loop it can be an if condition also after that you just have to update the maths again the math dot maths your current Max what do you have and your window size so these are the steps now we'll do a diagram to understand this in Greater detail but I run on this input a b a okay K is equal to one so what is the longest substring that you can get what is going to be the length of the longest substrate if I replace this B with a all my A's will be there so I will get Max equal to 5. or if you think this substring also initially if I replace this B with a I'll get 3 is sequentially or if I take this up string if I replace this V with a I'll get four So eventually I'll get 5. so how is this going to happen so I have my hash map over here so I'll add a so first thing is we are looping right so my left pointer is here uh my left is here my right is here I added a in my hash map I made my entry as one so I have put an entry that's my current character so after adding to the hash map what am I going to do I have to check the window size is One Max repeat count is going to be the same itself it is one so 1 minus 1 is 0 so 0 is of course not greater than K like we have said this is not good so what we will do is our Max variable is now going to be manipulated to 1. so it's just one character one is Max I'll add another character so my right goes and my a becomes 2. same drill window size is 2 a this is the window size what is uh okay let me also write the max repeat count so max repeat count initially it was 0 because we got in one character already so it became one now when I have my right pointer in the second a now there is two ways so in this case what is the window size is 2 what is the max repeat count Max repeat count here we have said that is going to be Max of current whatever count you have or the current characters count since you have two a's the max repeat count is overrated so it becomes 2 so Maxim bit count is two window size is also two minus two zero again the same so my Max is updated you got it right because two window sizes two Max repeat is also two non repeating count is zero is not greater than K so I will come to this and I'll update the max so my Max is now two now B comes so I'll have an entry B and 1. now what is the window size now window size is three what is the max repeating count initially I have 2 for my current character I'll get hashmap.get of character I'll get hashmap.get of character I'll get hashmap.get of current character current characters count is one only so max repeating count you can understand now right which character has been repeated so far the maximum number of times a has been repeated the maximum number so max repeat will still remain as 2. so window size is 3 Max repeat display 3 minus 2 is 1 greater than one no but one is equal to one okay so I'll update the max now because my Max is initially two and my window size has increased so I got a greater length now so my greater length is this became my first candidate where I actually did a replacement okay now uh okay my right was here so right will now be over here again a is Count has to be updated so a becomes 3 window sizes four what is the max repeat count now Max repeat as I said it's always the current characters count or the existing Max 2 is the current character is three a is three so max repeat will get updated to three so window size is 4 next to it is 3 4 minus 3 again satisfying it is equal to K but of course not greater than K so in this case we are not getting any kind of a condition which is uh greater than K okay it seems so again the Max gets updated so max was three so window size has become Force Max will now be 4. my Right Moves ahead now a again is added a becomes 4 so Max repeat the window size is now 5 Max repeat is again updated so what is the maximum repeating character so far the A's has been repeated the maximum number of times so max repeat count has to be replaced it will be replaced by 4 5 minus 4 is 1. again not greater but the Max has to be updated so my window size is 5 Max current Max was 4 5 is greater Max became y so hence we have completed the string and we got our output S5 so in this way we got the length of the longest substring by replacing the character so I'm hoping this question is clear to you guys the code is in the description so please refer to that thank you so much for watching foreign
|
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
|
137 |
Welcome to Coding Makeover. Today we will solve question number 137. The topic is single number. It will be repeated three times. We have to find D single element except one and that will be our result. We have to solve this question in linear time complexity. If You have seen my previous video ' Ek time tha hai se number 3 times' account offset se number 3 times' account offset se number 3 times' account offset and unset beat and H position can be seen here, we will check if the repeat is set, then we will sum it and divide it by 3 from the last one. I have tried three times. It's 21 times First of all, we will take a variable, we have to process the result, so we are running the look, OK, after this we will define once and will do total, I will release the last name I founder
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
1,909 |
all right guys so first let's get into it so here we have 1909 remove one element to make it make the array strictly increasing so let's just read over it once given a zero 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 1 minus I minus 1 is less than nums I for each index I uh actually I is greater than or equal to one and less than numstat length so the first thing I like to do is okay what is our input is a integer array nums all right and then what are we returning we're returning in Boolean so we know we have we're taking in uh our input is an array and our output is a Boolean all right and then the other interesting part is their definition of strictly increasing all right that means all right no uh some nums I cannot equal numbers hi plus one so then uh looking at example one we can see okay so nums is equal to 1 2 10 5 and 7. all right and so we know that if we can remove 10 then 1 2 5 and 7 is strictly increasing but if we come down here to example two we see two three one and two so we can say okay let's try removing three and we get two one two that doesn't work or we can say okay two and we remove the one and we say two three and two it doesn't work either so we get false and then we have example three nums is in one here since they're equal cannot be removed so we have multiple options going uh to solve this one we could do is just Brute Force we could start at the start of the array check if the rest of the array minus the one you're on is strictly increasing so for example one we could say okay if we say we're checking uh I equals zero so we don't count this we say it's 2 10 5 7 strictly increasing no okay you keep checking so we say okay what about 11057 is that strictly increasing no okay so what about one two five seven oh okay we found the answer check all right then we'll return true and then we can say okay uh but if we get all the way to the end we've checked seven right that won't work so that is a Brute Force solution but that is we're checking n minus one uh indexes uh yeah n minus 1 items and we're checking them n minus one times so that gives us a Big O uh N squared so that's also not ideal so let's explore a different way so now what if instead of doing the Brute Force what we want is a single pass solution right so what we're looking for is exactly one area where there's an issue right in this array it's true because there's one place where the condition is not met in it we can remove that element to figure out if it's strictly increasing so we can say so the way we would do this is okay so we're going through the array if we say what is one less than two yes check is two less than ten check is ten less than five no so then we say okay this is I equals two let's remember this all right and then we say is 5 less than seven check so we'll remember this now we have one two ten five and seven all right we know that this is strictly increasing so now we have the issue right here right now there's two ways we could do this we could say okay we could say one two and we could take out the five and we could say it's ten seven right or we could say it's one two take out the ten and then it becomes five inside so what we need to identify is okay does this work if it works good if you're not then no so this doesn't work but this works check but let's try that same process on uh example number two three one and two all right so we say okay it's two less than three it is we're good 3 is less than one no so our I is equal to y all right and then we say it's 1 less than two check so we know that this is good and we know that this is good so we need to start with three so we can we have two options again all right so we have two three two or we have two one two and neither of those work so if we return false so how would this work income so then we come take a look at the code so here we have that same thing that Index right this is the one we're tracking so we say okay our index is equal to negative one right so then we enter our array we start at zero and we're going to one less than the end because if we were to check seven we can't check the number after seven it doesn't exist we'll get a null pointer exception so that's how we get around that so we get in so if we say okay if nums I is greater than or equal to nums I plus one so that's the exact opposite of what they told us here so this is the definition they gave for it strictly increasing we're saying okay if it doesn't follow that then what we do is we get into this if statement now here it checks is this equal to negative one if it's not equal to negative one that means we've already found a different spot in the code in the array where it doesn't meet the condition and therefore there's two spots that we need to remove from and we're only allowed to remove one element so we say okay have we found a different spot to remove from and we have it so we return false uh we have so we return false right away and that's the end of this program if not then we say okay well our index is equal to I this is the problem area and so we hop in and so then how do we check you know we have to check if it's if either of those two cases that we talked about earlier are possible so then we say okay is it less than or equal to zero what are the cases here either I is negative one or I is equal to zero so what does this mean if it's negative one that means there were no problems right and so it's already almost for increasing if I equals 0 then 0 is the problem but if we know that from two so if we have 10 2 3 4. then we know that okay so we know this is all increasing we know that this is the problem so we can get rid of this and the rest of it is already increasing or we can take a look at I is equal to the length minus one and minus 1. oh n minus two that means so or we can say that I is equal to length minus two that means it's something like one to 2 5 7. 3 so we've identified that this is the problem area where we know that all the way up until here is increasing but something happened right here and so we can just remove that because there's nothing after it and we know the rest of the array is all clear so we get we cover all of our cases where we can't compare the two sides of the probability so then what we say is so let's take a look at this let's just bring up one of our examples so our so here our I equals two like we discussed earlier right that 10 is where it's going to find the issue where 10 is greater than 5. and so here we need to check two things we need to check okay there's two cases if 10 is less than or equal to seven sorry if 10 is less than 7 or if 2 is less than 5. those are two main areas now what that tells us is if it's going to go one what that tells us is if it's going to go in this case 10 is less than 7 so if that tells us if one two ten seven works or if one two five seven will work and so if I so remember we need to only return a Boolean so if either of these works then we are good to go so hence we check if the card number so in this case 10 is less than I plus 2 which is 7. right or is 5 greater than 2 if either of these cases is true we know that we can solve it by removing either the 10 or the 5. and that'll produce us the answer so we just return that last one
|
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,048 |
Is it a face or is Chand Mila the one with eyes like the ocean, tell me what is your name Chand Mila [ Chand Mila [ Chand Mila Is Is Is this the one with eyes like the ocean, tell me what is your name [ this the one with eyes like the ocean, tell me what is your name [ this the one with eyes like the ocean, tell me what is your name Jaan, kitna hai betaab dil tu kya jaan dekh How is it going The heart says, you are here, the flow of time goes in the hands, the river of time gets jammed in the flowing destiny, you made my heart crazy, what is the blame on this heart, this one with eyes like the ocean, tell me what is your name ] Desire is true [Praise] [Praise] [ [Praise] [ [Praise] [ Praise] [ Praise] [ Praise] Yes, this is desire You are You are You are met in silence There is no one in this world You are alone I am dreaming of you And what less is the ocean of mine now The one with eyes like this, tell me what is your name? May there be such a lover, the thirst of the heart should be quenched Neel Ambar Par Chand Jab Aaye Pyaar Barsaay Hum Tarsaaye There should be such a lover, may there be such a lover, may the thirst be quenched by walking on Neel Ambar Par Chand Jab Aaye Pyaar Barsaay Hum Tarsaaye Unche Parvat When the thirsty amber is kissed, the thirsty amber, when the ocean shines, the high mountains, when the amber is kissed, the thirsty amber, when the ocean shines, to laugh with love, to the gram flour in my arms, my dear, someone should come, there should be some companion like this. Is there any lover, the thirst of the heart Ambar Par Chand Jab Aaye Pyaar Barsaay [ Pyaar Barsaay [ Pyaar Barsaay When the temperature falls, the throat gets bored of the heat of the breath, the moisture of the hands, my mother yearns for someone, such a companion. May there be such a lover, may the thirst of the heart be quenched, when the moon comes on the blue and amber, it rains love 'Chaam 'Chaam 'Chaam cham karta' cham karta' Sawan opens the Guru's paan in the colorful rainy season. When even the mother is gone, Cham does the Saavan, the guru's paan is opened in the colorful rainy season. When my mother's body gets wet, I have to bathe in love, you are my life's heart, my yearning dream world is there is such a companion, there is such a lover, my heart's thirst is quenched, when love comes, showers its love on blue and blue amber, makes us yearn, Lal While walking, remember these songs of mine Never say goodbye, never say goodbye Remember these songs of mine, never say goodbye [ these songs of mine, never say goodbye Roti Haste Bas Hi Tum [ Bas Hi Tum [ Bas Hi Tum Keep Keep Keep humming Never say goodbye, never goodbye Say no While While While making love, we will go to the story till the day we fall asleep in the lap of spring. While loving us we will go to the story till the day we fall asleep in the lap of spring. Still you keep decorating the dreams like this. Kabhi Alvida Na Kehna Kabhi you keep decorating the dreams like this. Kabhi Alvida Na Kehna Jalti Chalte Remember these songs of mine Kabhi Alvida Na Kehna [ Alvida Na Kehna [ Alvida Na Kehna [ Praise] Humne Dilbar Badh Jaye Kahani Hum Magar Aur Sunny Si Laga Tumhe Jeevan Ki Dagar Bichch Mein Dil Let the story be filled with us, but you will feel like a sunny life, if we come, you will remain like a bullet, never say goodbye, while walking, remember these songs of mine, never say goodbye, bread would laugh, you would just hum like this. Rehna Kabhi Alvida Na Kehna [ Alvida Na Kehna [ Alvida Na Kehna Om Kya Yehi Pyar Hai [ Kya Yehi Pyar Hai [ Kya Yehi Pyar Hai Tere Bin Kahani Lagta Nahi Time Has Not Passed Time Has Not Passed Time Has Not Passed Yes This Is Pyaar Hai Yes This Is Pyaar Hai Yes This Is Pyaar Hai Yes This Is Pyaar Hai [Praise [Praise [Praise ] ] First I understood something else, the weight of the button, but now the story is going on, my night's wake up The The The day does not come out, my heart doesn't work without you, time doesn't seem to have passed, isn't this the love, tell me, no, yes, this is the love How Bhoolungi Tere Bane Se Milo Kuch Bhi Ho Dil Pe Koi Shor To Chala Nahi Dil Tere Bin Kahani Lagta Nahi Time Gwara Nahi Kya Yehi Pyaar Hai Yes Yehi Pyaar Hai [ Yes Yehi Pyaar Hai [ Yes Yehi Pyaar Hai In the season of people like this Do hearts meet like this, lovers, do we meet even in autumn Dulka Nahi Tere Bin Kahani Lagta Nahi Time Passes Nahi Kya Yehi Pyaar Hai Yes This is Pyaar Hai Ho Dil Tere Bin Kahaani Lagta Nahi Time Passes Nahi Pyaar Hai ] Yes, this is love O O O peace of my heart, pray for my heart O peace of my heart, please pray for my heart Seeing your own shadow, where you feel ashamed, now this is the first destination, you are Now I am scared, what will happen to me [Praise] Peace of heart, pray for my heart Maula The The The place of the heart does not suit me anymore, No heart in my eyes wants only you, so what should I do, oh my Give peace to my heart, pray for my heart Even if I am alone, I can recover after falling, If you hold my hand, I can make my world a cloud, I have asked you for the world Now decide for yourself my love, oh my Peace of heart, pray to my heart, O peace of my heart, O mine [ O mine [ O mine It's a fun evening fun evening fun evening Made me drunk [ Made me drunk [ Made me drunk And took my life [ life [ life You stay away from me Not a companion, it seems as if you are drinking the poison of a swan, fun Be Be Be intoxicated [ intoxicated [ intoxicated Baa Jamkaru makes me dream, kiss me, your sweet glance is good to me, why do I think of you Shame on you, let it be given to my lips, dark fun Let Let Let me be intoxicated, someone should pull the strings for you Let me Let me Let me go [ go [ go [ Praise] [ Praise] [ Praise] A sullen destiny like someone [ destiny like someone [ destiny like someone You are silent like a picture Someone becomes your eyes but your message should be given Sham Masti Madhosh Kiya Jain Me [ Madhosh Kiya Jain Me [ Madhosh Kiya Jain Me Someone Pyaar Deewana Hota Hai Mastana Hota [ Mastana Hota [ Mastana Hota Har Khushi Se Har Gum Se Begana Hota Pyaar Deewana Hota Hai We are happy with every happiness; we are alienated with every sorrow every happiness; we are alienated with every sorrow every happiness; we are alienated with every sorrow We are We are We are troubled by moths
|
Longest String Chain
|
clumsy-factorial
|
You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`.
A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`.
Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`.
**Example 1:**
**Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\]
**Output:** 4
**Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\].
**Example 2:**
**Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\]
**Output:** 5
**Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\].
**Example 3:**
**Input:** words = \[ "abcd ", "dbqca "\]
**Output:** 1
**Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains.
\[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed.
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 16`
* `words[i]` only consists of lowercase English letters.
| null |
Math,Stack,Simulation
|
Medium
| null |
114 |
Jhal Ajay Ko Hello friends welcome to my YouTube channel Teacher was today in this video are going to point question flat in the country to link description what to do is to convert to a form and how to do that what is traversal preorder traversal kaisa hota Means the ghrun is simple so like if this then its traversal preorder traversal like this one and if we talk about the meaning then this is where its operation is and we have li then nothing the work is very easy simple you fat I have to keep a suppository, I have this trick, I have something like this, I have made an entry, it is a tight suppository, its ok, now what to do, if I want to make it English, then let's keep one face, let's make the fat that is right, left, this will become a necklace, how will it not even be made? Once the address was made, we named it Let's Positioning List Album. The album turned out to be one and a half like this. We once again kept the fat there that the rights of the link list will be made, so we are okay with it. Now don't think about how it will be made. How will it be made? Will keep high level thinking day Will convert to English If it gets converted then its name has been added Now look support the album has also been released To begin to gayi to how did the figure of the crooked appear in the sight That the woman will look something like this Root to It will remain the same but this album list is now because now it is a train, so what will be the range of notes in it, like all the notes in it will be kept in near fashion, everything is right like this only because we put our stomach and made it in English, so in it Also such news which must have been kept for you as per the fashion of these English, you see, this is a very fun game. If this step is done and you understand then that's it, now the question is what did I do when I said to enter the English prayer of the rower in the pluot. This is the second Holi problem, the problem has been shortened, now what did we say, okay brother, it works because the left side is also an athlete and also a ride, so what we said is, cut the correction on the right side, make it a template and understand the meaning and keep it in the English side. The planet was removed from the side, and the one who has to sulk here, sulks on the left side, there is no website in English, everything is attached on the right side, so we cut the connection, after cutting the office collection, cut the element from here. By doing this or if it is physical, then how will you manage our pre-EMI, this is the route, we have our pre-EMI, this is the route, we have our pre-EMI, this is the route, we have muted the album along with it, totaled it here, there is nothing on this side when people are there because everything has to be kept in the right place. In English or tight in the album and all this will be fashion waste in the album itself, now yoga now you tell me as soon as the album is made and attached here, all the necklaces have been made, there is a belt contest because we know but according to this * It because we know but according to this * It because we know but according to this * It should be tested somewhere at the end of this list. So what did we say when we attached the album? Now what you have to do is find the last note of this album after which there is no element containing this note. So we have What point did you put, the team should keep freeing this clown till no more is found. When the massage note was found here, the team stopped here because after this there is no duty officer, Alto has nothing to do, straight to the end, simply here. Attach it and if I add it then how will the tree become with it. Now simply set the route. The second album is here. I will go to the album with some linear notes, after that it will be attached to me here and after that nothing will become a note. When the next question is solved, it is just simple, once I repeat it twice, there is nothing to be done, first of all I kept the area simple, then what I kept is that the album meaning let's tree in English will be created and the right chapter will also be created, both when If it is made then how to do simple arrangement, first cut it from there and put the album there, then find the last one in the album, it is not the last one, just stick the alto behind that last one and with that our list is ready. So from now on, let's do half of how it will come in the bar code, so first of all, what we said is, let's create a function that will name not reflect, take those appeals, time flat, it will give fruit, input B.Tech root, flat, it will give fruit, input B.Tech root, flat, it will give fruit, input B.Tech root, input like this, now see if the dough starts getting upset. So, it is right to raise almost any question from the people of the country. Now let's talk about what we had kept, we had set that if we have taken left, it will become 'Lee', so left, it will become 'Lee', so left, it will become 'Lee', so I called for an electrician and made it flat, something like this in the afternoon. What did we say? Left is loot and lottery. Our left was done and after flattening it, I had left cars in it. This was the left one that I had bought. After flattening it, I asked for the pointer on the left side of it. It will happen, therefore, it will pause the points. This is complete in English. Similarly, according to the face, we have also asked for the one on the right. There is no problem, we have also asked for the one on the right, after saying 'Ru Don't no problem, we have also asked for the one on the right, after saying 'Ru Don't no problem, we have also asked for the one on the right, after saying 'Ru Don't Like', both have arrived. Now it is useful, now Like', both have arrived. Now it is useful, now Like', both have arrived. Now it is useful, now we are one. Even if I don't know, it's nothing, and if I don't ride, I will do it first, then I will have to keep the pride collection aside somewhere in the point, because I will make the right part of the route because I will cut it on the right side. We will turn on the light of the bowling list. We can also say this as simple because we have already ordered the right one, so if we have ordered it from there, then we will store it here in it. It does not matter whether it is right or not, then we will do it simply. It's a matter of let's do it, so when we ordered it, what all did we get upset about, left side, right side of the route, whom should I start, but English has become in English, now what to do now because it has become so. Now what do I have to do? I have to decide now. Interview That Tease I had said that this huge point of animation hero should definitely be taken and in that we will travel and like subscribe my channel and Lord Yama will go and stop and that's it. On the right side, the tightening lace which we had ordered will again be made of teeja plate, it is dodi, we have returned it, this is done and if we take a decision in this, it can be made even more, like if we assume that the left side was English. No, never meant there was nothing on the left side, so what then what friend means, there is white on the right side of the opposite side, now apply only one more thing, put white on the right side of the root and red alum on the left side, because although it was taken, but still we Let's say that bloody take it once that if we assume that no one has ever come from the right side, that means there is no cleanliness in the right side, then we will never get any one from the right side, otherwise if there is no one from the right side, then I have been kept on the right side. Because the gender list is not always tight, so what do I have to do, I have to store my life in English right on the root and the one who makes the root a lieutenant colonel because it is relaxed, nothing should happen and that's it in English. Also work and return route in the last, so we have the complete function ready. Now let's call it once by our Dharmendra Samsung. Slapped by passing route and return loot in the last. And now there is a need to collect the return in this also because the points. No, if there is anything else, then chapter change, holidays, it was a mistake. Okay, duplication has come, so what was left with us here. The duplication that was coming is coming because we will do the left side channel here, when we will attach it on the right here. Correction done when we attached the connection here on the right side, after admitting the connection here, this side had to be taped, due to it being taped, the entire traversal was lifting the shoulder tree guard again when from behind. Who was that happening in the testis? So now it's okay. Here we simply tap left. Rest all the cements converge. Loot submit. Okay, it's done. I hope you liked the video. This later video please comment. Share and subscribe the Channel Thank You
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
230 |
hey folks welcome back to another video today we're looking at question 230 k smallest element in bst uh so the way we'll be approaching this problem is by actually using inorder traversal so what is inaudible it's actually um traversing through a bsd such that it'll give us um an order which is non-non-uh decreasing which is non-non-uh decreasing which is non-non-uh decreasing which would technically mean like increasing if they duplicate the elements it'd be non-decreasing and there are other non-decreasing and there are other non-decreasing and there are other traverses as well which is like pre-order and order which give you pre-order and order which give you pre-order and order which give you different orders as well but in our case since we need the smallest element uh if we use an inaudible and use like an array list to store all of the elements that we see in the binary tree we would just return the nth element so it's a pretty simple problem so let's jump right in um so when it's a tree problem it's safe to assume that it's uh you can use recursion in some form of the other to solve that problem um so we'll be doing the same here we'll be using recursion to do that uh the first thing that we actually need is a list right so the list will store all the elements in the tree so let's call it list and this will be new arraylist right and what do you need you just need let's call it like a helper method and you need to pass in two things you need the root and you need the list um and let's create the helper method right so it's void because we don't really return anything and helper two parameters that you're taking in tree node let's call it node and let's take the list right so it'll be list of integer let's call it list awesome so the first case that we need to check is that if um node is equal to null you would just return it as is if not um you would call the helper method on the left node so it would be node.left so it would be node.left so it would be node.left and list and the reason why you're doing that is because you're using inaudible because you need to add the left node before you add the current node because the left node will be smaller that's the reason why you call the helper method on the left node and then the current node that's uh you'll add that to the list as is node.value and after that you do the right node because this is the order which will give you everything in a non-decreasing manner everything in a non-decreasing manner everything in a non-decreasing manner dot right and then this is a list um and the in the end you just return it as is awesome and once you've finished uh traversing through all of the nodes we'll return the list with everything in it when i say return the list it's because it's passed by reference you don't really need to return it you have access to the list already and then you just need to return uh the kth element so in this case it'd be list dot get um k minus one so and the reason why we have k minus one is because all of the indices start with zero awesome so let's compile this and see if it's okay huh all right of course uh let's start out i'm gonna try again okay so the first test case is okay everything else is okay as well awesome uh so let's talk about the space and the time complexity of this entire solution the time complexity of the entire solution is off and since we are traversing through all of the nodes in the tree and the space complexity is also open since we are using a list to store all of the um the values of the nodes in the list awesome if you have any questions please let me know in the comments below if there any other questions that you want me to solve from lead code also let me know in the comments below i would really um i would be really happy to sell them for you and don't forget to subscribe to the channel i would really appreciate it and don't forget to like the video um all of this helps me um and keeps me motivated to make you make more videos so thanks so much and i'll see you all in the next video
|
Kth Smallest Element in a BST
|
kth-smallest-element-in-a-bst
|
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
|
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,671
|
1,859 |
So today we will do the question sorting the sequence, we will do the sentence question, so what is in it is that we have been given an input, the sentence string, in which we have been given some words, behind which their sequence is written, which number will come on which, like That will come at number two, this will come at number one, so if we rearrange them according to their numbers, then this sentence will be formed that this is a sentence, so we have to do this, let's see how to do it, so what if we have been given this input. So what we will do in this is that with the help of split function, we will put these words in a list and what about slicing or reverse, we will reverse them with the help of any function, then split function and reverse. By doing this, we will have this string, this list will be created, now what will we do, we will short sort them, with short function, then after sorting, we will have this list, what will we do now, with the help of for loop, we will pick each word and The first word is the first element of the string by removing it and the remaining one after that, we will reverse it and we will open it again and it is done.
|
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 |
446 |
okay friends let's solve their arithmetic slices Chuck problem a sequence of numbers called arithmetic if eita consists of at least three elements and if the distance between any two consecutive elements is the same so in this problem we needed to culture the subsequence there are their arithmetic slices in the previous question they must be consecutive but in this question they don't need to be so in this case you will see their 2 6 10 is also counted so let's see this example we will also use dynamic programming to solve this question but the question is how do we use the time a program to cash their previous code mmm well we will use a tipi array is also a 2d array so what does this 2d array mean we will let their I J means their total number of the arithmetic her slices indeed a wizard I and J so what do I mean so this case if you have the 2 1 which means the index of the number so the DP to represent the 6 this 2 means there are 6 and this one means to the for this is the index and the either will as a this is 6 and 4 so we need that you find the serve 2 times 4 minus 6 which means we need to find out you to make up arithmetic slices and then we find there's a chewing our map so we will use the number of the slot arithmetical slices and either with their two four and A two and A plus one once we have like this one we made another we can make have another is America slices we just actually make one more like this for two they can cause he's oven no arithmetica slices so we then we can add as one these case we can make half of the two four six as a rosetta crisis so these case you want the same idea is this three two we ended o is the six and eight and I will use the eight two plus one in case we can we already can make up who wrongs arithmetica slices so we add a 1 so in scale we can make up to so this likely is there four six eight and there o 1 o 2 4 6 8 and every time we will accumulate these coats so I forgot to mention this mapper as in this case we may have the same number so we needed to save their index for the lookup like if we have the last two elements we want to find that the first element to consist over the arithmetic here which have the three numbers we can use a hash map to quickly look up if we already contain this number so basically this is the idea how can you can't stand my poor English so let's code and I we needed there to calculate we need is a number of their array and then we need our 2d array which is the size should be and also we need a map but we should have paid and you choose there the key should be long because as we want to get to their first element we use the same Elementor times two minus the third element to soar it'll make holes overflow so we will use long and though we will use a lister to save the index map new hash map so for every element lesson and I plus so we'll put if absent then we will convert it into long new ArrayList okay and the map yet do not forget to cover that your long I add the kerning that's I okay we need a current there result was a total number of the earth Medicus subsequence the slices so for into I equal to 0 I less than and I plus this timings their third element and there J equal to 0 je les AI because J means is our second tournament J plus okay so now we will get to the target number the tie number should be the two times there AJ minus AI is in the first element we need so if the map contains key their target okay if we have this number in our map for every index right so for the K in the map yet so their target okay so if the K less than the J we know we can make up arithmetic slices so deep he i J well you coach shooter DP j k first one so this means the total number of the era's Mattox we can make up indeed or is there number K and number J this is number J in a number I and for every IJ we will sum up the D P IJ to our final result and final gesture return this result okay thank you for asking if you cannot understand that you may draw the table to see what does this deeply I Jamie and the how it Turkey caches their total numbers okay see you next time
|
Arithmetic Slices II - Subsequence
|
arithmetic-slices-ii-subsequence
|
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences.
* For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
The test cases are generated so that the answer fits in **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,4,6,8,10\]
**Output:** 7
**Explanation:** All arithmetic subsequence slices are:
\[2,4,6\]
\[4,6,8\]
\[6,8,10\]
\[2,4,6,8\]
\[4,6,8,10\]
\[2,4,6,8,10\]
\[2,6,10\]
**Example 2:**
**Input:** nums = \[7,7,7,7,7\]
**Output:** 16
**Explanation:** Any subsequence of this array is arithmetic.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Dynamic Programming
|
Hard
|
413
|
155 |
hey what's up guys babybear4812 coming at you one more time and today we're doing an older problem uh it's problem 155 it's called min stock it's an object oriented design problem so i think it's a really cool one and i think it's super deceptively marked as easy because it is not easy this one definitely isn't easy at all okay so if you're here because you got stuck with it and you're coming over looking for help nothing to be ashamed of okay so what makes this problem interesting let me close this what makes it interesting is as follows so basically we need to implement the stack that's kind of the standard stuff so push pop as in kind of getting the top element and then the interesting one is retrieving the minimum element in constant time in particular this constant time piece is what makes this tricky and i think super not trivial so we're told again push kind of pushes an element onto stack equivalent to depend um pop removes the top element top gets the top element without removing it and get min retrieves the minimum element in the stack um so i think it's pretty self-explanatory so i think it's pretty self-explanatory so i think it's pretty self-explanatory and we're told in the constraints that were the operations are always called on non-empty stacks so we're not gonna have non-empty stacks so we're not gonna have non-empty stacks so we're not gonna have to worry about error checking or anything like that uh basically what's happening here in the input is they push a negative two a zero a negative three and then they ask you to get the minimum value in this case that minimum value is this negative three it doesn't always have to be the one at the end but it was here we then pop that off uh they check top returns zero because now what we have in our stack is the negative two and the zero and then get min now we need to return negative two right so we're not returning to zero so there's a lot of different ways to think about approaching this problem and really just to like wrap your head around where the where the difficulty really lays in is in understanding the following if i start adding items onto onto the range i can simply track as i go while i'm adding them i can continue to ask myself is this number smaller than the last number was so i can ask myself like this if i do negative 2 and you know i can ask myself is negative to either the first number the smallest number if it is then maybe i can keep a variable min and i'll set that equal to negative two we then add a zero and we ask ourselves okay uh if we pop or sorry not if we pop but if we add the zero is it now our minimum element we'll know because it's greater than negative two cool we keep going we add a negative three is that minimum yes it is so we can you know keep track this negative three fine we now get to this point and we call a min function and again min function returns the negative three or this one we stored right here that's cool um but if we pop it off now so i pop off the negative three okay negative three is no longer there no you know what here negative three is no longer so i pop it off it's gone out of the array but the problem is now what's the smallest element so we've gotten rid of the smallest one here but it's like okay well does that mean every time we pop it we need to check if it's the minimum value so that's kind of that seems like a really weird approach and you might ask yourself well what if every time this get wind function is called we actually walk through the entire area and check for the minimum item and i would tell you that's a fair solution it doesn't make the problem a bit trivial um and so it probably wouldn't really fly in an interview and again if you're asked to do it in constant time then there's got to be a more clever way of keeping track and noticing like what are what is the minimum element that every step along the way and that's really what the question boils down to at every given step of the way if i was to pop off an item was my minimum value affected or not if it was if that wasn't a minimum value what was the previous minimum value to that it was the one previous to that and so on and so forth and we need to find a way to do that to keep track of every step along the way what was the minimum value now such that if we were to remove our current minimum value we have historical reference to everything else there when i say to everything else that just nuclear you know all the previous minimum values as we were growing and drinking this array and so that's kind of the key here of the point of confusion for many people in this problem so if you haven't thought about it yet pause the video think about it for a couple minutes if you can come up with a really clever way to do it um otherwise this is what i'd suggest and what i'll do is as follows we are we're going to take advantage of um a concept that can be known as invariance okay so in math for example an invariant is a number simply that will not it won't change kind of like a constant in the sense that um if things happen in the future what they were right now in this moment is they're locked and loaded they're not going anywhere whatever happens from here on out in the position that i'm in isn't going to affect my value my standing right now so how do we do that well let's think about this what if i gave you a stock and i told you or rather let me put this even easier let's say i run with the numbers if i had a negative two we got a negative two and they're fine i can now add a zero this negative two hasn't changed it's still staying as it is right even if i pop the zero off the negative two still remains so one nice proper to go to raise is that as i'm adding on every one of these numbers one by one add infinitum everything that happens before has not changed okay so lists or arrays have this really nice invariant property where all the preceding elements the ones preceding the one either pushed on or popped off don't actually change and we can use that to our advantage as follows every step along the way instead of storing just the number what i'm going to do is i'm going to store a list you can do this with the tuple as well because it only have two elements in it i'm going to store this value that we're adding in such as a negative 2. and what i'm also going to store is what is the minimum value thus far if negative 2 is the first element that i'm adding then by definition it is the minimum value so this is going to be my number x and the second position is going to be the minimum so far it'll be a negative 2. i'm now going to add the zero in when i add the zero in i'll add it as a nested array with a zero and what's the minimum number so far the answer that i asked myself well what was the previous minimum number and let's compare it to the number i just got a zero right i just got a zero the previous minimum which references the cell before us and its second entry right index one is negative two the smaller of the two will go right here negative two the previous minimum it will not change because by definition everything here and before it that minimum value is invariant for all the elements that have happened up to then whatever the minimum value was there it will remain to take it a step further if we were to add the negative 3 now not only would i add the negative 3 i would also say okay negative 3 is smaller than the previous min so the new minimum is negative 3. if i go to the four i had the four i compared to the previous minimum was still strong smaller we add the we keep the negative three as it is and so on and so forth what happens now when i pop this off here if i want to run my get min function what i've got to do is to check the final elements second entry so i do that i realize negative 3 has been the smallest element so far why is this handy this is handy because if i pop this off now this is now my final element at this point the fact that negative 3 was the smallest value excuse me from this point and onwards negative 3 was the smallest value from this point and onwards negative 3 is still going to be the smallest value up to that point similarly up to and including here negative 2 is the minimum value whatever happens here i know for a fact that in this chunk of array right here negative two is the smallest value because i've been tracking it as i was going every single time and the quota right this is i generally think it's like six lines of code or something the solution is very um how do i put it's a simple solution but it's not an easy one okay i think this is far from an easy question and if you're able to get to the point where you can piece together and understand here you know the logic to put the logic the ability to put the logic together in terms of figuring out how to store the fact of what some kind of my trailing minimum as they go every step along the way then you can really knock this out of the park so i hope that explanation made sense i'm going to jump into the code now and as always let me know in the comments down below if you've got any questions on the solution or the logic of it so first thing we need to do with you know as with any um object oriented design question we've got to initialize the actual structure since all we're going to need is one array i'll just call it self stock and set it equal to an empty array first we want to implement this push method and what we said is we want to do the following we want to check whether or not the array is empty and if so we'll have two different actions so we will say if not self.stack so if it's empty what self.stack so if it's empty what self.stack so if it's empty what we're going to want to do is to say self.stack.append self.stack.append self.stack.append and what we're going to append is that next that array and that will strictly just be the number and then the number itself which is our minimum so far otherwise what we want to do is we want to take the stack and append first off our number as it is and then we want to take the minimum of the number and the previous entries minimum so right here when we're adding it on maybe i should have scribbled this out so neatly but this number right here this second one if that if this is index i then this number is strictly going to be the minimum and this is i'll call this x this would be the minimum between x and i'll call it stock uh a negative one so the previous element we had so it'll be kind of i minus one but in this case since we're always pushing to the end it'll always be the current last element and we're looking at its second entry the entry in index one so this is the logic on how exactly we're going to go about picking the minimum of the two the historical minimum or the minimum we've had so far and our current number right now so what i'll do is take the minimum between x like i said and solve that stack at negative one which i'm realizing here took up a lot of space uh negative one and we're looking at the second entry or the entry at index one okay so we're just getting the minimum between those two and this second item will always by default and keep track of what the minimum value has been pop is easy okay so that's kind of the hardest one in my opinion pop is pretty trivial because all and we're not returning anything here either uh all we need to do is say stock.pop all right top is simply going stock.pop all right top is simply going stock.pop all right top is simply going to return the top element in the stack so we're going to return a self.stack so we're going to return a self.stack so we're going to return a self.stack and we're going to reference negative one and since they want us to return the integer i'm specifically going to reference the that first element or the zero element that sits right here in that at that index zero position within that nested list we're making right so just really what we're doing is what our final solution will look like is or not even final solution but the stacks will all look like this where we're going to have some number a and then the minimum so far b the minimum so far c the minimum so far so on and so forth now when we actually want to get the minimum this now becomes trivial because of how we've set this up to get the minimum all we've got to do is return self.stock at the final element we've self.stock at the final element we've self.stock at the final element we've got and we want to return its second element or the one in index one the position at index zero is the number itself the position of the value at index one is the value of the minimum number so far and quite frankly that's it that's all we've got to do but like i said the solution is pretty trivial and i'm just running through it super quickly to make sure i didn't make any dumb mistakes and there we go that's all there's to it so i really hope that hope you guys learned something here i thought this trick was wicked cool when i found out about it um and so i wanted to share i this one some way shape or form comp in the future for you i'm sure i really hope it clarifies the problem and i hope like i said that you really learned something out of this problem so any questions anything you want me to clarify or to you know answer drop it in the comments down below like comment subscribe yada i don't need to tell you guys what to do but i would appreciate it i really would um and yeah apart from that i guess i'll see you guys next time peace
|
Min Stack
|
min-stack
|
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the `MinStack` class:
* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.
You must implement a solution with `O(1)` time complexity for each function.
**Example 1:**
**Input**
\[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\]
\[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,null,-3,null,0,-2\]
**Explanation**
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
**Constraints:**
* `-231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
|
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
|
Stack,Design
|
Easy
|
239,716
|
42 |
hello and welcome back to the cracking Fang YouTube channel today we're solving one of the most legendary problems on lead code number 42 trapping rainwater before we get into the question prompt if you haven't already done number 11 container with most water stop this video go do that one because this problem hinges a lot on how you solve that problem and if you don't understand that one then this one is definitely isn't going to make sense CU it's a lot more complicated and you really have to switch your brain on to understand the solution okay given n non- negative solution okay given n non- negative solution okay given n non- negative integers representing an elevation map where the width of each bar is one compute how much water it can trap after raining horrible problem if you were just given that without this visual diagram o my God luckily they do give us this diagram so we can see that we have these black bars and we basically assume that it's raining from the top and how much water would get trapped here obviously if we look here in this case like even though water would keep going it's not just going to like trickle down so we don't have some sort of like trickle down effects it just there's no overflows here so it's not like from here it's going to overflow and then fill this Gap it's just literally where there's a gap between the two so let's just um kind of get that out of the way because I don't know maybe we're braing thinks it can overflow it can't so it's literally just um going to fill in the gaps here so let's look at an example so if we see this one obviously we can see that there's a gap here uh so this will get filled and then this area here is going to get filled um so we have what is this one square uh so this is four squares here and then we have one square here so there's a total of six again this is one of those problems where if you just look at it's really easy to solve but how in the world are we actually going to code this so if you've seen container with most water you remember that we had some logic where we were looking at kind of the left pointer of where we were and the right pointer of where we were and then basically just calculating kind of the area of the kind of rectangle that gets formed and that was the amount of water in there and then you know we just maximized that unfortunately now we have obstacles and it's going to be a bit tricky to do that and the way that we actually want to do this is we're again going to have left and right pointers so the left is going to start at zero or wherever this thing starts and the right is actually going to start at the end of the array so this is going to be the Len of n uh minus one right so it's going to start here what do we want to do okay so when we solved container with most water again we were we had some sort of perimeter uh sorry some area that we found and then we computed the amount of water inside of it the problem with here is that there's obstacles so we can't just do that because obviously there's things in the way so we're not able to just get the area we have to compute it on the Fly and then add everything together and that will be the final amount of water uh we want to trap but again this is a problem because how do we deal with all these bars it's you know it's complicated so actually what we're going to do is we're going to move our pointers from left uh sorry towards each other so the left is going to go this way and the right is going to go this way and obviously when they intersect then we're done um with a problem and the logic really comes down to kind of solving it in the middle so what we do at each stage is we look at the current value of the left and the right and we're also going to track what the left maximum is and the right maximum is and you'll see why we do this in a second so what we do is we're going to check okay so what is the current value of left equals Zer and right equals one right can we trap any water here no because obviously this has no boundary on the left obviously they haven't told us that kind of the axis here can serve as a boundary so there's nothing bounding us here so we cannot trap anything and remember that we don't know what's going to come in the middle here and obviously we're not going to just do it um we're not going to look in here because that would give us a big O of n s solution if we were just checking what's in the middle for every single one that you could solve it that way but that's not the optimal solution we want to just do this um in one pass so we can't just do that so we know that there's nothing here so we can't trap anything at this point in time so what we do now is we actually want to move um the left here we want to move it to one uh so now left becomes one and right is still one so now what we see is that let's assume that nothing was in between right so we had our axis and we had something here right that means that we can potentially trap something right if there's a gap anywhere then we can fill it because we know that there will be a bound at the left side and there will be a bound at the right side so we can for sure trap some water here assuming that not everything in between is already an obstacle so if there are any gaps then we know for sure because the left bounds it and the right bounds it so there's at least a height of one that we could trap again assuming if there's gaps right if everything was just an obstacle in between then we couldn't trap anything but basically now that we know that we can at least trap one square of water when we see a free one um we can trap it so this is the basis of our problem right we now know that we have bounds which can hold water and what we want to do is just next a position that we see that we can actually trap something in we will so here we can't trap anything because these are both um uh obstacles right but if we were to move our left one more and left is now zero because the left Max is one and the right Max is one we know that regardless of what is in this bit here this is free this has a bound which can hold the water and the right side has a bound that can hold the water so we know for sure at this point we can at least trap this water we don't know whether this one is going to be high or not we don't know if it's low we don't really care we all we know at this point is that this tile here at this stage can be trapped with water and this is the basis of our solution we're basically just doing this greedily and adding them up as we go along so hopefully that makes sense right because we have a boundary on the left side and we have a boundary on the right side we don't care what's in the middle here because we know that this bit will always be able to hold water okay so now we you know add one to our solution so let's just say res equals 1 cuz we're able to trap right so now we can move our left one up again and we're going to move the left here and now we see the left equals 2 um and again we can't drop any water because this one is actually a boundary so we can update our left Max so now because the left Max increased we actually want to move the right side to see if we can find a higher right one because say we then found another bit of water we want to basically trap as much as we can so because our left is actually two at this point if we didn't move the right pointer up we could be missing as we actually will in this example a higher right one which um could help us trap water so if obviously we have two then that gives us a lot more squares to trap right instead of just if we have one we can only trap um you know at a height of one but if we have two then we can trap higher so because our left is actually higher than the right we'll actually move the right one to the left to try to find a better right one so hopefully this isn't going to get too messy um let's see actually maybe I can clean this up let's see oh boy okay um how do I get rid of all this text one second bear with me okay that did not do what I wanted it to do all right that's okay let's just not do that then okay we have this extra space down here so we know that the left Max right now is two and now we've moved our right pointer to this one and we've seen that the right Max uh is also going to be two and obviously our result is still going to be one okay so now we've moved our right here and our left is still pointing here so now we can move our left again and we see that we have a gap right but like we did before right if we draw our d diagram we have two here and two here we know that we don't care what happens between the next value we know that we're here right we don't care what happens to the left because we know for sure that we can trap between the left and the right so we don't need to worry about it we can just take whatever the difference between the maximum height is of these two and whatever our current one is so obviously this one is one so we can only trap one piece of water because there's an obstacle up here so we can trap this piece and then add it to our result and then we can move forward so we can move forward now so now we've trapped the water here and then we see that we have another Gap here right and this one is a gap of two so again we don't care what happens to the right of our Gap up until the point where we hit our right we don't know anything about that yet all we know for sure is that at this point in time we can trap these two Waters at our current um position here with our left pointer because we know that we're bounded by the left and we're bounded by the right so we can basically trap all of this water and add it to our result and essentially what we do is we're just going to repeat this process uh on and on until we basically cross the left and the right at which point there's no point of keeping going because we've already processed everything and that's really just the basis of the algorithm I think what I'm really trying to hammer home is the fact that let's kind of just get rid of all this text bear with me for like two seconds here while I clear all this okay that's as far as it wants to go uh oh Jesus okay oh man I can't okay there we go all right I'm not going to touch it anymore okay never mind what the thing that I want you to understand is that if we have two points and we know that you know there are obstacles it does not matter what's in between when we process something and we see that we can take water because it is bounded on the left and the right it can't just like overflow or spill out we know that we can at least take that one in that way we're solving it in a bit of a greedy Manner and we're just taking them as they come we're just feeling where we are um as it comes so here if we don't care what comes to the right of this point up until this right boundary if at this point in time we see that we can fill water it would fill right assuming that there was nothing else here then we could just fill everything so depending on how high the current obstacle is then that will be how much water we can take we can either take two squares one and two or if here is an obstacle then we can only just take one but we know for sure that we can take water here understanding this part is really the Crux of the algorithm and why I've basically said the same thing for the last 5 minutes because if you don't understand this part then you're just not going to get the solution and this is what really needs to click in your head that if you have a left boundary and a right boundary then you can take something greedily because you know for sure that it will be trapped here it doesn't matter what is to the right of our current position at this point in time we know for sure that at least this one can be filled right the rest can be boundaries they can be unusable but this position will for sure be able to be filled so this is all you need to understand for this problem if you don't get this go back rewatch it try to draw it yourself and figure it out or let's see the code first and then do it walk through it line by line uh and you'll see what I mean okay let's go to the code editor and type this up I feel like I've been blabbing for 10 minutes okay we saw the basic intuition and now let's code it up luckily the code is actually maybe 15 lines it's really simple the explanation is the hard part so let us type this up remember that we need a left pointer a right pointer and also a variable to store our result so the left and the right uh sorry the left will be zero and also the result will be zero so we'll say left equals trapped uh equals z and then the right will be the length of our height array minus one because we start at the very last index and remember we're also tracking the left maximum that we've seen and the right maximum we've seen to basically determine how high we can trap right actually in our case we only looked at examples where left Max and right Max were equal but in the case that they're not equal um then we can only trap up to whichever one is smaller here right we can't just overflow just because one boundary is higher similar to how we had in container with most water the amount we can trap is based on whatever the smaller of the bounds is obviously because then you'd have water flowing out if you tried to do it uh the other way so it has to be whatever the um the minimum of the two Maxes here okay so we're going to have the left maximum is going to equal the right maximum and this is going to equal to zero and now like I said we're going to move the left pointer to the right and the right pointer to the left and when they cross uh that is when we're done so we're going to say while left is less than right we're going to say that the current left position is going to equal to Heights of L and the current right position is going to equal to the heights of R okay now what we need to do is actually update our left and right maximum because our current position May actually be an obstacle and it may actually be the new highest point that we can use uh to trap in the future right if our current value is an obstacle then chances are we're probably not going to be able to trap unless it's actually less than whatever the maximum is but we still need to update it right so we're going to say the left Max equals to the maximum of the current Max and whatever the current left is uh and then the right Max is the same it's going to the maximum whatever the right Max is or the current right position now what we need to do is we need to basically either move the left or the right up and also add uh to our solution if we have one remember if the left maximum is actually greater than the right then we want to be moving um the right maximum Sor the right pointer to the left so that we can potentially find a greater uh right value to trap with and vice versa if right is actually greater than left we want to move it um to the right to see if we can find something bigger to trap with because we don't want to have the case where um we never move our left pointer up and then maybe we have a height of like five later on and then we're you know our right pointer is out of five and we're actually just trapping with one and five that's not the maximum because you can only trap up to one here because like we just said you can't have an overflow but if we found the five then you could trap at a much higher uh number so we're going to say if the left uh maximum is actually less than the right maximum then we're going to add to our trapped what we're going to say the left maximum minus the current uh left position so this is the case where um you know our left maximum is smaller so that determines how much we can trap so if we kind of look back to our example when we were um I guess this is uh what's a good example here well because they all kind of equal but basically it's uh it's the case here where we just do the left maximum minus the current one so the current left in this case in this block would be one so we basically just do whatever the left Max is which is two minus one to basically account for the fact that our current position is one and we can only trap one water here and in this case we move our left pointer up otherwise in the other case we do the opposite so we're going to say trapped is going to be equal to right Max minus uh the current right position because we need to account for the fact that our current uh right position may actually be an obstacle as well you can trap on top of obstacles as you can see here there is a trapping between this one uh and this one and then we need to move the right pointer down and then at the end we need to just return um trapped so yeah a good example here is okay so say our left pointer is here at this big one this is three and then our right pointer is here at this two right the reason we can't trap anything above here is because obviously two um is not high enough so we couldn't trap anything up here it would just like spill over so we can only trap in this thing because it's bounded by um this height here and this height here so why even if this one was higher we couldn't just trap all this stuff because you need to have the same height at least to trap that one so that's why we go off of whatever the Lesser one is because that will actually determine how much we can get otherwise it would just spill over okay so that should be that let's run this uh Heights OH is it called height now okay Heights okay let's just run that again and okay looks good let's submit this and accepted Perfect all right what is the time space complexity of our algorithm so as you can see all we do is actually iterate through our height one time we just go from left to right and we will visit every index at most once so that means that our solution here is Big O of n where n is the length of heights for the space complexity as you can see this is the most optimal uh solution oops because we don't use any extra space we just have these kind of pointer variables for our left and right pointer and the solution we don't create any extra space so it's Big O of one and this is the most optimal solution you can get you can't do any better than this um this is kind of the gold standard so yeah that is trapping rainwater uh one where it's really easy to code um but actually explaining it uh is the tricky part again this is a greedy solution so we're only able to take um Waters as they come based on kind of where we were able to bound ourselves um right so you know if we have a bound of Two and a bound of two then it really like in this case we have a bound here and we have a bound here it doesn't matter what comes in between because we know that when we're at this point we'll at least be able to trap it we don't care if the rest is actually a obstacle there's a gap here we can hold it because we have a left side and we have a right side so we can just trap and then we do this in a greedy Manner and that's the way that we're actually able to do it uh in one pass okay so uh that's enough blabbing hopefully this um video makes sense this one is one that really just takes a while for you to wrap your head around it if you didn't get this one then I would just recommend you have the code here you know that it works obviously it was accepted um literally just go through this example or go through the next example um line by line update what left is what right is what the left Max the right Max is go through this logic and you know see for yourself uh how the variables change and why you can trap at each one and see that you get to the Final Solution that's really your kind of last bet um for figuring these questions out is just get a pen and paper do it the oldfashioned way H and write it out so hopefully that helps hopefully my explanation kind of hammered home uh the main points here which is kind of this left Max and right Max um which decides everything here anyway this video is probably 20 minutes long at this point if you enjoyed it leave a like and a comment M subscribe to the channel to help me grow and have a good one see you
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
1,299 |
let's solve leak code $12.99 replace let's solve leak code $12.99 replace let's solve leak code $12.99 replace elements with a greatest element on the right side so we're given an array and we want to take each element in the array for example 17 and replace it with the greatest element on the right side of it so we scan through 18 5 4 6 & 1 of it so we scan through 18 5 4 6 & 1 of it so we scan through 18 5 4 6 & 1 the greatest one is 18 so we can replace 17 with 18 the last element 1 doesn't have any values that come after it and the problem wants us to replace it with a negative 1 so basically what I do is just consider that there's an imaginary negative 1 over here that's not a part of the array but we're just gonna replace one with this negative 1 now if you don't know how to solve the problem the first thing you want to do is draw a picture this is going to make it a lot easier for you to visualize it and notice patterns so once you've done once you've drawn the picture choose the easiest way to solve the problem first so we already kind of did that so to replace 17 we're going to look at every element that comes after it so each of the five elements and we're going to take the maximum of these five elements and we see that 18 is the max so we replace 17 with 18 we can repeat this process so for 18 we look at the last four elements we see that the max is 6 so we can replace 18 would 6 to replace 5 we look at the last three elements again the max is 6 so we replace 5 with 6 to replace 4 we only look at the last two elements again the max is 6 to replace 6 we only have to look at the last element which is 1 so we can replace 6 with 1 and of course 1 is going to be replaced with negative 1 once you draw it out it's pretty easy to recognize the repeated work that we're doing because of the repeated work this solution runs an O of N squared time it's also obvious that we're since we're doing a lot of repeated work that there is a better solution so let's try to analyze it to come up with a pattern that we can use to make it more efficient so the first thing that I notice is that the new value in position 0 is equal to the maximum of each value that comes after it so in the array from position 1 to position 5 to get the new value in position 1 we did something very similar we scanned through each of the last four elements so we took the max of the array from position 2 to position 5 so this makes it even easier to recognize the repeated work that we're doing we're taking the max in the array from one to five and then we're doing the max again from two to five wouldn't it be easier for us if we took the max from two to five first and then stored that value and then to get the max or to get the new value in position zero all we have to do is take that stored value and compare it with the original value in the array in position one let me draw it out to make it easy to make it even easier so the thing to notice is that these two equations that we wrote to get the new value in position zero they're both equivalent but in the original value over here we have to get the maximum of five different values over here in the new one we wrote we only have to compare two values to get the maximum this cuts down on all the repeated work so the hint here is that to get the new value in position zero we have to first get the new value in position one and to get the new value in position one we have to get the new value in position two first so the this problem leads us to iterate through the array in reverse order to cut down on the repeated work so we're going to start at the end of the array and then compete the new values in reverse order of course the new value in the last position is simply going to be negative one because that's like our base case okay so let's go through it in reverse order so our max value initially up until this point before we've even gone through the array is just negative one right that's our base case so we're gonna replace one with negative one now we want to recompute the maximum right and we only have to look at two values to do it we only have to look at positive one and negative one so are recomputing the max up until this point is going to be positive one so we can replace six with positive one now we're going to recompute the maximum again and all we have to do is look at six and one the six is greater so six is our new maximum we can replace four with six now we're going to just keep repeating this right so our new maximum up until this point is 6 because 6 is greater than 4 we just have to look at two elements so we can replace five with six now we're going to do it again max up until this point we just look at 5 and 6 is greater let's replace 18 with 6 now let's recompute the max up until this point 18 + 6 18 is greater so we this point 18 + 6 18 is greater so we this point 18 + 6 18 is greater so we can replace 17 with 18 now we can recompute the max here right between 17 and 18 but there's no point to do it because there's no more elements that we have to replace so now we've done it all we had to do was go in reverse order which cut down on all the repeated work we didn't needed to use any extra memory and therefore the solution the runtime is just oh of n now let's write the code so before I write the code I like to write a few comments to remind myself what to do so we remember that the initial max can be set to negative 1 right because that's the last value that's what the last value will be replaced with and the reason this works is because it'll eliminate some edge cases for us and we know that every value in the array is positive so we won't have to run into any extra edge cases the next thing we want to remember is reverse iteration we're going to start at the end of the list and go backwards lastly we know that the new max is going to be computed by taking the maximum of the old Max and the previous position in the array keeping this in mind it's pretty straightforward to write the solution we're going to initialize the right max to be negative 1 then we're going to iterate through the array in reverse order without creating a shallow copy of the array we can start at the last value in the array we're gonna iterate in reverse order and we're gonna stop once we get to the beginning of the array we're gonna replace the value in the current value in the array with the right max we know we have to recompute the maximum right but we're overriding the value in our Ray but we need this value to compute the new max right just like we wrote in the comments so when we compute the new max let's do it before we overwrite this value lastly let's update the current right max with the new max that we just computed and the return value that this function wants is the array itself so we can do that and of course let's submit it and see that it worked perfectly so these are the steps you can take to solve this problem
|
Replace Elements with Greatest Element on Right Side
|
k-concatenation-maximum-sum
|
Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105`
|
How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1.
|
Array,Dynamic Programming
|
Medium
| null |
232 |
hey guys welcome or welcome back to my channel so today we are going to discuss another problem is Implement queue using stacks so in this problem we'll be we'll have to implement a first and first out queue using only two stacks so we can take two stacks and we have to implement a q the implemented queue should support all the functions of a normal queue that is push Peak pop empty so guys if you are not aware of what queue and stack is so I will give the disk Link in the description or you can check those two videos so you'll get to know and you will have understanding of cues and stacks so let's see this so implement the MyQ class so here they will be given a class will be given here my queue and it will have a push pop Peak and empty functions which we have to complete push will uh push the element in the queue or in the back to the back of the queue pop will be removing the front element of the queue Peak will give you the element which is like it will just return the element which is at the front but pop will remove that element okay empty will tell you whether queue is empty or not so basically what we have to do we do not have a Q right we do not have a queue we don't have a queue but we have to implement we have to Implement all the functions of Q using stack using two stacks that is these two stacks will be representing RQ okay they will be representing our Cube so for example if just like quick introduction yeah what is a queue Q is first in first out that is if you have some elements one two three four five so since when you have to remove an element right one came first so one will be removed first so you can take this as a queue like the queue of something so here what whoever come first will get will receive the thing first okay and if a new person will come so they will be uh they will be added at the end of the queue okay then the new person will come they will be added at the end of the queue okay so this is how Q works that is here if you have to insert an element that will be done from here that is end and if you have to remove an element it will be done from front okay front is for insertion oh sorry front is for the edition if you have to remove an element deletion and error is insertion okay so now let's see how we can Implement Q using two stacks we will be seeing that so let me take two stacks I'll be taking two stacks here okay these are two stacks I can represent it like this also if you have two stacks this is S1 and this is H2 okay so just see what we will do let's say uh we have some push operations I'm just taking an example I have just some push operations that is I have to push one two three four five okay so this S1 right here S1 stack will be acting as my Q okay this S1 stack will be acting as my Cube so if elements are there in a queue how will they be arranged like if one will come first one will be at the top two will be there after that 3 will be after that and 4 will be like and 5 will be here right so that because this stack is acting as a queue right so if we have to delete an element obviously top element of the stack will go and the top element is what the first person which first element which came so this stack will fulfill my purpose so what I'm trying to tell you here is that this if these are the elements which have to we have to push so in this S1 stack they will look like something like this like okay now let's understand how this will work let's say we have two now we have to push element six so obviously guys you cannot add 6 here why because let's say you have added 6 here in this stack S1 now a pop query comes pop so from Q if you have to pop something you it should be the second element right like it should be for like the most first element which you come which came first in first out right first in first out so one was the first element which came so one should be popped out right but here 6 will pop out because it's at the top that we do not want to write so when a new element will come right we will not add it in the stack one what we will do see whatever the current elements there in the stack S1 we will add them in S2 so one we will pop from stack one add it in stack two then what will happen now again we will pop from stack one and add it to stack 2. okay we will do the same steps until stack 1 is empty so again pop from stack 1 add it in stack two okay pop from the stack one and add it in stack 2. again pop from stack one add it in stack two all right done we will do this thing until stack one is empty so what we have done we have removed all the elements remove all elements from stack one and add it in stack 2. this is what we have done right now we will do what whatever 6 is right stick six is six should be after 5 right it's after five only so in if a queue will be there it will like this one two three four five six in this order so six we will add in stack 2 at the top that is second step will be add the element in stack 2. now guess what we should do after adding this is something your stacked to now what we should do if we have to what we should do think see now this is our final elements right but if we have to add it in S1 they should be in order one two three four five six because one should come at the top why one should come at the top because if in future we have to do pop operation whatever was the first element in the queue that should go out first right so what we will do now we will bring all these elements back in S1 okay 6 will be removed six will be added here five will be removed five will be added here four will be removed four will be added here three will be removed three will be added here two will be node two will be added here and one will be removed one will be added here so see this is what this is your this is something like your Q right one two three four five six so this is how you will do the push operation so push is costly here push has few steps so now the third step is the move all the elements move all elements from S2 to S1 again from S2 to S1 so this these are these three are your push Operation Push steps if you have to push an element six words you have to push an end limit now let's say second is if you have to pop it's very simple if you have to pop just remove the top element of the stack S1 because that will be the first element which came in the cube that's guaranteed okay so pop is very easy remove top element from stack one then the third operation is peak peek Peak is to know the top element that is the front element of the queue like whatever is at the front of the queue that is obviously the top element of Stack one again so just return the top element of Stack one and lastly empty whether your Q is empty or not so Q is empty Q will be empty if both the stacks are empty so just check if both checks are empty then your queue is empty both are empty okay so this is how we have to implement Q using two stacks here push operation is costly when I say costly it means in push operation we have to do few steps same there could be another way in which you can make pop cause pop costly okay you can check that article it's a very good article on geek forgeek's website you can check that you will see how we can make pop costlier but here I am making push costlier that is push has few steps and pop is very simple just remove the top element of the stack okay so let's see the code for this ones see I have taken two stacks S1 and S2 push operation what was the first steps First Step was remove all the elements from stack one so until uh stack one is not empty we will just push get the top element push it into stack two and remove the pop element top element of the stack one so basically we are just shifting all the elements in stack two after that add the element in the stack two so we'll add the element in the stack two this was our first step this is our second step and then this is the third step was to remove move all the elements from stack to stack 1 again that is until stack 2 is not empty just push all the elements of Stack tool in the stack one this is your push when you're popping so just remove the top element of Stack one take the top element and remove it and return the top element for peaking again super Peak was to get the top element of Stack one and empty is just check if stack so for empty you just simply check if stack one is empty or not because it will have all the elements right track 1 is empty or not so I hope you understood the problem and the approach uh just do check out the Geeks for Geek link I will give that in the description as well in that you can see why we can make pop operation costlier okay like you can use any approach it uh both are fine if you found the video helpful please like it subscribe to my channel and I'll see you in the next video thank you
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
1,329 |
hey what's up guys John here today I want to talk about this distorting problem here number 1329 sword the matrix there diagonally so okay so let's take a look you're given M times in size matrix and you need to sort out adamance diagonally which means from left from top left corner to the bottom right corner it has to be sorted alright for example this thing here right two and one you need sorted two one and two and three two one can you sort it back to one two and three same thing here three one two you also need sorted back to one two and three same thing one two is already sorted once sorted right I think it's pretty straightforward you know like I think the if you read the description carefully you already know that so all we need to do is find out all the numbers around the same diagonal and then we sort them right and then we just put them back right so for that well we're gonna have a like credit dictionary you know to save all the numbers on the same diagonal you know how to save that so because on the same diagnose there I plot I minor straya it should be the same all right because that's the Ephrem bottom lab to top from top left to bottom right so there this one two three there I'm an Australian are the same if you sort it like the opposite on the other side of time diagonally so the I plus J will look different let's say if you sort on this side right on this side then we'll be using higher plus J but in this case since it's on its this side from top left to bottom right then there I - J will be the same so there I - J will be the same so there I - J will be the same so basically we'll be using this one has a key and we add everything with the same batter up I - straight to the dictionary batter up I - straight to the dictionary batter up I - straight to the dictionary I restored it right in the weights put them back right cool so to find a ham right not zero right and then let's create a dictionary right so we're gonna have like defaults list right list then with to a photo P right for I in range and for J in range am right we loop this to all the elements right under for the same I - J right we add them to this to same I - J right we add them to this to same I - J right we add them to this dictionary right so am I to J and then we do what and then for each of our for each of the diagonal elements right with sword and right we sort them and since we're going to put them back right one by one right so the last one will be the first one to put back right so basically we want to put it back from the smallest to the two biggest right so that in that case let's do it in let's sort this dictionary first dictionary okay right sort right we're gonna sort it reverse reversely so which means that the biggest will be out the first and then we'll put it back we can just simply do a pop right so from the tail it will be that the smallest one and then since they are distorted and then which do another for loop basically since we already have assorted elements in this like in this array we just need to put them back one by one since we're doing well looping from the left corner and the first time when we see the like a value of I and J we know that's gonna be our smallest number right so range same thing am or J in range and so this time we do it reversely right we do it put it back from the D from the sword in the dictionary right I minus J right we do what we simply do a pop because we already sorted and the last one every time will pop it'll be the smallest one right and then which is returned Matt in the end default deep cool all right yeah pretty straightforward for this problem just sort them do a dict do a sort save all the elements with the same diagonal on the same diagonals to the list and then restored them and then in the end which put them back from smallest to biggest right cool I think that's it for this problem yeah thank you so much for watching video ok I hope you see you guys soon bye
|
Sort the Matrix Diagonally
|
minimum-cost-to-move-chips-to-the-same-position
|
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.
Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_.
**Example 1:**
**Input:** mat = \[\[3,3,1,1\],\[2,2,1,2\],\[1,1,1,2\]\]
**Output:** \[\[1,1,1,1\],\[1,2,2,2\],\[1,2,3,3\]\]
**Example 2:**
**Input:** mat = \[\[11,25,66,1,69,7\],\[23,55,17,45,15,52\],\[75,31,36,44,58,8\],\[22,27,33,25,68,4\],\[84,28,14,11,5,50\]\]
**Output:** \[\[5,17,4,1,52,7\],\[11,11,25,45,8,69\],\[14,23,25,44,58,15\],\[22,27,31,36,50,66\],\[84,28,75,33,55,68\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `1 <= mat[i][j] <= 100`
|
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
|
Array,Math,Greedy
|
Easy
|
1895
|
515 |
all right let's talk about the find largest value in each tree rule so given a root of binary tree written the array of the largest value in each row in the three hours so this is the tree and then what you actually need to do is you traverse every single level and then find the largest one and then the range is between the integer.minimum is between the integer.minimum is between the integer.minimum uh minimum value to integrate the maximum value minus one so this will be pretty simple let's just follow along just using preferences method so this integer i'm going to call this new arraylist if the root is equal to no you can actually return a list and i'm going to using a queue to actually uh queue up into my uh i mean four or four my three note right for each level i would just uh append uh the note into my queue so uh q3 no q equals and then i need to offer the route by the way and then while the queue is not empty i will just keep painting right and i will keep traversing i'm sorry so i would say in size for the current level size so to choose the size i need to know my current maximum value right so i was about equal to integer integers so i will set the meanwhile initially and then traverse every single three no and then compare it right then i would say for inside your i less than size i plus and i will say three no equal to q and then i would say so when i pull the tree now right i need to know uh is the current value is actually comparable with my vowel right so i would just compare which ones which one is greater okay this one is greater than i would just assign to the vowel then i need to also check my children which is left and right so know that is not known i will say okay now i need to append this i mean offer this into my queue for the current and for the next level of a tree right so uh cuba offer know that's right and also you need to check the right so not that right no kill the offer know that right and at the end you need to return this right so this will be the pretty much the solution but the problem is when we assign about right we need to add into the list right then again the next current the next a three level you will reassign i mean re-initialize to the individual and let me just run it and then let me see if you have any or not so no dot right so this is a typo and hopefully i don't make another title uh this question is pretty simple and easy so um don't uh don't be afraid of typing this okay so let's talk about the timing space complexity for the time traverse every single one of them and then you compare so this is definitely all of n and it's actually this is a preferred search method and for the space i would say i will find right i mean at least i mean for uh for the worst case sorry for the worst case order thing you add every single value in the tree but for the space i mean let's be honest uh it should be constant uh which means all of and because you only need uh three value for the entire tree right i mean in this example right but the problem is you have to keep offering into the uh queue right so it will be pretty much like all of them be honest but most quickly you will probably say constant be honest but this will be my solution for timing space and i will see you next time bye
|
Find Largest Value in Each Tree Row
|
find-largest-value-in-each-tree-row
|
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** \[1,3,9\]
**Example 2:**
**Input:** root = \[1,2,3\]
**Output:** \[1,3\]
**Constraints:**
* The number of nodes in the tree will be in the range `[0, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
117 |
Hello hello and welcome to day itself in the assembly at 40 today's questions flirting next ride point is not second od ministry and you need to play list next right points for it's not byte fold electronics ride point if given winners will send you are soaking Date for the First Women Purpose 9X Elements Write for Second Element Two A-319 Writes for Second Element Two A-319 Writes for Second Element Two A-319 Writes Over 1.2 Side Part 23 Points Third Internal Over 1.2 Side Part 23 Points Third Internal Over 1.2 Side Part 23 Points Third Internal Storage for Internal Day 14.5 End Five Storage for Internal Day 14.5 End Five Storage for Internal Day 14.5 End Five Scientists 76 77 Note There Spirit Will Eventually Point to 7 End Sights Null Features to Make Short Period of the trees at all the rights of correctly populated Ayub Button hit film The Example Little but it's something dipped to abs several articles were going level-1 level-2 is possible 10-second level-1 level-2 is possible 10-second level-1 level-2 is possible 10-second looting level and not just look at Jalgaon location Slammed Slideshow and Lemon Juice Explain Earlier You All But I Don't Do in This Question Will Do Atypical Festivals or Few Things Need to Third Take Care of Badoda Vibration of Its Website to Display for Internal Thank you Right Elements Channels All Should They Want The Right Most Element of the Tree 2.2 Null Want The Right Most Element of the Tree 2.2 Null Want The Right Most Element of the Tree 2.2 Null to Hearts Right Element Solve This Channel CNN Security System and Requirement for the Question Will Make Short Rightmost Element Is Post in First in the Left Side Vote for This Post Aap Bhigone Do a Slack Trials of Sholet Lemon Juice Ka 80 Q10 Gota And Vein Viplo Dr Ne Bigg Boss Completed And Will Keep Ru Previous Note David Is Channel Should Support Elements Chappal Elements Ride Point Total Special Correct Navi Mumbai And Also One Reply The Element Powder Tube Willard Tourist Children Into The Guy Before beginning with that will of thirty first bright child for us and left side should be rough shipbuilding connections to also will decide the previous right element supreme website element gas reset-2 not seem in which was in website element gas reset-2 not seem in which was in website element gas reset-2 not seem in which was in description all two great coastal and 37.2 and 37.2 and 37.2 previous Right Element 28.18 Ride Point previous Right Element 28.18 Ride Point previous Right Element 28.18 Ride Point Shuddh Na Limit Vipul Lutti A Hung Verdict Billu Will 86 Post 2015 To Tu Kyun Ki Panda Hadf But E Do Previous Element Dates Of Deities-Demigods Thirty Years Dates Of Deities-Demigods Thirty Years Dates Of Deities-Demigods Thirty Years Old And Arnav Will Blot Way Or Rifle Point To The Previous Elements With office collection and whip just i don't they or its sub detail 128 my voice boiled distributed uplift right side effect will only art slapped 53525 this point marks two competition at one level morning to reset previous not previous next note gold previous next point to channel And Witnesses Give Up Because 6 Absolutely And 6 And Arnav Secret Endpoint Previous Note Prisoner In This Caste Discrimination As Established And After Examination Results Will Just Move Ahead And Previous Not Accepted Fact E Main Abhi Kaun Chhoti Pass Right 3.2 62 Kaun Chhoti Pass Right 3.2 62 Kaun Chhoti Pass Right 3.2 62 Previous Word Bollywood Super Star Plus Connection And You Can Save The Children So Will Just Opposite Of Under Previous Elements And Updated 250 That Pranav Absolutely Lies 350 Why Me Panap Office Ride Point To The Previous Next Right Element 150 And West Office Collection And Mrs Children And Foreign Policy And Hearts Breaks And Will Not A Gross Show What Vihag Chali Don Intercellular Means We Are Right Notes For Delayed Dynasty Start Respond Element Special ₹2 Lax Tried All Should Be Special ₹2 Lax Tried All Should Be Special ₹2 Lax Tried All Should Be Recited Next Flight Element Level Settings Show At Every Level Period Is Tunnel On Hello Hi Ho Pay Minute Clear To you what is the time complexity of algorithm time during the required to make water for instance you ride point mintu is not bamboo swift match draw lemon juice code of 202 writing on that persons note why new link last date of this root all subject bow Corner Case History Question Null Whose Everything And Return Route Has Knowledge World In The First Board Key Dot Is Mt6589t Delinquent Website For Maintaining The Level Of You Don't Size Also Will Need To Keep Track Of The Next Flight Elements Known Next Flight People's Tribunal Which Will Always Get way 8 minutes mother language change size - - 1800 phone minutes mother language change size - - 1800 phone minutes mother language change size - - 1800 phone why dot fool pa a tex leader the development of you in naav doobi do dot right sequence you next flight established in the connection and next right victims equal to head that updating next flight element And fair dot right in this notice internal billadi ₹10 made dried element for billadi ₹10 made dried element for billadi ₹10 made dried element for electronic that is similarly similar for the day i left side half jhal android ko love god and return tut ki film just that sort of a jhal ko adjust pritam vishwa tum shravan after all Why note right good next dot next explanation is gold letters update thank you for watching my video
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
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,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above 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, 6000]`.
* `-100 <= Node.val <= 100`
**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
|
116
|
1,029 |
hi I'm today I'll be doing the problem to city scheduling there are two and people a company is planning to interview the cost of flying the eighth person to city a is costs of I of zero and the cost of flying the ithe person to city B is costs of I of one so return the minimum cost to fly every person to a city such that exactly n people arrive in each city so let's look at this input array so just quickly the costs so this is the first person this is the second person this is the third person you want to interview and this is the fourth person the cost of flying the first person to city a would be ten dollars and the cost of flying the first person a city B would be twenty dollars same thing here so the cop this would be the second person their cost to fly them to city a would be $30 and to fly them to city a would be $30 and to fly them to city a would be $30 and to fly them to city B would be $200 and so on and so city B would be $200 and so on and so city B would be $200 and so on and so forth for so that's the basic idea but we need to make sure when we're trying to minimize our cost that we fly exactly n people in each city so in this input array there's exactly four people so 2n is the amount of people we're planning to interview so in this case two n will be four right so exactly n people would just be two so just be 2 n divided by 2 and in this case 4 divided by 2 is 2 so we want two people to be flown to city a and we want two people to be flown to city B so that's important to keep in mind so I'm just gonna go over the general idea and then I'm gonna go straight into that code so I'm gonna sort in descending order okay so I'm just going to take the absolute difference and sort from largest potential impacts of the company to smallest and financial impact to the company so take absolute difference and sort from largest impact it's the smallest impact okay now this is a really important part we want to set a cap right so there's a cap of how many people we can send to city a and how many people we can send to city B we don't want to fly more we don't want to send more than n people to city a or like you know we don't wanna fly more than n people to city B either so we need to set a cap and what that cap would be is just the length of the array the input array / - right array the input array / - right array the input array / - right so the cap per city a and city B is the cap equals costs top length divided by 2 so we want to make sure we don't fly more than 5 more than n people to either city we want to fly exactly at the cap to the cap so and so like the basic idea of this is if 2n is the amount of people we want to fly for the interview so that would just be the length of the cost array therefore n will just be the length of the cost array divided by 2 so we're gonna just set our cap to n so exactly end people arrive in each city okay so we're also gonna have counters to keep track of how many people we find each city and as long as we're below the counter below the count the cap sorry as long as we're below the cap we could fly that person to that city so have counters for each city to keep track of how many people we've flown to that city and we're gonna also have a variable called sum which is what we're going to return and when adding to the sum we pick the city with the lower cost of course because we want the minimum cost right so by default we're just gonna pick the city with the lower cost but as long as that city is under the cap so that's the catch so when add to the sum we pick the city with the lower cost and the catch is as long as that city is under the cap okay so this is super important okay and now I'm just gonna go straight into coding this so we're gonna sort in descending order so that's just going to be costs dot sort it come up okay now I'm gonna create a variable called sum I'm gonna declare a cap to be cost length divided by two and I'm going to create my counters to keep track of how many people are being flown in each city and make sure that it's not going to be more than the cap so I'm gonna call how many people I'm gonna call the counter for city a just a and city B just be okay so now I'm just going to go through the cost array and you know some based on you know add to the sum based on which city is cheaper and of course if it doesn't exceed the cap I said the cap which is just going to be exactly n people okay so it's not a loop through it so the cost of city a so they set it right here the cost of city a is I of 0 cost of I of 0 so just be this right for each person their cost of city a so let cost of city a to be cost of I of 0and like cost of city be the cost of I of one okay so we captured the cost now if city a is cheaper so it's it cost of city a it's less than or equal to cost of city B and remember also we have to make sure that you know we didn't reach the cap right so cuz you know if we have exactly n people already in city a we don't want to fly them to City a anymore so we have to check that so if a is less than cap then as long as this less than cap you know it's the cheaper city we're less than the cap let's just slide them there to city a and then increment the counter because we want to keep track of how many people we flew there else if we reach the cap if we reach end people sending end people there we're gonna fly them to city B even if city B may cost more okay so that's the case of city a is cheaper so the case of city B is cheaper we're gonna first same thing check if we're below the cap and then you know if it's cheaper cities B is cheaper and or below the cap we're gonna of course send them to city B and then of course increment our counter so we want to just keep track of how many people we flew to that city and then some same thing so I don't send them to city B because I hit that cap I'm just gonna send them to city a even though it's gonna be more expensive and then Ingram at the counter yeah okay now I'm just gonna return this um and that's it I'm gonna run this off lay it on any spelling errors or something okay submit okay and just quickly I'm going to go over the time and space complexity so the time complexity of this will be Oh an log n you know the most costly thing in the time would be sorting it so that's why it's om log N and the space complexity would be O of 1 so it's just going to be constant space and that's because we just declared these variables they're conkland they're constant so it's just these variables so like as the array size increases the input size of this function increases this space is not going to increase with it so that's why it's constant space rather than linear space so just remember that as like the input size increases does my space increase no I'm always just going to have these variables so that's why it's of one space yeah and thank you so much for watching
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
169 |
what's up youtube today we're going to take a look at leaker problem number 169 majority element marked as easy let's get into it so this one has a lot of upwards quite easy to understand and the problem statement is just a few lines given an area of size n find the maturity element is the element that appears more than and divided by two times you may assume that the area is non-empty and the majority element non-empty and the majority element non-empty and the majority element always exists in that area so the majority element is not the element that appears the most often but that appears at least and half times so if the array has length six needs to appear at least three times so it's kind of like a voting system where you have to get at least half of the votes and not just the most votes i'm gonna go through two solutions for this problem that i really like because there are a lot of possible ways to solve this but i'm gonna start off using one of my favorite data structures in python being counter which is an implementation of a hash table that is already pre-existent in python that is already pre-existent in python that is already pre-existent in python which makes it super easy and also works for a lot of liquid questions so let's call that counter c and just use counter to build up our counter and as an input we're going to use nums our array of numbers i'm going to print that counter for you just to know what it does pretty much counts each element in that array so 3 appears twice 2 appears once it's pretty much a dictionary so you can look up the value for that key so value of the key three would be two and that's what we're going to do right now we're just going to check whether that value that count is higher than n divided by 2. so in order to check for the maturity element we're just going to go through that counter so for n and c let's say n should be a number we're gonna look up the count of that number so if that count is larger than n divided by two that means it's the maturity element and we're gonna divide well n i'm using it twice here but the description says n should be the length of the array so i'm just going to get the length of the array divide that by 2 without remainder so if it's an odd number of elements we're gonna round down in that case we have three elements in the array and by dividing it like that we're gonna get one and because we're not using any remainder not 1.5 remainder not 1.5 remainder not 1.5 but one and then we have to be larger than that to be the maturity element so if we were larger or equal one would be allowed and one wouldn't be the majority we need at least two here so if that is the case we're going to return c or n sorry because n is the number and we're not going to return the count which is going to return the number which has the highest common majority code so we submit that code we're going to get an accepted output and that was quite simple easy to explain using counter which is reusable in other solutions as well and yeah this is pretty much what i would use in real life probably because it just makes sense and it's easy to understand and debug and yeah easy for other people to work on understand so runtime complexity for this solution is o then because that counter needs to be constructed and that is going to loop through the entire array and count up the appearances of each element there's no magic going on here you could pretty much implement it yourself so another trick we can use quite often in these data code problems is sorting the array before we do anything and that's how we can get a runtime complex or n log n which might be better for small cases and um yeah it's also quite simple so let's just implement that one so in order to sort that area we're just going to use norms.sort going to use norms.sort going to use norms.sort and if we print that it should be sorted now so if the majority element is going to cover at least half the array it's always going to appear around the middle that is best visualized by just looking at one of the solutions which has it outlined here so these are just illnesses in this visualization but the red lines indicate where the majority element would have to be and that is already the worst case so if our array would have a size of seven our majority element would have to have at least four appearances and that is visualized by that line so it's always going to cover the middle remember four is the ver the worst case it's probably going to appear more often than that in most cases and if it's not the highest number if there's higher numbers than it is going to be further to the left as well here or further to the right if it's not the lowest element in that area so this is already the worst case that could appear and it's still gonna cover the middle and in case we have an odd number of elements in our array it's going to cover both middle elements so in this case third and fourth element out of a area of size six so we could use that logic to just return the element that is at that index so we're again going to use our whole division without remainder so we're going to return nums at index length of lumps integer division by two so in the case of length 7 it's going to evaluate to 3.5 3.5 3.5 and then 3 because you're not using a new remainder and in case of an odd and even number of elements in the array in this case 6 it's just going to go straight to 3 and yeah take that element here because index starts from zero so it's going to pick up this element and in this case it's gonna pick up this element so it works perfectly pretty much so we submit that it's going to give out an accepted solution as well and that's pretty much it for this video already these were quite short i mean these are easy problems it might take some while to it might take a while to come up with these solutions but yeah once you've seen a number of these problems uh you're probably always going to think about sorting them and using a counter maybe anyways hope you enjoyed the video leave a like if you did and i'm going through more lead code algorithmic and database questions solving them using python or sql so if you're interested stick around and maybe subscribe see you next time
|
Majority Element
|
majority-element
|
Given an array `nums` of size `n`, return _the majority element_.
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,2,1,1,1,2,2\]
**Output:** 2
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
| null |
Array,Hash Table,Divide and Conquer,Sorting,Counting
|
Easy
|
229,1102
|
32 |
hello everyone welcome to another episode of coding decoded my name is sanjay rudeja i'm working as technical architect sd4 at adobe and here i present the 697 of daily liquid problem the question that we have in today's longest valid parenthesis it's a hard level question on lead code but i don't feel the same for all those who have been associated with the channel may know that we have already sort this question in the month of april 2021 the comment says it all the like says it all i have clearly explained the approach over here this is a stack based question and i'm pretty sure once you'll go through the solution you are definitely gonna love it up i have clearly explained the algorithm along with the coding section so guys do give it a shot you may not believe me but believe these folks who have written the comments over here that's not all i have couple of important announcements to make so do watch this video till the very end the first and the foremost one is product internship opportunity at adobe so adobe released a new opportunity for product in turn it is about the development profile so guys who are still in college and are looking for internship then please dm me your resume is on linkedin i'll be more than happy to refer you guys up and you may get an opportunity to work with adobe itself a lot of people have already done it please spread the word about it in your colleges among your friends so that they can also apply to it and might get a chance to work for adobe the next announcement that i would like to make is with respect to revision strategy so most of the people are confused when they have an interview scheduled how to devise various concepts in depth what questions to go for helping you guys i have created couple of playlists and let's go to dsa revision sheet the first one is for dynamic programming that i've already talked about yesterday's video as well the next one is for graph then we have binary search then we have backtracking bit manipulation sliding window so let's open each one of them one by one so this one is for the dynamic programming sd sheet so if you have an interview schedule you don't know how to revise the entire dynamic programming concept then this playlist is for you need to go to this excel sheet try each and every question and i promise you after going through this sheet you will get the confidence of nailing each and every question with respect to dynamic programming in an interview it covers various concepts one dp2 db 3ddp longest increasing subsequence and what not so i've also marked uh specific questions with double star that represents highly asked questions that i must do before an interview so guys do give it a shot and the next one that i am going to talk about is the backtracking sd sheet so consider the first one as the bible for solving each and every question related to backtracking in this video i've explained the template that can be used in each and every question of backtracking what you need to do you need to go to this video have a look at it understand it fully then you need to try these questions that i have listed over here and you will yourself see that the same templates get supplied in each and every question so backtracking also gets done the next one is for graphs coding decoded graph revision sheet so before an interview you are totally confused what are topics to revise because graph has various underlying concepts for example topo sort dfs bfs this extra spanning tree union fine so i have cherry picked each and every question which is most important and must know before an interview and i've listed those questions over here along with their video tutorials so if you have any doubt understanding those questions up please do refer to these videos and i promise you'll get a good hold of the underlying concept you'll be able to crack any question of graph fully so you'll yourself feel confident after going through this playlist also i have not added a lot of questions over here because at times they'll become redundant and it becomes overwhelming for a student to solve so many questions before an interview so as very selectively chosen few set of questions that will really help you boost your confidence level the next seat is for sliding window uh the next one is for a bit manipulation so guys i'm attaching these links in the description below do check them out and i'll be adding more to it in each and every list you'll find video solutions attached to it also the difficulty level will be specified must to do will be specified now my work is done i have provided you with the conceptual video solutions i have provided you this with the selective question said that you need to do i have provided with you with an internship opportunity that you may apply the struggle is all yours i can only be the catalyst going ahead so guys do give it your 100 and i promise you'll be able to crack any dream company of yours i hope you have a great time watching and going through these links and i'm looking forward to receiving as many resumes as i can let's wrap up this session now thank you
|
Longest Valid Parentheses
|
longest-valid-parentheses
|
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_.
**Example 1:**
**Input:** s = "(() "
**Output:** 2
**Explanation:** The longest valid parentheses substring is "() ".
**Example 2:**
**Input:** s = ")()()) "
**Output:** 4
**Explanation:** The longest valid parentheses substring is "()() ".
**Example 3:**
**Input:** s = " "
**Output:** 0
**Constraints:**
* `0 <= s.length <= 3 * 104`
* `s[i]` is `'('`, or `')'`.
| null |
String,Dynamic Programming,Stack
|
Hard
|
20
|
72 |
Del code problem number 72 edit distance so this problem gives us two strings word one and word two and the goal is to return the minimum number of operations required to re convert the string word one to word two so here it gives us three operations we can either insert a character delete a character or replace a character right so here it gives us an example as well we have horse and to convert the word or the string horse to R we replace the first character H with an r and then remove the extra R right so it will be forse remove the uh replace the h r and remove this extra R and so this EX e and we will get RS Ross which is word to so my approach to this problem is to use dynamic programming again so the way I do it okay so let's say I have a graph for status I'm not sure what this is doing here but yes let's say I have a graph so not really a graph but a 2d Matrix of basically this 2D Matrix will store the minimum number of operations for those characters right for each character in the string so let's say the word one is ABC word tool is a DC I guess right so obviously we know that we will only need to change replace this character to get the to get word one into word two but let's see how it works in the code right so again I mentioned there's a 2d Vector right so word one size so there three of this right and for each one inside there will be three as well right so for starters I will make them zero I guess okay so it look something this so just to write out or since it's plus one there will be a extra one so this will look something like this we have a b c and this is just an mition string and on the top here we will have a b c and then the base case right this will be the base case Okay so uh we populate the base case so for in I = in I = in I = one as long as I is less than word size we are replacing the first character of each into I right so I one so 0 one zero this character will be one right will be I so this one and this one right okay next we do the same thing but for the y- next we do the same thing but for the y- next we do the same thing but for the y- axis so for this first one it will be one two and three okay so these are the base case meaning if we were to convert this is ADC if you were to convert let's say a to okay so basically on this box should be like this yeah okay so if you were to start from here and convert it into a empty string right from string ABC we will need to have three operations which is to remove delete three characters right A B C right same thing if you were to do it for two characters in the word we will need to remove two characters and vice versa for the y axis as well okay after that we go to our for Loop so this for Loop will iterate through every single character against the characters in word two right so what will happen is if the current word we're looking at so let's have the pointers out first so I equals to one right so we are technically looking at I minus one so one is and B right minus one is a here we have a let me put the number in so J will be one as well all right so now we check since both of these string the first character of which uh is the same so we will just copy the result we got from IUS one and J minus one right so I is I i1 J1 is at this box so minus one will be at this box right so this will remain as zero next J Will increment to D and since you can they are not the same so here we check DPI DP J Will equals to I equals to one so I again is here however J is here so we're looking at this now so it will be equals to 1 plus the minimum of minus one M -1 is 2 minimum of minus one M -1 is 2 minimum of minus one M -1 is 2 minimum of two this minus Jus one is zero and minus one which is one St so the minimum would be zero so this will give us one okay sh increments again so we're looking at this C now again since they don't match so we do the same thing here it will be one plus the minimum of three 1 and two so obviously the minimum is one so 1 + one give us two okay I increments now + one give us two okay I increments now + one give us two okay I increments now we're looking at B J goes back to a they are not the same so we do the same thing 1 plus minimum of two 1 or zero minimum is of course zero so 1 + or zero minimum is of course zero so 1 + or zero minimum is of course zero so 1 + 0 still one same thing here B they are not the same so we do the same thing 1 plus minimum of one 1 so obviously this is going to be zero which is one 1 plus minimum of two one and one right this is obviously one + 1 is right this is obviously one + 1 is right this is obviously one + 1 is 2 okay next I will increment once more sh go back to a we repeat the same process they are not the same so we add up the minimum of the three previous cash results this will be the minimum of one plus minimum of 3 2 1 this is one 1 + 1 is this is one 1 + 1 is this is one 1 + 1 is two increment B plus minimum of one of two one and one this is one so we get 1+ one is two and this is one so we get 1+ one is two and this is one so we get 1+ one is two and lastly since they are the same so again if they are the same we just copy from this value here which is one okay now once that is done so we look through for our DP what we have calculated we have deduced that the minimum number of operation required to convert ABC to ADC of course would be to just replace it and it say so over here as well final result with one where DP if you were to access uh Tre right three it will be one right we return one which is proven here as well okay so yeah that's basically how the code works by running dynamic programming uh that's all I have to show thanks
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
17 |
we're looking at lead code at number 17 letter combinations of a phone number this is a very frequently asked question we can see here that amazon microsoft facebook i mean everyone's asking this question just even the last in the last six months um even in the last year even the last two years this question is frequently asked it's actually very easy to solve if we apply a specific backtracking template to this problem okay and so i have many other questions that use this backtracking template in particular permutations one and two subsets one and two combination some they may not as be they may not be as frequently asked but you can see that this is just a variation of any one of those problems and once you have a really clear understanding of how this template works you can really apply it to any question that's dealing with combinations subsets or permutations okay so we'll go step by step uh how to solve this and how to apply this template this backtracking template and then if you're still confused i highly recommend checking out my other videos um in this list that really go over this step by step and it will make sense it's a little confusing at first but once it clicks it really is not that bad and you can solve a lot of questions uh really quickly okay so let's take a look at the prompt here letter combinations of a phone number here we're given a string from two to nine inclusive we want to return all possible letter combinations that could uh that the number could represent and we can return the answer in any order so we can see here the mapping is that two maps to abc three maps to d e f and so on and so forth so here we have two and three so we can look at this as a b c and d e f and then what are all the letter combinations of that if we get an empty string we just want to return an empty array so that's a good edge case to be aware of and then if we just have two we're just going to have the first three letters the digit's length will be less than or equal to four so it's not going to be a very large input and the range is between two and nine okay so this is a combinations problem and the way we want to look at this is we're going to use recursion we're going to use a backtracking template and we want to look at this as a tree okay so what do i mean by that so here we're just we're not we're gonna have to create a hash that maps to all these numbers but for here because we're just looking at two and three i'm just going to create a little hash map right here for two mapping to abc and three mapping to def so when we get to our first level of the tree we're at two right over here what are our options what can we put into our slate we're gonna have a slate right over here okay and we're gonna use it use an empty array to keep track of everything as we recurse down the tree and in our slate what are options when we're and when i is at this two well two maps over here to abc right so we have three options we can either have a we can have b or we can have c in the slate okay and now once we have hit all three of those we can go ahead and increment i call depth first search recursion on each one of these nodes on the next level of the tree so on a b and c and what are our options once we get to the second level on a so here we can see that we have d e f so we can push um we already have a on the slate we can push d on the slate we can push e on the slate and we can push f on the slate same thing here we can push d on the slate we can push e on the slate or we can push f on the slate and the same thing here we can push d on the slate we can push e on the slate or we can push f on the slate okay and now i is going to increment we're going to pass it down our recursive helper function and we can see we're out of range so we hit that leaf level okay and once we hit that leaf level we just want to have a global result and we want to make a copy of this we can just join this because it's going to be an array but our result we want it in a string so we can just add that into our result okay and so on and so forth now how is this working what's happening here is that we're going to have a slate which is just an empty array we're going to pass this recursively down the call stack okay so this slate array is going to come over here it's going to come over here and then it's going to hit this base case where i is going to be the equal to the length of our input right that's when we hit this base case when we get to that base case we're going to do a linear operation join whatever's in the slate and then push that into the result okay then we're going to go ahead and pop off this d off our slate come back up and then push this e on there now we are at the base case here we're at the leaf and then we're going to make a copy of this and push this into the into our global result we're going to pop this e off come back up and so on and so forth and we're going to do in or pre-order all the way down this in or pre-order all the way down this in or pre-order all the way down this tree okay so that's the idea this is difficult to grasp if you're not familiar with recursion or if it's your first time being exposed to this concept it is a bit difficult so if this is your first time and this is not making sense i highly recommend get a pen and paper draw the tree out okay once we go through the code put the code side by side to a pen and paper and just draw everything out and it will click i promise it will click and once it clicks it makes these types of questions really easy like they're not that bad not that difficult to do so let's just go over time and space complexity on this what is our time complexity well worst case we could have uh let's see here we could have nine or seven so worst case we could have four letters here right so we could have four uh to the n okay and that's going to be how many levels of the tree that we're going to have based on the digits that the digits are mapping to and then at the bottom we have to do a linear scan okay so we're going to do 4n times n is going to be our time complexity here okay and it is a little bit difficult to calculate time complexity with this because you have to really look at it as a tree so if this doesn't make sense i would take the numbers seven and seven that both have four uh four letters on it and just draw out the tree and you can see that when you draw it all out the time complexity is four n times n and you have to remember when you get to the leaf you have to do that n operation which is where that n comes from now what about space okay uh it's pretty much the same deal here okay worst case we're going to have 4 n okay and then we're gonna that's just gonna be our result and then it's going to be another n because that's gonna correspond to the length or the height of the tree okay the call stack that we're to need to get all the way down so our space complexity here is also 4n to the n if we're including the result output into our space so not the best time or space complexity and that's why you can see in the input the length of this is no bigger than four because you can see how this just grows like crazy huge okay so let's go ahead and jump into the code and we're just going to use this template and if uh if this is new to you i highly recommend checking out the other videos in this list this recursion group of questions that i have videos for so highly recommend checking out those other ones until this template kind of becomes second nature because you can apply this and you know solve a lot of these types of questions quickly so we're going to start with our global result okay and in here we're just going to set that to an array now we're going to have our depth first search recursive helper search okay and this is going to equal i uh digits and then a slate okay and now we want to have our base case so if i equals digits.length so if i equals digits.length so if i equals digits.length then we want to take whatever's in the slate join it and then push it into result okay and then we want to return out of there and now we want to figure out our depth first search recursive a recursive case okay so what do we want to get the chars right so we can say let chars equals we'll create an alpha hash map here that will map all these numbers to the letters so we'll say alpha of digits at index i okay so that's going to give us a b c for the first one the second one when we increment i it's going to give d e f and now we just want to do a for loop so we can say four let uh char of chars okay so we're going to be at a then we're going to go to b then we're going to go to c and then we just want to add a to the slate call a recursive helper by incrementing i and then we want to pop this off the slave okay and that's all we got to do for the uh depth first search recursive helper then we just want to call depth first search recursive helper i will set to zero we'll have our digits there and then our slate will be an empty array and then we can just return our global result okay and one last thing we want to do here is uh alpha hash map and so here this is kind of monotonous but we're just going to do 2 is going to map to abc okay 3 is going to map to d e f 4 is going to map to g h i 5 is going to map to jkl 6 maps to mno 7 is going to map to pqrs 8 is going to map to tuv and 9 is going to map to wx yz i feel that was the most exhausting part okay so we have our alpha map here let's just zoom out a little bit so you can see all the code in one go and that's what it looks like you can see the main code is not that complicated and this is just using a template that we used in all these other problem sets that we have in this group and let's go ahead and run that make sure everything works and we're good oh we have one last thing here we just want to say if digits.length equals 0 okay digits.length equals 0 okay digits.length equals 0 okay then we just want to return an empty array okay and you can see we're making relatively pretty good time and space complexity on this so that is leak code number 17. if you're still confused about this that's okay this is a difficult question or these types of questions are a little bit tricky if you're not really familiar with recursion or if you're not familiar with this template so if you're still confused i highly recommend number one get a pen and paper and draw out the tree really make that connection between recursion and a tree and then check out the other videos because it's basically rinsing and repeating we're using the same template and solving multiple problems using this recursion tree method this backtracking recursion method okay so that's leap code 17 i hope you all enjoyed it and i will see everyone on the next one
|
Letter Combinations of a Phone Number
|
letter-combinations-of-a-phone-number
|
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`.
| null |
Hash Table,String,Backtracking
|
Medium
|
22,39,401
|
1,091 |
Hello Everyone Most Interesting Shot In The Soil Which Can Travel From Top To Bottom And Elements Subscribe Iss Time Se Chalkar Algorithm And It's Not Its Roles And Have A Chance Of Moving Element To All The Best All The Last Gautam A And Sunao Share Dozen Condition That You Can Travel In All Directions 31000 Must Subscribe Channel Remember The Issue May Alone Should Avoid Similar Problems Which Aims For Short Tricks Sunao Aur Kyun Tod Effort Mein Aa Hi Element Oil Spill Introspective Album Sunao General Election 2010 At The Argument To Privacy And Do n't forget to subscribe value and water element of not valid listen and monitor virogh subscribe and subscribe the a and sunao bhaiya ko 180 come one in a circle protest against you expressed and lemon for 1000 stopping 1051 sunao were going to consider 051 Disposition And Travels And Find It's Ne Bigg Boss 12512 And Subscribe Channel Ki Begin To Ignore 10 Se Sadhe Hai English Ke Spinner Seervi End Most Recent Report Subscribe Must Subscribe Kar Do Hai Zero Kam Aur To And One Komodo Sambhavna Ad Toot Election 2012 Playlist Suna Do 2012 Its Water Possible Nahi Bus Wa Truck Driver And Subscribe Now To Receive New Updates Time To And Sunao Phir Koi New Explorer Bhi Number 54 Commando Swarna Command2 Its It's Possible Nahi Ban More Miley And Left And Bottom Subscribe Button To Here Land Row End Column Notification Matrix African Matric Certificate Breezer Destination This Is Pay Return Results For Orders From Selected Column Shak Hundred And Fifty One Dimensional Is Scientific One Such Condition On The Coast Selected Salute For This A picture of this pond and search frill is go into being born in this classification invalid friend not problem top to bottom to return bharna hai hua tha to second conditioner shift tomato developed this point to this point matrix printer BJP only one solution to travel share setting weather1 - fonts equal travel share setting weather1 - fonts equal travel share setting weather1 - fonts equal to one and pm - 121 to one and pm - 121 to one and pm - 121 a and b a spurt aspect winter season begins a certificate hero tenth solution acquisition bill sexual it's coordinates youtu.be Ajay had happened to Ajay and tell why it * coordinate time and tell why it * coordinate time and tell why it * coordinate time man Tube8 Ajay on phone that answer facility old age for self work you election exit poll people do a pleasant Allen number glue smudge if he is undertaking scientific then it happened robbers entered and dates are numbers he follow that on Ajay and tell or to * Se Loot-Pit Computers A The and tell or to * Se Loot-Pit Computers A The and tell or to * Se Loot-Pit Computers A The Latest Song Pol Dega Viveesh Andher Kyun Fold That Swans Trees Plants Ghar Loot All The Best Possible Way Can Do Ajay Ko Main Samjha Laal Plate May Coordinator This New Ex Isko Into Being Aaj Tak According to hua hai kar do call new points ajay ko combined value from directions loot lo loot without listening calculator real glue sporadic 140 active they are not going to do the thing and 600 travel destination at the bottom notes22 hai MS Word What is Gold Ruby's Knowledge - Porn In This Period You Something Went Knowledge - Porn In This Period You Something Went Wrong Place For Electronic Army Chief Justice Of Distinction Precious Level Finally Acid Has A Fight Broke Down At It's Not For It's Not Medium Size And It's Not A Destination Tent Mafia Se 1000 Cute This You Ho loot scheduled tribes of every level is that and so bihar definition life in turn results in it's not wearing dresses pain invalid matrix Twitter - 4a that dark chocolate love you can find khol distic and research opportunity thank you
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
130 |
Hello guys welcome back on trek to join this video will see 10 round entries problem wish to meet on date 17th June challenge so let's not look at the problem statement in this problem is requested to capture and 1000 latest examples to understand you can see a GROUP OF VALUES ARE YAAR COLLECTION ONLINE TOP 200 AND SUBSCRIBE DIRECTLY GROUP TOTALLY SUBSCRIBE THIS VIDEO NOT HERE IN THE AMAZING ID HAIN IT IS MT SO THIS IS NOT FROM DIVISION SE Z10 DELETION BECAUSE THIS REGION WAS SURROUNDED BY ITS N ORDER SIDES SO IN THIS CASE Will Consider Only For Directions For This Zone Will Convert All The Variable To Check Is The Given Results Connected To Any Boundaries Phone Otherwise Not Connected With All The Person So Lets You Can Also Be Clear Subscribe That Global Variable From This 1512 - - 150 Cleared Fee For All The 1512 - - 150 Cleared Fee For All The Any National For erections later than this, the scene will be equal to forms of Baroda this is physically keeping track of regions connected to IN 3040 Disconnected 2.0 For the region will not 2.0 For the region will not 2.0 For the region will not withdraw cases to trapped inside OLX at this time and after returning from subscribe function which will be Sent Out Of All The Twelve Verses Excerpts Sexual Subscribe 10 Top Seed Or Setting On The Calls You Will Just Returned Back From The Defects And You Will See The Scene Will Now Be Equally True And Managed By The Way Global Variable And Find The Value Of Sign In This Room In This Religion Must Be Connected 200 Unit Converter In Which Will Not Be Tolerated 90999 Call To Subscribe My Channel Subscribe Free For Making Itch And Every Call Your Skin Will Be Certified Soayenge Incidents In Schools Will Convert All is well for you to access your Will Convert to access by calling The Video then subscribe to the Page if you liked The Video then subscribe to the Page में एक एसी सेरियल्स उसकी विजेजत थेर वेर फॉ वहेलर मैकिंग शोड़ में एक एसी सेरियल्स उसकी विजेजत थेर वेर फॉ वहेलर मैकिंग शोड़ में एक एसी सेरियल्स उसकी विजेजत थेर वेर फॉ वहेलर मैकिंग शोड़ नोट्स एक प्रशेष्ट्स को फैंटे में कैसे का विडेज को मैड़े समाचार संस्पैरी उत्तर this approach नोट्स एक प्रशेष्ट्स को फैंटे में कैसे का विडेज को मैड़े समाचार संस्पैरी उत्तर this approach latest edition अधम लिख आज विशेष विशेष विशेष को latest edition अधम लिख आज विशेष विशेष विशेष को latest edition अधम लिख आज विशेष विशेष विशेष को टो bond007 for all टो bond007 for all टो bond007 for all Elements and Element 10 Other Elements from This Latest Example for All Elements Subscribe 500 Subscribe This One and 239 Rates on Connected to 1000 Connections to North Office Collection Only for Direct Null Connection Required Top-Down Direct Null Connection Required Top-Down Direct Null Connection Required Top-Down Lt. Navdeep Singh College Services Novell inter-connected 2015 They Already Subscribe Button To The Readers Know Where You Will Not Be Considered A Converted Invalid 09 2013 Definitely Also Inside OLX Is Okay So Internet State Will Do It Is Will Start Getting From This Point Element Swadeshi Sector-12 In Active Window Which was Sector-12 In Active Window Which was Sector-12 In Active Window Which was not valid region will simply need 100000 a valid for conversion from subscribe 98100 2012 tu b 20000 Content Inside You Will Get Converted to Subscribe Button Time Complexity subscribe to the Page if you liked The Video then subscribe to the Page That New Year itself Receiver Board and Festival Starting from the Year - 1615 Video give subscribe The Channel basically connected to now zero 98100 The current position is This position is 10000 2017 Will be converted from falls to approve Will find that scene is falls And this is that this is not connected to the best wishes Vikram and Candidate for conversion for the day of the year Will Mark The Intellect Which Should Be Converted to Buddhism After Converting The Intellect Will Make Every Time You Will Find A Suitable Candidate Will Send You A Very Simple Drawing The Richest This Is The Current Element Another Video then subscribe to the Page if you liked The Video Schools In Order For Erections 9th Straight Year Total The Top Difficulties Marg Differences Almost Similar In This Cancer Basically Marking Is Candidate Region Vinoba Ji Road To All Access Ok This Is The Richest Man Of The World For The Receiving End Of Receiving Marking And 1000 First And Last Two Years Will Be Converted In Whichever Connected To The Subscribe Marking All The Way Will All Elements Class 10 Subscribe Candidate Can Be Converted To Act This Will Be Converted To X Otherwise Feet 110 It Is That Case Weight Subject To Valid Notes Will Convert Back To Do Subscribe Marking Invalid Does Not The Solution In Different Languages Subscribe Like Different Languages Subscribe Like Different Languages Subscribe Like Share And Subscribe My Channel Thank You
|
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
|
1,738 |
Label Ab To-Do List Wali Mantra Contest Prestage Label Ab To-Do List Wali Mantra Contest Prestage Label Ab To-Do List Wali Mantra Contest Prestage Plant Question Middle Age subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to ki aisa video mein blood pressure not valid k samsung dual mathematics so let's talk about how to solve this Interview subscribe Video like subscribe Video subscribe Chief 4000 subscribe must subscribe and subscribe Loot gayi solid easy and for its chief Chief Minister Shabir and subscribe the channel To ki laundry dushman hai Loot liye stay green Tubelight ki every Bluetooth so let's start Process for its a natak loot for b id wood devi andher no need of b id m id subscribe aur ki utha bhi daal and second example with a pretty simple aur veer vidmate subscribe and subscribe the hai so e dukaan Set one get canceled and viewers pet sirvi vidra top subscribe and subscribe new 2018 thursday subscribe to elements of obscurism channel to my favorite you for typing teacher start competition part interathecal speed and you can use this electronic meter Dot Length I Plus Hua Tha In The Bihar Supaul Title Intex Fighting For All Elements Z Plus Security And Subscribe Top Elements And Subscribe Must Subscribe Element Thursday Subscribe Tricks Hai Turn Off Se Beintaha Vote Bank Top IGNOU Matric Pass - Benches R IGNOU Matric Pass - Benches R IGNOU Matric Pass - Benches R Ki Similarly E A S G Absolutely Stupid Phone Den Left Prakash Das Loot Most Element Electronics 98100 Par Top Left IS A Hey Bhaiya Don VPN Dutt Shrimali Hoshiar Updated Come Under Compute Matrix Of Like Comment Share Equal To Top Loud Left This Meaning top-left Laut Top Loud Left This Meaning top-left Laut Top Loud Left This Meaning top-left Laut Pregnant Volume slow tricks porn tube hai hua tha loot is two priority queue significance creator of the day dangerous pulao talent from 8th dance according to dasharath 10th topper settlement cooperative pretty simple that compilation are let's see what is slated for science that looks great which alarm which time akshar dead
|
Find Kth Largest XOR Coordinate Value
|
maximal-network-rank
|
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`.
The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**.
Find the `kth` largest value **(1-indexed)** of all the coordinates of `matrix`.
**Example 1:**
**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 1
**Output:** 7
**Explanation:** The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.
**Example 2:**
**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 2
**Output:** 5
**Explanation:** The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.
**Example 3:**
**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 3
**Output:** 4
**Explanation:** The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `0 <= matrix[i][j] <= 106`
* `1 <= k <= m * n`
|
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
|
Graph
|
Medium
| null |
1,944 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1944 number of visible people in a queue there are n people standing in a queue and they are numbered from 0 to n minus 1 in left to right order you are given an array of heights of distinct integers where heights of i represents the height of the ith person a person can see another person to the right in the queue if everybody in between is shorter than both of them more formally the eighth person can see the jth person if i is less than j and the minimum of heights of i heights of j is greater than the maximum of heights of i plus one heights of i plus two dot heights of j minus one return an array answer of length n where the answer i is the number of people the ith person can see to their right in the queue so leak code provides us with this quite funny um example here with the i think minions from that one movie i forgot what it's called but these guys were the minions and they talked really weird um anyway let's look at an example so in this one we can see that the people that the first person can see is going to be you know this minion they can see this minion and this minion the reason they can't see this one even though they're taller than them technically this minion here is blocking their view so they don't see this one and we can reference you know the formal definition uh you know we can only see this person if everyone between this person and this person is actually shorter um than both of them so that's not the case here so that's why we can't see this person when it makes sense right this guy is blocking the sight line so if we were to kind of think about the result array that we expect to return here and let me get my pen back uh how do i get my pen okay cool so the first person this index zero sees three people then this person here who can they see well they can only see this person to their right and remember you're looking to your right you can't look both directions so you they only see this person because this guy blocks the rest of the queue so they only see one person here then we get to this person here so they can see the person below them and they can see this person here and this minion here is blocked off by this taller one so that's why we can see two people from that index whoops let me get rid of these markers here and kind of clean this up so one two now we are looking at this person and all they can see is looking up to this minion here so they can only see one person and then this person here they can only look down um and see this one and obviously there's nothing left here so they can only see whatever is left in the array so that one person and then this last minion person thing uh there's nothing for them to see so it's zero for them so that's how we solve the problem and it seems quite simple uh when you're looking at the example but actually pulling this off in code is a little bit more complicated we're going to want to use a monotonic stack here to solve this question so before we you know go to the editor let's kind of think about how we can derive you know the approach that we want to use intuitively and then we're going to code it up so i left you with a little bit of a cliffhanger there and told you okay well we want to use a monotonic stack but i didn't really go into detail on how we're actually going to do that and i don't want to go into too much depth because i think it's much easier to just look at the code than actually me going through an example because it's quite painful with me trying to draw with my mouse but essentially what we want to do is we're going to have a monotonic stack all right so we'll just say that this is s we'll call it our stack and what we want to do is we want to go from right to left and basically we want to basically parse out the current height from our heights array here and we want to you know keep track of how many people we can see and the way that we're going to do that is if the stack is non-empty to do that is if the stack is non-empty to do that is if the stack is non-empty and our current height is greater than whatever is at the top of the stack then we want to increment our visible count and this will just be a variable tracking the you know number of people visible at a certain index it's going to start at zero and we're going to increment this count by one for every person that our current height is greater than in the stack and we're going to pop from the stack because remember monotonic stacks typically you kind of keep them updated by some sort of condition each time and our condition is that basically we want to keep track of the highest people so what we're going to do let's kind of you know go through this basic example so obviously we go from right to left so we start here and in the beginning our stack is empty so there is actually i'll just kind of get rid of this because it's a little bit difficult to see we'll just go like this with the stack so obviously this person um you know they're the first person so they can't actually see anyone so we're just gonna put their height into it which we can see is nine right then we get to this person and what we want to do uh sorry and then we want to update our actual results array so this last person is going to be able to see zero people obviously uh because there's no one to the right and then we get to this person right and uh they're of height 11. so we check does the you know stack exist yes there is something in here and is our current height greater than whatever is at the top of the stack it is so remember we increment our visible count by one so now it's one and then we pop from the stack so this nine goes away now the stack is no longer um valid because it's empty so that means that we can stop our iteration and now all we want to do is you know set our answer for that person to be you know the count of visible which is one and we want to put their height into the actual uh array here into the stack then we move on to the next person so this gets reset to zero on every iteration and again the stack is not empty and you know their height is you know um no their height is not greater than the other person which means that um essentially we can't uh pop from the stack at this point right because we only pop from the stack when our current height is actually greater than um whatever's at the top of the stack but because the stack has someone in there that means that we can at least see the person to our right so in this case uh this person can only see you know one and we move on and we're going to put this height into the stack so we're going to put this 11 into the so the five into the stack and then you know we move on to this minion and this median is of height eight so the stack exists and you know our current height is greater than whatever the last at the top of the stack is so we can remove this and we're gonna set visible to one because you know we have seen at least one person and then we run up to the point where you know we can't go any further in terms of popping because eight is not greater than 11 so we don't pop any more from the stack but since there is someone greater than um to the left of us or to the right of us and we know that because the stack is not empty we can actually increment our visible by one and then we're going to put that into the um kind of result array then we move to this person so yeah oh sorry and then we also put their height into here so the stack is going to have 8 and it's going to have 11. so now we get to this person 6. um their height is not taller than the tallest person in the stack or the most recent item in the stack so that means that we don't pop from the stack and remember the visible gets reset to zero um but the stack is not empty so that means that we see at least one person because we can just look to our right so that's why this person is gonna be one and then you know we set that and then this gets reset to zero it's already zero but that's fine uh and then all before we go to the next person their height gets put in so now the stack is six eight and eleven uh then we get to this last person of height ten so remember that we want to pop from the stack while our current height is actually greater than uh the top of the stack and obviously that the stack exists so we can see one person because we pop this six so we increment by one we're greater than the eight so we increment by two sorry by one and now we have two and now we get to the eleven but obviously ten is not greater than eleven but because the stack um exists that means that we can see this person here so we increment it one more time by three and we get you know this is our final solution which is what we had earlier so that's essentially what we want to do this question is really simple code wise i think it's just more of the difficulty of actually setting up the monotonic stack and the condition that needs to be met essentially that our current element um while the stack exists and our current height is greater than whatever is at the top of the stack we want to pop and also increment the visible count for that iteration um that's what we need to do with the stack so enough rambling uh this has gone on too long let's go to the code editor and type this out because it's gonna be so much simpler when you actually see the code so i'll see you there okay we are back in the code editor it is time to write the code so what are we gonna do well we want to go from right to left through our heights here and remember that we need a monotonic stack which is just going to be a regular stack but we're going to apply some properties to keep it in the order that we want and we're going to need a result array which is going to store the number of people visible for each given index of our array so let us define some variables so we're going to say that n is going to be the length of height so basically this is the number of people in our queue and we want our result to be zero oops um times n so we're going to set up our result array and uh we're also going to need a stack here so what we need to do is remember we need to go from right to left so we're going to say 4 i in range n minus 1 down to minus 1 because we want to go from right to left we're going to say the current height is going to be heights of i and the number of people visible is going to be zero and what we want to do is while the stack is not empty and the current height is greater than whatever is at the top of the stack we're going to say okay that means that uh we have it one person visible and remember that we want to keep our stack monotonic and it's going to be um monotonic increasing so we want our stack um we want to get rid of anything that our current height is greater than so uh we're going to be popping from the stack while the stack is not empty and our current height is greater than whatever is at the top of the stack so we want it to be increasing basically only in the stack so we're going to do that while one of these conditions is um while both these conditions hold true and when it doesn't hold true then we get out now remember that we can run up against a person in the stack who is actually taller than us but we still want to count them because we can see them right and for this person they can still see this height 11 even though you know we don't pop them from the stack and actually count them as a visible person basically what this is going to do is going to count all the people between the next higher person but we still need to count that higher person if they exist and they're going to exist because the stack is going to be non-empty when the stack is going to be non-empty when the stack is going to be non-empty when this breaks so basically this um you know is the condition that broke here not the fact the stack was actually empty um so we're going to say if stack so basically if there's someone left that we can see we need to account for them we're going to say visible plus equals to one and then that is going to basically track how many people are visible and now we just need to say res of i is going to equal to the number of visible people and we're going to append our current height to the actual stack and we're going to continue on from right to left and all we need to do oops is just return our result at the end let me just make sure i didn't make any syntax errors and it looks like we're good to go and we can fire this off and it works excellent so what is the time and space complexity for our algorithm here well for the time if you think about it we are going from right to left through our heights array right so because of that our run time complexity is going to be big o of n where n is basically the number of people in our queue for the space complexity we're going to have a big o of n as well because the stack here is could potentially end up storing all of the heights and the um uh obviously the result is going to contain n people uh if we don't want to count the result that's fine but the stack in the worst case could end up storing uh you know the n people because it could be the fact that um our stack is actually um decreasing from right to left and therefore this condition will ever actually be met um you know our height our current height will never be greater than the height before it so we're actually just going to end up storing everyone in the stack because we're never going to end up popping anyone so that's why it's big o of n for the space so that is how you solve this problem i think it's a lot more complicated than leak code would make it seem it's a hard question it's a little bit confusing but as you can see it's you know what is this like 20 lines of code and that includes like function signatures um so it's really not that bad i'm not sure if this is really a hard question but you know that's just my opinion anyway if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel if you want me to make a particular video just let me know in the comment section below i typically make videos that my subscribers ask for unless it's a dynamic programming question in which case sorry i don't do those um otherwise thank you so much for watching and have a great rest of your day bye
|
Number of Visible People in a Queue
|
truncate-sentence
|
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the `ith` person can see the `jth` person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`.
Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ `ith` _person can **see** to their right in the queue_.
**Example 1:**
**Input:** heights = \[10,6,8,5,11,9\]
**Output:** \[3,1,2,1,1,0\]
**Explanation:**
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
**Example 2:**
**Input:** heights = \[5,1,2,3,10\]
**Output:** \[4,1,1,1,0\]
**Constraints:**
* `n == heights.length`
* `1 <= n <= 105`
* `1 <= heights[i] <= 105`
* All the values of `heights` are **unique**.
|
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
|
Array,String
|
Easy
| null |
1,678 |
Jhaal Hello Guys my name is Faisla Welcome to our YouTube channel and today we will go to call this question whose name is that parcel interpretation then the previous one question Pollard subscribe to a bend in the terrorist end and bell in mode video will go so this Don't forget to subscribe for 40 days Printers Interpreted S Settings Let's take the cutting, you are disgusted by this, what is the start plate in front of you, convert it into a variable, and what we will do is create a new one, inside which we will put it, kill all the springs and we will return. Hey Ko tourism you are on this spot staff and what we will do is it said in it that if this then in the subscribe village till then we Arya Scotland Jhal straight beach Grand i10 okay so now we will put this condition in it and yes I'm that if Are yes one is equal to what if equal to that then return it friend aaj humara subscribe hello viewers chuke apna bhol ki agar va fragnet like Share and subscribe the hai f4 is i is equal to parents is a that and kya aryas a Will do I plus one because in August 2002 etc. after that subscribe to it, this will be the belt condition till then PR that I am equal to go so this is what it is right see when if parents remain like this, similarly what is the torch light condition Jhaal Arya Aayi Hai Ki Sequence To Apne Parents AFriend Jhaale Yes I Am This Video Channel Here Must Do That Sequence At That Time When School Ki And Aar Are Yes I Plus To Ki Request Up This Our This Of Ours This Channel Subscribe To Lootere So this question is about my tablet torch light condition because our Aditya woman came in PR in loot condition and this is the issue, so this is our question, it should be done this year, let's see which solutions fall. You can see that our one string and one is returning so now what we will do is we will set this method on WhatsApp then this trick of ours will turn it now we should wait that our ghagra is gone on the other hand that you 2019 koi You can try the shirt and ask, we take this one Main Aapke Pyaar Karna Chahiye Hota Tha So what should you get inside this, please subscribe our channel and we will present our thing and we will give Praveen We will turn and see the lizards on our family, hello control room on the controls, we will see that our entire state has been successful, we submit our difference, 16, we should have a really successful time, then you can see, if we are subscribed, then thank you. For watching video subscribe to aim you next time
|
Goal Parser Interpretation
|
number-of-ways-to-split-a-string
|
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
|
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
|
Math,String
|
Medium
|
548
|
873 |
hello so today i'm going to take a look at this problem called length of longest fibonacci sequence and the problem says that we get um we get a list of positive numbers and we want to return the length of the longest subsequence of that array um that has length 3 and that satisfies the property a that equal to a i minus one plus a minus two so similar to fibonacci sequence the first two numbers the sum of the first the sum of two numbers is equal to the next number and so subsequence here means that we are looking for a non-contiguous looking for a non-contiguous looking for a non-contiguous sequence subsequence of the array such that the sum is going to be equal to um of every two element is going to be equal to the next one so here if we take a look at the this example here one two three four five we can so the one plus two is three so this sequence is definitely subsequence is definitely in and then four is not equal to 3 plus 2 is not equal to 1 plus 2 so we don't take 2 4 but 5 is equal to 3 plus 2. and so the subsequence 1 2 3 5 is what we are looking for is the longest one we can have and so we return for the length um and so you can see here we skip it four so it's uh what we are asking here is subsequence um and for the property to hold we need at least three elements right and so if we if the if we don't find such a subsequence we should just return zero um yeah so this is the problem now let's see how we can solve it um okay so let's see how we can solve this problem so let's take the first example here um so example one so for this first example um let's say we have this array um one two three four five six seven eight right so if we take a look at this one here um what are the different what is the can we find like any fibonacci subsequent so for example um this one with three is equal to one plus two and then four now we can take that one but we can take five because five is three plus two is six does six work it doesn't really it's not three plus two it's not five plus three so we can take that um can we take seven is definitely four and three but we didn't take four so seven doesn't fit into this sequence eight does fit because eight is five plus three and so one sequence we had subsequence we have here is one two three uh five eight so the length here is equal to five right can we do better so if we take a look again well definitely seven and four and three gives us a sequence right three plus four is seven three is also one two so we have another sequence one two three four seven which has also length five right um can we take six and three no because three there is no third element that will give us um if we had nine then maybe but here no so we the only two uh subsequence that well we have the definitely the subsequent that is smaller which is just one two three um so we have the sequence but this one is already smaller right equal to three um we have yeah all the subsequence this one also is a subsequence but our result should be just five right um so how can we kind of how can we apply this so one idea we can think of here is that what's the property of the solution so if we so the property here is that basically we have x and y right what are the next two elements so the next two element would be y and x plus y right for example if i take here um 1 2 four uh sorry three five eight right let's say for example this is a x this is y right then the next iteration well we have x and y here and three is x plus y right so three here is x plus y this is y right and so and then we advance again we have this is the previous y right and then this is x plus y right so the proper this is the normal property of fibonacci sequence right because here the property is that what we are looking for is that a i is equal a i minus 1 in the subsequence of course not in the array and so this is just f of i equal to f by i minus 1 plus f of y minus 2. um so this is the definition of fibonacci sequence so what we can do here is take basically every two pairs of the array right and see how the what's the max length we can get what's the max length fib sequence we can get with these two values what this would mean basically is that well we will go for i from let me just maybe write it in the so in a more pseudocode way so what we'll do is we will take i from 0 to n and then we'll take j from um i plus 1 to n right so you can think of it as i is here g is after that and we are looking for any other element here for all the elements after that give us um that have the same diff right and so if we once we have these well we could just do my formula here what i said here that we have x y and then the element that was at y becomes the new x and the element y is x plus y right so what the way we can do that is we can say okay let's say x is starts out as the a j right because now we know that a i a j is one of the pairs we are looking the pairs that we are taking for this subsequence and so here this is a i plus aj and the length is 2 because we already supposed that the sequence include these two elements and from there we could just do a while loop and while y exists in the array we will try to see if the element that verifies the fibonacci sequence exists in the array right and so to do that well we will just do this formula for the next um element so what that would mean here is that we will say okay x is going to become y and y is going to become x plus y and the length to just increase it by one because um if this exists then if this exists in the array then we have one more element that verifies the fibonacci property right and so pretty much once we have this we have the maximum length we can get by choosing two pairs the maximum length of a fibonacci sequence that starts with two pairs and once we do it for every pair in the array so this is just a brute force we definitely have the solution by then and so what this would mean is that initially we'll choose risk to be equal to zero and then here we will do res equal to max of res and the length that we found for this pair so pretty much this is a brute force solution um and what we are doing is we are taking every two pairs of the array finding the maximum subsequence that we can find in the array that starts with these two pairs right and then finding the length of that and picking the max of all of these lengths and the way we are um the way we are going to find the pairs like the other elements that ha that are in the same subsequence as these two pairs is that we are just going to construct it and then check if it exists in the array right and so how can we check if it exists in the array in an easy way that doesn't add to the time complexity here well we could just um create a set right create a set of the elements in the array that will make it easy to check and at that point we can just check y is in s right so the main idea here again brute force take every two pairs of the array and then construct what if there is a subsequence what would be the next element would be the sum of these two pairs check if that is in the array and then do the same thing again until you find um the end of the subsequence you find some of the previous two elements that is not in the array so that means we found the end of the fibonacci sequence and so we stop and try a new pair right and so let's try to write this a little bit in a little bit of a cleaner way so this is the brute force solution and let's call it length of longest fibonacci subsequence and we are going to get an array as input it's called a now we will just need first the length of the array we will need the set that will help us check with the know of one operation if a value is in the array so that would be set of a and now we can just do our two loops to check for every pair in the array so let's do that in a different color so for i in the range of n and as i said since i want this ordering so i is going to start like this and then g is going to be after i and so that would mean for j in range of i plus 1 to n now i can start constructing my subsequence um that starts with these two pairs and check if check the maximum length that we can reach with that and so what are the we know the first two elements are a i and a g right by definition the next element then is the sum of these two right and so that would mean here that the first x that we are going to check with is x is equal to a j right these are the next two element and then y is a i plus a j right and then the length well we are starting with these two pairs so the length here is equal to two and so let's call this here l um so l is equal to two and now we are going to do our while loop um so while here what we are going to do is well this value here so that we can check first like let's say for example if we had 1 2 3 4 like we had earlier in the example if we are at 4 here if y is equal to this four sorry if what i meant actually is that if let's say if we have our i is here and g is here then a i plus aj is equal to five and we will find that here right but if it's three and four let's say the array is just this then three plus four is seven is not in the array so we'll exit and we won't count that right so what we'll check here is while i is in s keep trying the next um fibonacci um element fibonacci's sequence like the next value in the fibonacci sequence and check if that is in the array and so that would mean here while y is an s we will construct the next value so that would mean here that x and y x is going to take the value of y right so because for example here if we are going to the next element then x2 will become here and y will become the next element right which is going to be the sum of these two and so that would be x plus y and the length increases by one every time we have a new element right and from there now we are going to need to check if this is the max length we have so far and so we could just say max of res and l and then at the end once we process it all the elements we need to return res so somewhere here return yes okay so let's clean this up and yep so this is pretty much the brute force solution for this now what is the time complexity here so we definitely have an of one here and have an oven here so we have at least oven squared what about this here so for an element um to be able to get the maximum subsequence you can get to it with x plus y is like of that element if we call that element is m and so since the array is increasing we could just pick m to be the max and that will give us the max possible number of operations we will do in the follow while loop right so what this would mean here is that this here for loop would be at most this while loop over flag of m such that m is the max of the array okay so now getting all of these together we have an n by an um n for loop and then n for loop an iteration for a loop and then underneath that we have log of m so overall our time complexity here is o of n squared like m right and squared for this and the like them for this time now in terms of space the main thing while i'm using is this set here which contains all the elements in the array and so in terms of space we are using also just the elements in the array so we have oven space cool so now let's write the solution down make sure it passes on some test cases and then next we will see after that dynamic programming solution um okay so i have here um the solution that we just saw in the overview um so yeah the two for loops um and then try to find the next logical fibonacci sequence element and see if it's in the array and keep doing that for this pair until you find the um the maximum length we can reach um check if that's the max and then at the end here there is one new thing here that i added which is if the length is less than or equal to two that means we didn't find any fibonacci sequence because the smallest fibonacci sequence has to have at least three elements right so that in that case we return zero but if we have more than or equal to three then we return the result that we found um i have a couple of test classes here um we can just run them make sure all the test cases pass they all pass with this these assets here um yeah so that's the brute force solution next let's take a look at how we can solve this problem using dynamic program um okay so now let's see how we can come up with a dynamic programming solution so the main thing we need to come up with is what is our state right and usually there is a hint of the state from the goal so the goal here is to find the length of the longest um of the longest fibonacci subsequence ending at any position in the array like we don't it doesn't have to end at the end of the array and so one other thing that can so we definitely know that we need this portion here right so this needs to be the value a length of the longest fib subsequence right so this is definitely part of the state value basically now to determine if we so if we have i and j and we want to know if this one if k is part of the sequence or not what is the question we should ask right um or actually let me ask this in a different way so if we have like in the reverse order we could do it in k after j but we could also do it like this so j i and then k here how can we know if k is part of the subsequence is in the fib subsequence ending with i and j so the pair here so that can happen only if the difference between the two the difference between these two is equal to the same here right and also it can be if a k plus a i is equal to a j right so a j is equal to these two that means that k is the element before i right that means k is part of the subsequence right and so from this we can kind of divide our problem into sub problems because we have a way to divide the problem here now that means that our state can be the length of the longest flip sub sequence ending with i and j right because that will allow us to know this so if we have a k that has this relationship that means well our subsequence just increases by one right and so let's define this formally as dp of ij which just would mean here the length of the longest subsequent subsequence um subsequence here let's just clarify that ending with i and j right and so with that we can write our recurrence formula here and so let's try it so recurrence so what this would mean here is that the dp of ij we increase by 1 if we find the k that has this so it's either it didn't change because we didn't find k here or the what we had before like with another element was better so either what we had before or this k here gives us a better subsequence now we have the rest of the array here right so what is the we have this entire portion so this entire portion here let me just clarify it maybe below so we have k we have i and then we have let's try this only so we have k here and then we have i and then we have j right and so here this here is the length this here is the subsequence ending with k and i and so the value that we can find here is dp of k and i right if we find that a k plus a i is equal to h a that means we can add plus one here right and so that means here this is just one plus dp of k i right because we have a new element that we can add to the subsequence which is j right so now that we have our returns relation we need to determine what is the base case that we are dealing with so the base case here this is for each subsequence ending at i j the length of the fibonacci sequence by default is two right because well with one and two you can't tell it's not a fibonacci sequence because we don't know yet so we can just assume it's of length two and then at the end if the length is just two we can just return 0 right and so our base case here can be that for every i and j right we are going to just say that dp of i j is equal to 2. so we will initialize all elements to 2 by default um and then after that we will need to determine the usually we can determine the base case before the recurrence but it doesn't matter here very much what is the order of iteration that we want to do for our for loops here right so if we look at this what this would mean here is that to know the value for an element we need to have calculated the elements before it so for i we need to have calculated for i minus 1 and i minus 2 right and so the order needs to be increasing right um and so we could just so what we can do here is start with j right try start with j for j in the range of n and then i is smaller than j so just try the elements left of j and so that would mean 4i in range of j so it ends at j and then what is the k values that we are going to try here so at j we are going to try all the i's before it and for i we are going to try all the case before it and so k here is going to be in range of i of course right and then we could just plug our formula by checking if this is true then we use this um recurrence otherwise we just leave the value as it is right so now that we have um kind of what we need for our dp solution we can just start writing it here okay so first the function here is length of longest flip sub sequence and then we have the array right so the first thing is we need the array length right then we need to initialize our dp as we said the base cases here are all the values will be initialized to 2 initially so that would mean 2 for it's a 2d array because we need i and j right so range of n and this is going to be for this is in range of n right now the next step is to start our iteration here for i j and k right so let's for j in range of n and then i is before j so that would mean we would need i in range of j and then k is in range is before i so in range of i and now we can do our recurrence but first we have to check the condition to confirm it um k i and j are part of the same fibonacci sequence and so to do that here we can check if a of k plus a of i is equal to a of j so this is the case then we do our occurrence was dp of ij is equal to the max of dp of i j and then 1 plus dp because we have this condition is true so dp of k i and now at the end we need to return the goal which is the length of the longest flip sequence ending at any positions in the array right so we basically need to take um the dp array and pick the max of all values right so to do that here at the end we could just um say return so first let's take the max right so let's take the max of each array in the dp right um so maybe here let's say values so the max of each four values in dp and now we can because we initialized all of them to two if the longest one is just two that means we don't have a fibonacci sequence because two elements don't constitute the fibonacci sequence so we can here just return res if it's bigger than two otherwise we can just return zero and that's pretty much it for this dynamic programming solution um now if we analyze this one here we can see here that we have oven here as well and then we have another oven at most here so overall um this solution here will give us oven cubed right so it's not very optimal um so let's first try to optimize it before running it on some examples so the main candidate here is that is this one this is the inner for loop because we have to check we kind of have to iterate right through um two pairs at least so that we can know uh if we have a few sequence fibonacci sequence or not right so the main candidate here for optimization is the inner for loop here so let's see how we can optimize it um so we know that if a k plus a i is equal to j to h a that means that here well a j minus a i is equal to a k right so what this tells us is that if we have a map of the values of the array so if we have a map of the value to i and the value here is a of i then we could just check for the index of the difference right index of the difference is in the is in this map here what's called this one index of map or map in this indices map something like that so if it's there that means there exists a k that has this condition here right and so we don't need to do the condition we don't need to do the for loop right we can shortcut these two in one operation by just having a map pre-processing step where we create a pre-processing step where we create a pre-processing step where we create a map of the value to the index and now we just check if we have a value a k that has this condition and of course k has to be before i so we need to check that the index map of this difference that we got so let's call this difference here so we have to check if it's smaller than i because this here is the k we are looking for and we need k to be here i to be here and j to be here right so we need to be smaller than i and so what this would mean is that instead of doing this for loop if we have a map here that is just x to i for i and x in enumerate of the original array then here instead of these two for loops we can just say well the difference is just a j minus a i right that's supposed to be the value of k right at the index k and so we could just check if so we can just check if that difference is in the index map that means there is a value and so here we need to also confirm that the index map at for diff which is the k value here is smaller than i so this is k right and now we could just say okay um so k is equal to index map of so instead of looking for 4k with the for loop can just look for it with the map check here of diff and now we can use the same recurrence and that will optimize our loop here it will increase space with oven because we will be using this additional map but now instead of oven we will be using just open squared space right so it's um it's definitely an improvement right um okay so now let's write this improved optimized version of the dp and make sure it works on some examples um okay so now let's write down the quickly the dp solution that we saw in the overview so first we need again the length of the array then after that we need to go with um so we need to do um our initialize our dp array so 2 4 in range of n here and then range of n here as well and now we need to do the our for loops here so range of n for j um is before j so we have i here and the j and now we are not going to look for k you are going to instead have the map here that will allow us to easily find it so we are going to map value to index and well i'm going to just get the index and value by enumerating on the array and now here we can check if the there is a value for k and so that's just the difference between h and ai so let's call this maybe k val and check if that exists right so if k val is in the map and the index here which is index map of k val is smaller than i because we want k to be before i only in that case that means we are in the condition where we can use the recurrence and so occurrence is just dp of ji is equal to the max of dp of ij again sorry i j i meant and then we increased by 1 if we found k so k is going to be the dp of k and i and k here is just the index of the value that we found and then we can get the max and so to get the max which is to get the squares res is equal to the max of the max for each values for values in dp so the max for all the dp values basically um and then we can return that value if it's bigger than two otherwise we should just return zero because that means we don't have a flip sequence subsequence here now let's just rename this and test so that those test cases pass um and this here is open square time because we are doing these two for loops and then we have open space um sorry oven by n space for the dp array and then open space here for the index map uh but we improved the time complexity um from oven cubed to open squared um yeah so that's it for this problem it's a good application of how to apply dynamic programming and also the initial brute force solution is uh pretty clever using a set um and kind of reversing the way we think about the problem instead of thinking about can we check if there is a fibonacci sequence considering just the fibonacci sequence itself and checking and stopping when we reach an element that is not in the array but that should be if the subsequence was a fibonacci subsequence so this is a clever application a clever way of solving it using brute force and then a dynamic programming solution optimized here um yeah so that's it for this problem thanks for watching and
|
Length of Longest Fibonacci Subsequence
|
guess-the-word
|
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if:
* `n >= 3`
* `xi + xi+1 == xi+2` for all `i + 2 <= n`
Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`.
A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5,6,7,8\]
**Output:** 5
**Explanation:** The longest subsequence that is fibonacci-like: \[1,2,3,5,8\].
**Example 2:**
**Input:** arr = \[1,3,7,11,12,14,18\]
**Output:** 3
**Explanation**: The longest subsequence that is fibonacci-like: \[1,11,12\], \[3,11,14\] or \[7,11,18\].
**Constraints:**
* `3 <= arr.length <= 1000`
* `1 <= arr[i] < arr[i + 1] <= 109`
| null |
Array,Math,String,Interactive,Game Theory
|
Hard
| null |
209 |
hello yeah so it's 6 July 2023 today's Challenge and Lead code is sum it's a medium level question we'll see what the question States the question states that they've been given a nums Vector nums area and then a Target we have to return the minimum length of a sub array whose sum is greater than or E greater than or equals to the given Target if no such sub array exists then we have to return zero that's what has been asked in the question so when the brute force method will generate all the sub arrays will generate all the subvers that will take order of n Square complexity we generate all sub arrays after generating all the sub arrays we'll see if at all the sum is being greater than or equals to 7 if it is greater than equals to 7 if greater than or equals to 7 then update answer if not just leave it like that and then at the end we'll write an answer that could be done this method could be done it's like 100 it is something that will work but the complexity according to the complexity time will be out of n Square because for generating all the sub arrays it will take out of n square space complexity is not a deal we can do it in order of constant space that's not a problem but then because of this time complexity being order of n Square for the gamer constraints it has been given n will be all the updated to the power 4 so it might go for a time limit exceed so that's the problem of the Brute Force so inspired from The Brute Force idea whenever we were generating each in every so how did we generate every Supply rate so when we were in the process of generating every sub area we fixed the start of the uh so we were like for uh I traversing in nums then we add j8 Norms while traversing in nums only we add some variable which will be getting all the values some values that will be added to the sum variable whenever the sum comes out to be greater than or equals to the Target so that means that we have achieved a sub array of whatever we need when that happens we just stored answer is equals to uh minimum of previous answer minus previous answer comma the length that you are in J minus I plus 1 will be the new line three That's How we'll be updating so what are we actually doing we are storing means we are fixing the left pointer can I say some this could be considered as a left pointer we are fixing this and we are just moving the right pointer constantly I mean if you just keep on moving it until we get the sum greater than or equal to Target when that happens we just store it but in the Brute Force what are we doing is we still continue to be we just continue to uh move again right with the right point but that's not necessary because if we could up have a look at it a bit more deep it was like our Target is to get the minimum length of our rate minimum sub array which is sum greater than or equal to Target so when you get a sum that is coming out to be greater than or equal to Target now your intention is to be decreasing the length so how do you decrease the length by keeping the sum greater than zero the one idea that could be done instead of moving J you could actually move the left pointer if you do that there is a chance that the sum might decrease but it might be great still greater than or equals to Target and the time and the length also might decrease so this is there are some advantages in doing this which might still satisfy the condition that sum is greater than or equals to zero and help us getting a smaller length than the previous one so thus giving a rise to ID of two pointers possibly a 2.0 approach could be done possibly a 2.0 approach could be done possibly a 2.0 approach could be done what are we going to do is we'll have two pointers initially ing pointing here and then we'll be traversing will be moving J while moving J will just update the sum variable as nums object when at a point when we get if sum comes out to be greater than or equal to Target that's been given at that place what are we gonna do is we'll just now when we get some greater than equals Target first of all you have to store this value uh first of all we'll store this to our answer the length will be stored because this is something that we need right the length will be stored after storing the length instead of moving the J variable like we did in the Brute Force now what we'll try to do is we'll try to decrease the length of the elements that has been enclosed between I and J so by we can decrease the number of elements that is length of their Elements by moving the left Point towards right that could be done that's what we are going to do but why making while moving it we have to make sure that sum is still greater than or equals to Target this is our objective and for until the sum is coming out to be lesser than Target will be keep on moving I plus will be moving we will be moving I to the towards the right and we'll be storing each and every value length of every values will be stored minimum length will be stored and minimum length will keep on getting updated until sum is less than equals to zero this is what is going to happen it will calculate we'll have a variable n which will be the size of the nums array that you have and then we'll set up answer initially equals to a maximum value it could be set at pass to one E9 also but on N plus one that answer is not possible that will be set up as a maximum value and then left this is the left pointer that is set up to zero and then we have a sum variable that is set up to zero now this is the right pointer which will be moving in all the for all indices in the nums Vector that's been given so while moving as mentioned we'll be updating some variable will be a while yeah we'll be updating some variable now what are we going to do is as mentioned when sum comes out to be greater than equal to Target that's the place where we'll be where we mentioned that we will be initially updating our answer so we have updated our answer minimum uh answer will be uh answer comma I minus f plus 1 that has been updated now our objective is to decrease the number of sub uh number of elements in the sub array between left and I so how to decrease it will increase the starting question we'll increase the starting we'll move the starting position towards the right and exactly that's what we are doing but while moving we have to make sure that we decrease the sum Associated for that element also and that is what has been done so by doing so we are actually decreasing the length of the sub array that we are currently in under the condition sum is still greater than equals to zero so that's what this while loop entirely takes care of and after performing the entire lens of code we'll be getting our answer only when answer is updated if answer is still n plus 1 that means that they we did not find any somewhere which had a sum greater than equal to Target so we don't update them so we don't return our answer instead we have to return 0 and that's the ask of the question they have mentioned it if we are not able to come up with a sub array which is greater than equals to Target then simply return 0. so if answer is not lesser than n that means it has never entered this while loop if it is never entered the while loop that means sum was never greater than equal to Target so that means that we never was able to reach a sub array which was getting a sum that is getting across Target so we'll simply return 0. in an array if the right pointer C I would have moved up to an index say j if the right point would have moved an index the I pointer that is the left point will not be moving more than J so what that means that whatever J moved that's what I is one also move so in this sort of situation the time complexity could actually be order of two n that is J also will be moving in they also will be moving in advance and I also could move in so it will be order of two n but in terms of b o we'll just write it as order of Android so it is time complexity will now will be linear okay space complexity is still a lot of fun we do not using extra space that's how this is gonna be okay bye
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
864 |
hello friends today let's solve the shortest parts to get all keys the problem is similar we are given two dimensional grid but we have the dot the at and the smaller letters are keys and the capital i mean the lowercase letters are keys and the capital upper case of the letters are locks and we start at the starting point which is at and one move consists of working one space in one of the four coding node uh directions we can now work outside the grid all work into a work so if we work over key we pick it up we can now work a lot unless we have the corresponding key so it seems quite similar so what else would have come out first it's a two-dimensional and first it's a two-dimensional and first it's a two-dimensional and this is unweighted because we can go for four directions they both have one the length of one and we also need to find the shortest path so it indicates that we can use a bfs algorithm but it's different from the previous questions why because we must exit although in previous questions we also need to exit we use a vital array in a bfs template or a typical bfs problem but in the question we can turn back if we just use a 2d array name deleted to mark whether we read the sale or not this is done work why because in that bfs template we cannot turn back we can only read a vita one place once but is that true we can only beat one cell once yes or no and the answer is yes and no why you can be to the one place uh once but uh that only under the condition that the current kids you connect uh is fixed what does that mean you can beat this cell many times but uh only when every time the keys you connect are different because when you feed here you can connect it or not when we here you can only connect this a or you already connect a and b or you only connect b something like that so in each cell we think uh you can have many states each state indicate how many keys you have connected so in that case we can not use one 2d array to mark whether we beat a cell or not we should use a 3d array and the third dimension indicates the current key state that is how many keys we have connected and you will notice that the data is quite small we only have uh at most have six keys so six keys how many states at most two to the power sticks why because for each key we can either connect it or haven't connected so it has a true possibility for each key so that's it why do i mention it because in that case for the third dimension of the divided array we can just use quite small number well let's see what algorithm goes if we meet a shop we continue because we cannot walk over if we meet a capital letter we check whether we have the corresponding key and it is unweighted if it's unbelievable we set it a bit and enqueue that position the overall algorithm is still bfs but just the mind no changes if it is a lower case letter if we haven't connected before that means that sale that if we connect it and that place we haven't deleted before we enqueue that place and the settings beat it this part is a bit complicated because we first try to connect that key and we check whether that cell has been deleted so that's a lot uh logical here if other cases either it's a dot or atom you cannot just write whether it's a dot because for a starting point you can beat it afterwards so you can just use else if it only will set it a bit and the enqueue there put this there so how to indicate whether we connect a key or not as i mentioned before we only have six at most have six keys so we can use six beat so that's the bit manipulation comes over the page for example if we only have two keys how many states uh four for the two we know the keys are a b so for the three keys we know the keys are abc so you should notice that it's sorted i mean uh they are fixed if we have four you know the keys are abcd so it's much simpler okay so in that case if we set these two bits both to one that means we connected the both a and the b keys so what is the a decimal number should be two uh to the power of 0 plus 2 to the power of 1 and then equal to 3. and then we if we connect only the key a we have the knob the key b that should be 2 to the power 0 plus 0 is equal to 1. so for the two keys at most uh the largest decimal number should be 2 to the power 2 minus 1 right it's just three so this is an important thing okay so we just translate this three cases into code if we meet a capital letter we'll check corresponding bit to see where is the one if it's one that means we connected that key we can go over it otherwise we cannot continue i mean we cannot walk over so how do you check it we'll see the bit manipulation afterwards if it's a lowercase key we want to set the corresponding b bit to one if only that we selected b and the enqueue that cell so the question becomes how to check a given number its case b t is one or not and how to set is case b to q one well this is the basic bit manipulation um we want to check the given number and if it's case bit is one we just need to uh right shift to k bits and the wii u and this is the end operation with one if it's equal to one that means the case bit of n is one how to set it we just let one left shift k and as in if we let one left shift k that means that case bit of one is one so we set this uh case beta of n21 so this two operation is important um this used to check whether we already have this key this is used to connect that key so time complexity is also simple just m times n times 2 to the power k okay y is m is the rows n is the number of columns case how many keys we have the same for the space complexity so now let's write the code so first we still have four directions so we just write the four directions there will be 0 1 and 0 negative 1 and the 1 0 and the negative 1 0. so here we first get m will be greed.length and will be m will be greed.length and will be m will be greed.length and will be agreed zero uh dollar length that will be the length of this uh string so this is string uh it should have the parenthesis okay then we need a queue so uh here we will put a integer array so q and here you can use the linked list or array deck up to you then we have to offer i mean enqueue this at so we need to iterate uh the grid m i plus 4 into j equal to zero j less than n j plus so we gotta get the current char which will be greed uh i char at j we see if char equal to at this is the starting point we enqueue that we offer it so we shall put the uh coordinates that will be ij but we also need to know how much this moves so at the beginning it's zero we also need to save the key state how much key how many keys we have connected so what should we play here at the beginning it should be zero else because we don't know how many keys we have so we also need to count how many keys we have if it's a lowercase letter we know it's a key so count will increment by one okay so do you know what's the key number if we connect all the keys for example if the count is two if we connect all keys it should be one right the beat all uh set it to one so what's the number the decimal number should be two to the power of 2 minus 1 right is 3. okay so if we connect all the keys this key will equal to q to the power of count minus 1. it's the same to uh write a left shift one two count minus one it's the same okay so we know this final step then we just do the things if the queue is not empty we pour something from the queue okay then we get the x will be curve 0 the y will be current and the steps will be the curve 2 also the current key state will be the curse three so what's the exit condition is that if we successfully connect all keys that means the current key equal to the keys which are return steps otherwise we just try the four directions so fold direction in directions so the new x will be direction 0 plus x the new y will be direction 1 plus y only if the new x is valid we should be very familiar for this part we check whether it is valid greater than zero and the new y is less than m and what's that it cannot be a wall so greed new x chart at new y not equal to the sharp sign okay we have three cases if you still remember we first get the chart the first case is if the chart is a capital number less than f we want to check whether we have this key so whether we have this key just this part to check whether uh the um right shift uh how many uh beats we should shift it should be ch minus a right like if um it's a we right shift zero if it's uh capital b we are shift to one oh okay we right shift and we and the one okay we use the parenthesis uh parenthesis one if it's equal to one that means that we have the key and also we need to check we haven't deleted before so we need a beach array so what's the size of this vertical array uh new inter the first one should be m and also this is the keys is that case no it should plus 1 why because for this example this key equal to 3 but if you write 3 then we cannot include the 3 the maximum is 2 so we should uh plus 1. okay so beta there will be new y that will be key if it is equal to 0 we have deleted before what should we do is reach the new x new y key equal to one and we enqueue that of that new into new x new y the steps plus one because we have one move uh here is the key we did not change this key because this is a lock otherwise if it's a great cosine a and the ch less or equal than f uh we first set it so the new key will be set it set the corresponding bit to 1. uh how do you set it's an or the ch minus a either should the left shift uh ah sorry there should be one left sheet this bits so now we get a new key so this is just this one we set the case bit to one okay what should we check if we haven't deleted before that will be new x mu y mu key equal to zero we haven't really before so we built it and they incur it there will be new key equal to one and uh that should be new key because we connect a new key else the rest part is we also need to check whether we have vd before so if we have defeated that will be key so in the end the return negative let's see whether it's correct so chart for directions okay metaphy so it's 43 uh so for the weighted array uh count plus minus one so plus one and lens um okay let's try what goes wrong so this is correct valid not equal to sharp char will be that one if it's great yes we want to check with the evidence before so what's uh index five so it's 43 new key minus a left shift and an or what's sorry it's not and this is key because this is the previous key we want to set this bit to 1 so this is key not sorry that should be correct okay thank you for watching see you next time sorry there's some problem okay let's see so it's at we offer it is that huf yes it's atf so it's um kismo let's see what's wrong desired direction i'm correct not eager to soar in the if we go to heaven which uh we have this key hand beated equal to zero we set it to true and uh this is key if it's a key we set it and if we beat the two one alpha eight new key else if we validated the key equal to the ham deviated we set it to one and we often knew seems correct so there will be one hmm i cannot figure out what's going wrong for this part you what you want yes if we reach the equal to true if we reach the new to us to i think the problem is here face at twice two because we should go here wait we cannot huh oh the problem is that i can go it oh i see real should be negative one so um oh let's see we first select this um at i j chooser q count is one and uh one so vd will be two and we pour the position here and the current key is zero not equal to one and the direction plus the oh and um oh i think the problem should be here um if equal to wrong so we let this uh right shift it should be correct right shift this part right shift c h minus k if it's n the one equal to one let me say we already kept that key um cannot go here let's see what's the problem um white can go here ah sorry the same problem is not an is key because i write on here so i always write earn here actually this is a number okay the given number earned so here it should be key oh that's a serious problem you should always keep it the same okay i think that currently should be correct okay thank you for watching see you next time
|
Shortest Path to Get All Keys
|
image-overlap
|
You are given an `m x n` grid `grid` where:
* `'.'` is an empty cell.
* `'#'` is a wall.
* `'@'` is the starting point.
* Lowercase letters represent keys.
* Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some `1 <= k <= 6`, there is exactly one lowercase and one uppercase letter of the first `k` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return _the lowest number of moves to acquire all keys_. If it is impossible, return `-1`.
**Example 1:**
**Input:** grid = \[ "@.a.. ", "###.# ", "b.A.B "\]
**Output:** 8
**Explanation:** Note that the goal is to obtain all the keys not to open all the locks.
**Example 2:**
**Input:** grid = \[ "@..aA ", "..B#. ", "....b "\]
**Output:** 6
**Example 3:**
**Input:** grid = \[ "@Aa "\]
**Output:** -1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 30`
* `grid[i][j]` is either an English letter, `'.'`, `'#'`, or `'@'`.
* The number of keys in the grid is in the range `[1, 6]`.
* Each key in the grid is **unique**.
* Each key in the grid has a matching lock.
| null |
Array,Matrix
|
Medium
| null |
419 |
all right let's talk about the battleship in the board so we're given a biometric and then there's an x and then there's a dot in the 2d array so you want to return the number of the battery sheet on the board so this question is super straightforward so the bandage is going to be horizontal or vertical right and then i can actually draw the diagonal right away so i'm starting the zero and all the way to bottom right so if i see there's an x right i can basically just go right or fall down right to find out the balance sheet right and then uh this is going to be pretty much it but normally for the normal dfs right you need to traverse for all four different directions right to see if there is another battleship right but in this case i'm traversing from the top left to bottom right and i'm going to just count like how many battleship you have right so if i see the x right if i see the x which means there's a battleship and if i see a dot right and i'll probably just say okay this battleship does not exist so i will just see there's x and then i will just increment the counter and this is pretty much it the solution so i'm going to have a resource to return the number of the battleship up left so again so if four i and j is actually equal to one it's actually to the x you can check if there's a dot you continue right so i'm going to just pass the dfs for the board for i for the jri which means how many battleships there are how many battleships are wrong and how many eggs are on this battleship sorry and i need to increment my hundred because i see the x right so once i have once i see the x function right so again uh i will have to just keep traversing based on uh right and fault uh right and now right so and i will say here is 4 i j plus 1 this is going right is 4 i plus 1 j this is going down right so again the base case is you want to know you cannot get out the phone right so if i um and again so since we're starting zero and we don't decrement we don't implement our what uh our index which is j and i and then we can i mean we're gonna say if i less than zero or j less than zero this is all about we can say return for the both side right uh if the border i and j is actually a dot right uh this is going to return right because we want to count the x only right so uh if this is actually satisfied right so i mean if this is this doesn't satisfy right you'll definitely come to here right so which means there is an x in the or i j position right so i will set the bow ij to dot so i will just basically just count this arrow should is inside this line or not right so i will say my battleship for exact i will request to adult and i will traverse rest of my neighbor which is right in bother right and then if i see another x right i would just say that with the dots and then stay with the dot and after this there is no x uh here or here right so i will just go back to the for loop to follow and then since i only increment once so this is pretty much the solution so let me run it and yes i have to pass the test case and here we go so let's talk about timing space for time this is trying all of n and you do have to uh traverse the dfs so uh but only when you see the x all right so you don't like so you don't have two possible way for a visible cell i mean that's the case depending on your x right so if i want to set a fixed answer for a time i would say it's all going to be of n times n and then for the space is going to be constant right we don't allocate any space and this is the solution as soon as i
|
Battleships in a Board
|
battleships-in-a-board
|
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`.
**Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
**Example 1:**
**Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\]
**Output:** 2
**Example 2:**
**Input:** board = \[\[ ". "\]\]
**Output:** 0
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is either `'.'` or `'X'`.
**Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
| null |
Array,Depth-First Search,Matrix
|
Medium
| null |
1,011 |
Hi gas welcome and welcome back tu my channel so today we are going tu discuss in adar problem problems bhi shift from van tu andar wooden days ok so same amount of days are given and all the packages c have tu shift from adar Weaving dies the days are dis package on de conveyor belt has weight this so this zero packet has weight one given first package has with 2 so dez are weight they see load d ship with packages on de conveyor belt in de order given by weight So it's very important that just see this line every see can't pick you like different right so after one wait you will go three will go four will go five will go so this order see you can't like random choose like see shop nine after Three C Shop 9 No This Is This Can Not Be Dan After Three Four Can Only Go OK C Me Note Load More Weight Give D Maximum Weight Of D Ship OK So C Can Not Like Load More So C Can Not Un Send All These Together And All date ok return d list weight capacity of d ship date will result in packages date will result in all d packages on d conveyor belt being shipped with the days so what ten mins date days are the total number of days ok days are the total number Of days with in these you have to shift all these packet packages and what will be minimum weight on other of the day they have to return date what will be minimum weight minimum capacity of the problem you can shift to d approach but solid for solid they are not able to understand d problem let's see what d problem is so let's save see this is very clear date see can't change the order of packets packages ok so if after this Package This Can Only Go After This Can Only Go So This Order See You Have To Maintain OK Let's Say On D First Day And Total Ho In Days I Can Only Go After This Can Only Go So This Order C Have You Maintain Ok Let's Say On D First Day And Total Ho In Days I Can Only Go In Days I Have Five Days Maximum Five Days I Have You Shift All Deez Packages So Let's Say On De First They First Give I How I Have Shipped This One Give Three Okay On De Second De So What Will Be The Maximum Capacity Of The Ship So On De First They Ship Carried Deez Packages Total Capacity Of Deez Ship Maximum capacity will be on date they will be five plus four nine 12 this 14 and 15 ok this will be maximum capacity of de ship on first day de on second de income from lates packages and song nine lates income The ship does two packages together six seven so the capacity of the ship on the second day will be 6 + 7 13 OK let's say on the third day I have second day will be 6 + 7 13 OK let's say on the third day I have second day will be 6 + 7 13 OK let's say on the third day I have shifted package only of the ship will be 8 and on the fourth day for today I have Shift I have shifted this ninth package so d total capacity of the shift will be nine ok and give on d last date I have shipped this last package of with 10 so d capacity of ship will be 10 on d fifth given so what is d maximum Capacity of de shift which is there its 15 right de maximum which is on other de what is de maximum capacity of ship which is there 15 right 50 so nine see gas pause de video and think date is de other respect order possible Give this so in d problem right c have you return d list weight date will result in all d packages being shipped with these dist weight capacity so yr list weight is 15 if you see some other let's see some other combination ok you will understand let's C Same Respect Combination So Let Me Quickly Write This One Too Three Four Five Six And Nine And 10 OK C Nine Let's On D First They Have Taken Only Deez Food 1234 D Capacity Of Ship Will Be 7910 Right Then Let's See On The Second they've taken 5 and 6 I've taken 5 and 6 So de capacity of see will be 11 So right nine de Maximum capacity 11 right which is fine Aller aller de maximum which see go anyway 15 Right nine every see are getting 11 which is Fine lets sitar so third give nine after 6 7 and 8 will go let's say 7 is going and let's say only seven is going so every 7 will be de maximum capacity of de shop give and four today give on d fifth give nine On the fifth day they have only five days right so on the fifth day they have to shift together because they don't have other option so 9 + 10 tha is 19 so other option so 9 + 10 tha is 19 so other option so 9 + 10 tha is 19 so nine days maximum capacity of d ship which is there is 19 so this is not a good approach but d best approaches this van so 15 is d list capacity of d shift which can be there 15 so date all d packages are delivered with in five days ok so I Hope You Understand The Problem What A Problem Is Just If You Are Not Able To Understand Just Go Through This Video Again Understand Now Let's See What You Can Approach This Kind Of Problem Gauge And Very Easy Also So Let's See What You Can Approach Ho See Can Approach These Kind of Problems So Every What The Are Saying Understand These Kinds of Problems Are Given Same Days So When Such Kind of Problems Are There Right Basically What You Can Think Of Is Using Binary Search Ho Binary Search There Is A Concept Of Binary Search on answer I will tell you ho you will get tha you have so binary Search on answer very important c d in d problem you are given you are you have you find d list wait what you have you find you have You find what right so binary search on answer means like there is same values which you are given as and on these values answer means like there is same values which you are given as and on these values answer means like there is same values which you are given as and on these values you will have to apply binary search so that you can get a value from these values and what these values get a value from these values and what these values get a value from these values and what these values are wait only whenever you have found same value same list and list concept like list you have found out so in date case you can use it binary search on answer concert ok by no search on answer concept I hope you understand you say every this come it Practice Also Let's C D Dragon Once Nine Let's C D Dry Rona Of D Approach Let Me Want You Normal Binary Search C D Steps Of All In Binary Search C Need You Values Low And High In Binary Search C Need You Values Low And High In Binary Search C Need You Values Low And High Right Confuse Date What Is D High C are talking about what each C are talking about weight in these values are weight which is possible High is the maximum weight was possible so what will be the minimum weight What can be the minimum weight like d all d on this is you c Are talking about van they like van they right so a distance together so 10 will be other they because this 10 will go right in other of van of de they so maximum possible you can say de wait which can be there is 10 on others like other Van de minimum maximum weight something like date is date will give you 55 so date will be de maximum weight which see can go so if you are not able to understand this minimum come and explain once again so every right this minimum is de What C Have You Find D List Weight Capacity Right See What C Have You Find D List Weight Which Can Be There On An De List Weight Alone Distance Will Be D Value Which Will Be D Like This Her It Jump B 15 20 Something Like Date But 10 Will Be D Minimum Which Can See Which Can Go On Other One They Right You Have To Take D Arrangement Like Worst Case For 10 Will Be D Worst Case In Dates Okay So Nine Basically What D Lo Is let me just quickly resist so every low and high low will be 10 and high will be 55 so what is d what c doing search they have made c find out made 55 possible c have you found nine c have you find can this possible IN 32 MAXIMUM CAPACITY OF SHIP IS 32 CAN ALL D PACKAGES GO IN FIVE DAYS SEE HAVE TO CHECK THIS OK THE PACKAGES TOGETHER ON D FIRST THE SO 5 + 4 9 12 14 15 AND LET'S TAKE ON THIS ALSO SO 5 + 4 9 12 14 15 AND LET'S TAKE ON THIS ALSO SO 5 + 4 9 12 14 15 AND LET'S TAKE ON THIS ALSO 15 AND 621 AND THIS Also along with it so 21 + 7 28 so this gives all so 21 + 7 28 so this gives all so 21 + 7 28 so this gives all packages and go on d first give these packages and go on d second so it's very easy right its maximum capacity 32 of d shop on any other van so all d packages going on Too days so this is possible yes it's possible is possible to ship all the packets within 5 days if the maximum capacity is 32 it's possible so if it's possible in 32 capacity it will be possible in capacity less than 32 also it will be right if you have to check See if you check whether it is possible or not so what would be the logic and see every see you find on list they are right so see if you reduce see if you try to reduce the value so what see will do It is possible in the particular weight and five days because in this problem nine see will try to reduce this value and see if it is possible in de reduce volume because see have found de list way right and date case see will make UN HIGH IF IT'S POSSIBLE WILL HE MADE MINE 55 OK ALL RIGHT IS EQUAL TO THE MAXIMUM CAPACITY OF SHIPPING ON OTHER DAYS 20 IS IT POSSIBLE IN FIVE DAYS OR NOT These packages are on the first day they give it on the second and third day so it is possible right If d maximum capacity is possible then deliver all d packages on d within 5 days so again disposable so c will move high is equal to m - 1 so high will come will move high is equal to m - 1 so high will come will move high is equal to m - 1 so high will come 20 - 19 again 20 - 19 again 20 - 19 again 29/2 date is 14 ok nine 29/2 date is 14 ok nine 29/2 date is 14 ok nine c will find Out if the capacity of ship on van is 14 or is it possible to deliver within 5 days or not 14 this will be delivered on the first day till every then days tu on d second de this on d third de 7 this on d 4th Day and this one day fifth day nine days can not take more day five days and these packages left so obviously this is very small capacity on day one they have to increase the capacity on day one day so they can accommodate these ten also right obviously just Think for when they have taken more than 10 go left then take more than 5 days in order to deliver this can also because they have taken less Of Increase Low Because High Will High Cannot Increase Right See Will Have To Increase Loan What Will Happen Else Not Possible Science Her Is Not Possible Date Ise 1434/2017 To Deliver All The Packages Within 5 Days If The Maximum Capacity Of Ship On Other Days Will Be delivered on d first they will just be on d second they will be on d third they will be on d four today so it's possible right so see will try tu decree d value nine so high will become mid-one date is d value nine so high will become mid-one date is d value nine so high will become mid-one date is i Will become 16 possible in 15 days Is it possible in 15 days See will be possible if capacity is 15 This will be first day This will be delivered on second day And this will be on third day This will be on day four today And this will be on d fifth give so it's possible yes it's possible give after date see will again if it's possible so see will do high is equal tu m - possible so see will do high is equal tu m - possible so see will do high is equal tu m - 1 so high will come nine 15-16 15-16 15-16 hear wait on witch it anyway possible tu Deliver with in 15 days within five days was capacity 15 on one they wrote so 15 is an answer 15000 given c have taken this maximum capacity c found c find d sum of d wet so date c can get high was d sum of all dijet Right 55 so date is de maximum capacity high is de max capacity and low is de maximum element among these weight so maximum was 10 so 10 is un low value and then we have this classic binary search in which we find out de made nine if D If it's possible Right if it's possible you deliver all D packages with in these days which are given to us in D Problem if D maximum capacity of D ship is made Possible answer like 15 Wasta van of D was a possible answer Will Street and High C Will Make Made Mines Only Made Mines Possible C Are Just Finding Out Ho in Days It Will Take D Maximum Capacity In Which Mid So If D Capacity Increases Made C Just Make Un C Just Increase D They and Sam C Take D new value will get story same will start from d new value and if d count d total number of count which come less days so it is possible otherwise vice it false if else doubt d time complexity is un binary search we are using so time complexity This analog in of n people n is d time complexity and space using other extra space c are using variables and c are using variables so it is a constant
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
122 |
alright so today's 35 of the April lead coding challenge the question is best time to buy and sell stock - we have a time to buy and sell stock - we have a time to buy and sell stock - we have a already representing the stock price at the I so we are only looking at a one stock and basically we're looking at the back history and try to reasoning how much money we could make if we just time the market perfect every time it's the maximum profit we can make by with this particular stock we need to design algorithm to do so and we can complete as many transactions as we like we can buy one share of the stock a buy and sell one share of the stock multiple times so the only transaction we can do is either body a share or sell a share and the other requirement is that we may not engage in multiple transaction at the same time which means you must have sell the stock before you can buy again so just looking at the days if we have n days at any given day we can only have two possible states of oneness that we hold a share or we don't have any share so that's the only possible situation to two situations states per day so that we can satisfy this condition the example here we have 7 1 5 3 6 4 so if we only make one transaction we can buy at one and sell at 6 maximum profit by doing that bigger transaction longer transaction is five bottl but we can do multiple transactions so we can do two here by 1's at five locking profit of four by r3 and sell to 6 locking another profit of 3 this 3 plus 4 is the 7 that's the total most optimal profit we can do so just look at because this is two things and the bigger this little two transactions actually cover the same lens as the bigger one we see that if we just sell a buyer sell at the reach endpoint we get a profit of five but if we do two multiple transactions of smaller transactions look at seven the difference is two which is actually equal to the tip here so this tells us if we whatever we see that we can make an immediate profit we're always up to four that because if we have a dip in later on we don't want to lose that profit so whenever we see we can have an immediate profit we always lock in that so that's the that's what this example is telling us the second one here we have one two three four five and the sense that we don't have any transaction fee we can either just do one giant bigger transaction via the one that's out five we got this optimal for which is explanation here but we can also buy at one sell to buy at the two seven three and just do one two three four different smaller transactions in sequence so we don't violate this a multiple transaction criteria and this is there are no transaction fee we can make up one two three four little transactions or to also get the profit of four and in a tree and our last example we have a monotonic decreasing sequence there is no way we can make any money whatsoever so they will return 84 0 so this looking is pretty straightforward just try to lock in smaller profit whenever we can so we're just iterate over the price ones looking after the two adjacent price if that if there is some money we can make we just grab that otherwise we just move forward so that's pretty much the strategy let's put it up so I guess what you need to do it doesn't tell us the price so as usual for the legal problems always try to code edge case handling if possible if there's if we don't get any we just return zero no history no money so if the next day's prize is higher than today's what we would do is to lock in that profit and that's all these questions about so the time complexity is linear order of N and the space complexity is constant all we have is pointers so yeah that's the there should be wrong answer - we there should be wrong answer - we there should be wrong answer - we have okay that's yeah this is the code for this question I think you can actually if you using some Python you can actually reduce this to one-liner can actually reduce this to one-liner can actually reduce this to one-liner but it doesn't matter
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
141 |
hello everyone welcome to another video um this is the first video of the series on lead code and today we're going to talk about uh Le lead code 141 so uh on the left side we can see the problem and on the right side we're going to go through the problem find out ideas and ways to approach it so uh let's go through the problem first so the problem basically uh tells us to find a uh link list cycle and um they're going to give us two things basically the first one being the head uh of the link list and a pause is not something that we can work with so this is the only thing that we need to look into and find if uh there's a cycle within the link list so uh let's try to look into the example that they have given here so it's three then two then zero then minus 4 so these are each uh nodes or elements within that link list and uh when we going through traversing the link list uh we go through 1 2 uh 3 4 and ideally it should stop here right CU there shouldn't be anything else on the list but due to the design of the link list when we reach minus 4 it goes back to two again now that goes back to two again so we need to find out if the link list itself has a cycle meaning that four when we go to minus 4 comes back to two and then goes to 0 goes to-4 and two and then goes to 0 goes to-4 and two and then goes to 0 goes to-4 and this goes on like a loop all right so um how do we approach this problem and U the initial thought process is uh okay let's uh do a y Loop that can go through the link list and uh if we come across the same value again so we go to 3 2 - 4 and we value again so we go to 3 2 - 4 and we value again so we go to 3 2 - 4 and we find the same value again that means this thing has a uh duplicate value that means we are traversing the same values again which means it is a cycle however the problem with that is if we are storing values let's say we storing values in an array or within another list it has to uh continuously that array is continuously increasing orth less whatever you prefer it's continuously increasing right and every time let's say you're on minus 4 you have to check a is-4 within minus 4 you have to check a is-4 within minus 4 you have to check a is-4 within that array or not right now the same simp for smaller uh numbers so like for smaller counts or smaller lists however it's not possible or doesn't make sense when there are thousand values right yes it might work definitely it would but the goal of uh lead code is to uh have the best performance and with the uh least amount of time and this does not cut it right so what is the other solution how do we approach uh this problem with the same concept that we are checking the values if we encountered the same value or not so there are two ways to solve this the first one is the hair Auto problem or the algorithm uh which you can uh Google to find out it's pretty simple there are two pointers uh one is going one is a slow pointer and another one is a fast pointer so the slow one goes by one and the fast one goes by two so increases by two the other one is and the problem this is the solution that we going to talk about CU this is the one I found that this is uh the most understandable for most people so is but uh there's a cat here it changes the values within the link list now if you look into the problem uh nowhere here does it say you cannot uh change the values you cannot change the values there is a problem like this same problem but the uh requirement is you cannot change the values so uh we are going to talk about the hair toys algorithm for that problem which would be the next video hopefully and um but now we're going to talk about this one so we are going to change the values uh of the link list okay so how are we going to do it so let's look into an example uh let's look into the same thing uh that uh the problem States so 3 2 0 - 4 and uh this minus 4 then Loops 2 0 - 4 and uh this minus 4 then Loops 2 0 - 4 and uh this minus 4 then Loops back to two Okay okay so uh what we're going to do is we're going to Loop through uh the link list so initially we get three okay cool uh then we replace uh so initially we get three then we check is three a value that we have encountered initially so as we are trying to solve this problem using uh python so uh the variables can have any uh any type right so a can have let's say a is a variable a can have numbers or strings or anything like that this is how python works but for uh other languages let's say like Java you have to put uh let's say you're putting uh the value let's say we have the variable called Val and you're storing whatever link whatever value you got from the link list by traversing so let's say it's three for python you can uh let's say change value of three to um a okay but for Java uh you have to keep the same uh type so you have to keep it an integer now U one of the constraints says that the number of nodes in the list blah it has to be from- list blah it has to be from- list blah it has to be from- 10^ 5 to 10 power- 10^ 5 to positive 10^ 10^ 5 to 10 power- 10^ 5 to positive 10^ 10^ 5 to 10 power- 10^ 5 to positive 10^ 5 so you have to replace it with a value that is above or below that range all right so uh let's look at the python way uh because that's easier to understand okay so um we're we got the value three we are going to check uh we are going to basically uh check if this value so let's say the variable is called Val is equal to uh this is for P for present and this is a uh string okay if the value that we got is it equal to P if it is then that means this is the value that we got before and there that means there is a loop so for our case the uh link list value still look like this and uh three does not match with B so what we're going to do is we are going to replace three with the value e Okay so now the link list looks like this P20 -4 now the link list looks like this P20 -4 now the link list looks like this P20 -4 cool now uh next up we go to the next value so Val is 2 now we again check is 2 equal to P it's not so we change the value again so p 0 - 4 and you get the value again so p 0 - 4 and you get the value again so p 0 - 4 and you get the point right so we Traverse and make all the values P all right cool so this is now what the link list looks like and we still haven't uh traversed uh we still haven't triggered the loop yet so if you're look at the old values this was -4 right and at the old values this was -4 right and at the old values this was -4 right and uh the loop was -4 goes back to the uh the loop was -4 goes back to the uh the loop was -4 goes back to the first index which was initially two okay now uh what our Loop would do is it again comes here we change the value and goes to the next so the next is basically this one right and it says Hey valal 2 p is uh Val equal t yes that means we are in a loop because we are seeing the same value again so this is the solution that we are going to talk about or we are going to see the code after this but this is the uh most easiest solution and one that is most understandable without going to complex algorithms basically changing replacing the values with something that we can look into later so p and p then when four Loops back to whatever uh index uh the problem is on uh for example the example says uh the lead C problem says the position is one and for our case uh this is position zero 1 2 3 so after reaching industry it goes back to one and our problem or our solution basically goes back to P again checks if this is the same value that we checking against that means there is a loop now let's look into the solution okay so on the left side you can see the solution it's accepted and uh for runtime it beats 55.6% and for the memory 97 94% yes it's 55.6% and for the memory 97 94% yes it's 55.6% and for the memory 97 94% yes it's not the best but let's just go through the solution to understand how we approached uh the problem okay so uh this is the part that's already given to us and first we need to check hey if the list that they provided uh as a test case is the list empty or not cuz if it's empty we don't need to go through all of this code right we don't need to look into it nothing needs to be done uh no point in uh using up resources so if it's empty we are returning false that means there is no uh loop okay moving on um all right so the next thing the next test case we're going to talk about is uh let's say the link list has only one value and uh it doesn't point to uh itself or anything else all right so it doesn't point to itself or anything else in such cases that means there is no Loop all right so these two cases ens sure uh we don't need to go through the whole set of code okay um so uh remember as I mentioned in the initial problem so 32 0 - 4 we are replacing uh the values so - 4 we are replacing uh the values so - 4 we are replacing uh the values so here rather than saying P I'm saying the value is uh or the replacement value is checked so I'm replacing the head which is for our case three is the head we replacing three with checked all right and uh moving our pointer to the next one now uh we going into the loop so while head do next is not none so we need to understand hey is the next value present or not so is there a note after three or not so if it is go there check the value so see here we checking uh if the value of the pointer so in our case a pointer uh is basically the variable called Head we're basically Che checking if the pointer value is checked or not checked the string and uh if it is that means there is a loop so we return true else we replace the value so for the next one for our case uh it's not so we are replacing the value with uh the string checked and this is how we uh Traverse the whole link list if uh after traversing let's say there isn't any Loops so basically four uh doesn't point back to two so it doesn't point back to two it just ends here so uh after this so head. next uh my bad head do next is basically none then uh it's done that means there was no Loop and we returned false so now let's look into so I submitted the code again and uh let's look into some of the test cases that went through so 32041 that example uh that was uh present here in the Leal problem and the head position or The Loop basically starts from uh points back to index number one and in this case the output is true and the expectation was also true and for other cases like these which does not point back to anything which is zero uh sorry it points back to zero again so it point back points back to the first index and it in this case it also found out that there is a loop and for the first one the remember that we considered that there might be cases where uh there's just one value in the list and it doesn't point back to anything so the pause is minus one referring to it does not have a cycle and our system or our code identifies it properly uh that's about it for this solution um thank you and let me know if I can help you with anything else again
|
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
|
423 |
hello everyone welcome to my youtube channel the question for today is reconstruct original digits from english all right so given a non-empty english all right so given a non-empty english all right so given a non-empty string the string is not empty containing out of order english representation of digits from zero to nine out of order by autofocus means it will contain the letter but it won't be like it would be written like four directly or five directly it would be jumbled up all right we have to output the digits in ascending order so that's the question over there i know it sounds very difficult one when reading this event but it's so it's very easy uh the note points given uh are the hints here and as the input content rolling lowercase english letters so we can use hashing over here and input is guaranteed to be valid it's not invalid so we will surely get an answer so we should not look for like any other words we should look for the words that can come that's one more picking and this means abc or zero on like this are not converted because why this is not permitted because zero and one so it has to contain two o's for zero one but it contains only one so all such kind of words are not permitted uh they are sure that there is an answer and there is an on an empty string all right so that's the question over here so let's see the approach for this question and let's see how we can solve it so as let's see the approach for this question so i have discussed earlier what we do is given any string like this first we will create a hash map for this after the hashmap is created or of 26 array length array in which we going to map the characters and the references suppose z is okay one thing e is occurring one time and r is occurring two times and for e for z and for o two times r is one time and n is also something so we have has it like this we will create a hair or else everyone will be zero now after the hash is created what we going to do how we're going to approach this problem is because we know there are certain characters that occur only in unique uh you in unique digits and there are certain unique characters and if we keep their count so we are sure that these digits are this direct strings uh or their words are present in the string given to us let us see how and what are the unique characters all right so let's move to this just to this all right so here as you can see that for zero is said has as any other has the representation not z in it for six it's x because if any one cannot have x for two it's w because no one has w because t is present in both and q for four it's you and for it's g all right so what we're going to do is uh if we get there occurrences like suppose we know that the z is occurring four times so we can simply say that digit of zero or zero value is occurring four times already we will create a zero variant when we will store the recurrences as we have to return in a sending order so from zero to nine if we create one array and at the positions of we will just return the values present if it's 0 we won't do anything if it's 1 2 3 or we will just append at that time because you have to return the result in ascending order because here this value of 0 is 4 so what we're going to do is digit of 0 value digit of 0 would be nothing but what's the in our hash the value at z minus a that is at the last index that is at 26. so what value would be stored or directly we stored in this zero variable because so we have to just look for the special occurrences of the character all right now these are the things for the digits like 0 6 8 4 and 2 what about the rest of digits how we are going to calculate them all right let's see how right so now let's see for the other digits that are present we'll go quite from this we have got from this numbers and let's see what the other so here we have five all right so if we get a 4 and f is present so if two f's are present then we can see it is a 5 but if it's if it isn't a 4 is present so that it's going to add value at 4 would be 0 because it would be set initially only so the value at five would be the value at four minus the value at the value of f because if f is occurring two times or three times so if one of the f is of four then other two will be a five wave and if two of the f charge for four then one would be a five and if three others are for four only then one of will be of five so four five would be the value of f character f minus the value at array index at 4 because we have calculated only for 4 because it's a unique collector similarly so like this for 7 would be s minus 6 because s is occurring in two only that is seven as well as six in any other it's not upgrade so because for six we will be calculated uniquely because of x so for seven it won't be any difficulty that's why we are calculating these results based on the unique values that are calculated before because uh that would be make uh make our job easy and we don't have to you know reverse it again and again to find the spelling job to check it like that all right similarly for three it would be t minus 200 because t is occurring only in the two three and eight so the two and eight are unique so because the references will occur first we'll calculate them earlier so we can calculate for three all right the point here to note is we are calculating uh with the help of the unique occurrences the let us say because you can pick any letter but why we are picking these letters because these are uh already occurred in the characters which we have uh which was which count we have determined previously and in the unique conversion all right so yeah similarly for one it would be o from two four zero because for 0 it's z and for 2 it's w and for 4 it's i think it's u so yeah so because these all are unique similarly like that and now similarly for 9 we have transferred from 5 because 5 is now calculated in here 6 as x and 8 has g and it already triggered so the calculate how it's how we will calculate it all right i hope it's clear why how we are looking the common thing then why we are not looking at every word in the common list because we are thinking smartly because if we get the unique values first and then we compute this then our computation results will be easy so let's see the code for this question and if you have any doubt it would be clear just clear then let's see the so here is the code for the question here i have just make a hash of care array and just computed the values it was just string once only so of n for this and let's see now what we have here i have declared my digits array with 10 from 0 to 9 all right in which i will be storing the counts of the digits that are occurring based upon the hash map uh made before all right so first of all the unique characters for zero it's red so it is occurring and six is x u is for four and two is for the w is for two and for g is for eight all right so i will calculate this then i will calculate my this numbers because these numbers are based on the values that are completely before all right so that's how my result will be a result will be calculated and yeah now when these values are filled my asparagus 0 to 9 will uh occur the occurrences of all the letters we have to take on only the possibilities because some values can be negative also we don't go into that let's see how all those is because suppose if 3 is not occurring and if a 8 is occurring twice so zero minus two is negative two that would be stored in an array so we don't have to take negative value we will see the positive value let's see how okay now for this it's often and it's o of one constant space its first space and now see we have taken a string answer final answer where we are going to append our answer so all right let's see and for equal to 1 to 10 this is for traversing this array because it says zero to nine values and if the value is not equal to zero we have to see it's not equal to zero if it's not equal to zero and if we you know decrement it doesn't become zero because if two is if zero is occurring here four times then for every four uh zero we have to append it in an answer because it's occurring four times so that's why i have taken a while loop over here and after that i have a pending my result in the this answer string builder and after that i have converting it to two string because i have to return string data so let's uh try to submit this code and see what so as you can see it's accepted so if you have any doubt regarding this question you can ask me in the comment section please like this video share it among your friends and subscribe to my youtube channel thank you for watching bye
|
Reconstruct Original Digits from English
|
reconstruct-original-digits-from-english
|
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_.
**Example 1:**
**Input:** s = "owoztneoer"
**Output:** "012"
**Example 2:**
**Input:** s = "fviefuro"
**Output:** "45"
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`.
* `s` is **guaranteed** to be valid.
| null |
Hash Table,Math,String
|
Medium
| null |
653 |
hey everyone welcome back and today we will be doing another lead code problem six five three two some for input is a binary search tree this is also October 9 lead code Challenge and we are doing it this is an easy one given the root of a binary tree a search tree and our Target number K return true if there exists Two element in the binary search tree such that their sum is equal to the given Target so this is a very similar problem uh do some to someone to the to someone we have already done and that's it we just make a list uh we just make a dictionary or in that case we made a dictionary because we want to return the indexes I think and in this case we will just make a set and if we have the targeted value subtracted by the node value uh yes in our set we are going to return true otherwise if we are going to return false and that's it so our set will be equal to our set and we will just run a DFS depth first search taking the node okay taking the node so if not node we are going to return true uh not true false because we cannot find a Target in the null node and now if let me just calculate our if what we can call it like T okay if T in K minus no dot well if T is present in our set then we are going to return true and if in the else case we are going to just add it so the node value not the T because we want the node value so in whenever we find uh that t that is basically present in our set which is just basically the node value so that's it then we will just return it and our set hours set dot up band it with no dot well okay this is done and after doing that we can just return by calling the DFS on the Node Dot left or DFS at node no dot right and then just return and say called DFS with the root okay this should work let me see if this works or not yes there is not append there is I think an add one to the set so adding yes so mistake and that's it
|
Two Sum IV - Input is a BST
|
two-sum-iv-input-is-a-bst
|
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 9
**Output:** true
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 28
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* `root` is guaranteed to be a **valid** binary search tree.
* `-105 <= k <= 105`
| null |
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
1,167,170,1150
|
565 |
hello everyone and welcome back to another video so today we're going to be solving the lead code question area nesting all right so this question is actually pretty interesting because to actually solve it there is a pattern that you have to observe so what i want to do with this question is to kind of show you how you can actually come and see the pro pattern and actually make that observation and eventually solve the question using that so real quickly this question we're going to be given an integer area nums of length n where nums is a permutation of numbers in the range 0 comma n minus 1. so let's say over here we're given these nums um and essentially what it's telling us is that uh the length of this is seven so the range of numbers is going to be from zero to seven minus one which is well six and obviously the zero and 6 are inclusive in the range so in this we're going to get a random permutation with these values and what that basically means is let's say we had the values 0 and 1. so one of the permutations would be 0 comma one and the other one would be one comma zero so essentially if something had a length of eight you would get one of the permutations with the number zero all the way up to seven because eight minus one so that's going to be our input so now the goal with this is that we want to make a set called s of k where k is going to be an index volume and the set the way it works is that the first element is going to be nums k the next element is going to be nums at the index num's k then we're going to have nums at the index nums k okay so in simpler words uh what that basically says is that at sk so let's say s0 you're first going to have a number at nums k that's going to be num 0 then the next value is going to be nums and whatever this value is so at this index then this over here is going to be nums at this index over here okay so that's basically what these two are saying over here and we stop adding right before a duplicate element occurs in sk so essentially a set cannot have to uh repetition of elements so every time there's a duplicate we stop okay so the goal is to return the longest path of set sk so before that let me actually go over this part and show you how we can build that set so just to make it easier on us what we're going to do is we're going to write out so nums at the zeroth index has a value of five okay so nums at the first index has a value of four so let me just fill this out uh completely so at the second index zero at the third index we have a value of three at the fourth index we have a value of one at the fifth index we have a value of six and finally at the sixth index we have a value of two cool so we have this over here so whatever is at a certain index and the value at that corresponding index cool so now what we want to do is how do we create a set as k okay so let's say we want to make the set s with k having a value of zero so f zero and the way we're actually going to do this is the first thing we do is we go to nums zero because k is zero in this case and that is a value of five so the first value is going to be five cool so now the next thing that we're going to do here is we're going to go to the index five so at the fifth index we have the number six so that's what we write now we go to the sixth index for this value over here so the sixth index is the number two cool now we go to the second index so the second index has a value of zero and the zero index has a value of five but now notice five already exists so we cannot add five again so that's it that's going to be our set when k is equal to zero five comma six comma two comma zero and this has a length of four cool so now one thing that we could do is we could kind of store this somewhere and look at this for all the k possible values and form all these sets and just find out which one has the largest length so obviously that is a brute force approach it could it would work but it is a brute force approach we want to look at a better solution so this is where the pattern i was talking about comes into play so basically how i found it in the beginning is what i did is i took the k value so what are the possible k values in this case the possible k values are zero all the way up to six and for each of them i wrote the corresponding set so s k and when you do that you actually find a very interesting pattern and that's what i want to show you and explain to you how that comes along so let me just write that down all right so now at k is equal to zero we've already found out the set and the set was five comma six comma two comma zero cool so i'm gonna fill this out for everything but i'll just do it a little bit quickly so at one we are going to have four and the reason with four so we go to the index one which has a value of four then we go to the index four which has a value of one now we go to the index one and that has a value of four obviously and four already exists so we can't write that again so cool we have this as it is so now we go to two and at two it's going to be zero comma five comma six comma two so i already have them written down so i'm just gonna fill it up quickly and at three it's just going to be the value three and let's just look at that so first we go to index three that has a value of three then again we go to index three and obviously the value is still three and we cannot add duplicates so cool so now at four our set is going to be one comma four and at five it's going to be six comma two comma zero comma five and finally at six we're going to have two comma zero comma five comma six okay so now this is where our observation comes into play let's look at kind of all the sets that we have so all of these are a length of four these are a length of two and this has a single length of one now when you let's just take a look at everything with a length of four specifically now the numbers here are five six two and zero cool and over here we see the same numbers five six two zero they're in a different order but it's still five six two zero and one thing to notice is it's still in that same kind of word okay so what i meant is uh the first number here is zero but still it's kind of shifted over so this is five six two zero and you could read this as five six two and then zero right and over here we have the same thing five and then six two zero and i'll highlight the five again five and then six two zero so the numbers here are the same so the question here is why exactly is this all of these have the exact same numbers but their starting points are different so five zero six and two they start at different values but they have the same numbers so why exactly is that now the explanation for this is pretty simple and that's because we kind of have a cycle and i think this is best explained when i kind of draw it out so five points to six points to two and two points to zero and zero points to five and let's just actually confirm this so at the zeroth index we have a value of five correct at the fifth index we have a value of six at the sixth index we have a value of two at the second index we have a value of zero and again zero points to five point two six and it's just an ongoing never ending cycle so realistically what's happening over here when we're looking at these k different possibilities we are going at the same cycle except we're just starting at different places so my the basic thing that we need to get out of this is that we could have several of these cycles and once we visited one of the starting points so let's say when we visit the one which starts with five there's no point of visiting the other ones because all we care about is what is the length going to be and in this case we know the length is four whether you start from four or six or zero no matter where you start from the length is always going to be four so this is the idea that we want to implement and now let me show you how we're going to implement the fact that once we've entered one of these circles we do not want to ever enter it again and the way we're going to do this is let me just take k is equal to 0 as an example so in this case first we go to 5 then we go to six and then two and then zero now what we're going to do is at each time once we visited it so in this case uh we would actually store the length right which is four we calculate the length is four and we stop but now at this point what we're going to do is each time we make these numbers negative one so once we visited them we make it negative one and the reason i'm saying negative one is we just want some sort of way to kind of mark that we have visited this number and the reason i said negative one specifically is because the range of numbers is just going to be from zero up to the length of nums so negative one is not going to be in that range ever so that's just kind of a marker number i'm using so in this case when it's a negative one that means i have already visited so now let's see how this could actually be important so now let's say i go to k is equal to two so the first thing i do is i go to the second index which has a value of zero now when i go to zero what's basically happening is at this second index i have a value negative 1 and what that's telling me is that look i've already been to the circle with the numbers 5 6 2 and 0. now when i visit the circle i'm going to be getting the same exact circle values which are 0 5 6 and 2. so the length is going to be the same so at this point there is no need of visiting it and then i'm not going to do anything so since so that automatically tells me in the beginning i've already visited this circle there's no point of visiting it again so this is going to just basically have a length of 0 because its previous length which was 4 has been accounted for once and that's enough so let's see what that looks like when k is equal to one so k is equal to one we so we go to the first index which has a value of four and then we go to one over here now both of these don't have negative one so this is the new loop that is formed and these two are also going to have now going to have a value of negative one so in this case now we have a length of two but now again what happens when we go to k is equal to four the second we go to the fourth index which has a value of one over here at the fourth index it has a value of negative one not one right so that means we've already visited that cycle right so this the cycle has the numbers four and one and in this case the starting point is one instead of four so we don't so this also we don't need to check for that cycle so it also has a value of zero okay so in simple words once we visited the cycle visit a certain cycle we take that length and we never visit that cycle again so keeping that in mind this three over here is actually not visited yet so now we visit it and it has a value of negative one and it has a length of one so now when we go to k is equal to five well this cycle with six has a value of negative one it's already been visited so we're going to give it zero and over here this cycle has also been visited so it gets zero so realistically the value that we end up uh returning is going to be the maximum value between all of these lines which in this case is going to be four so four is the value we end up returning so hopefully you understood this and let me just sum it up real quickly we know that there is some sort of cycle and once we've entered one of these cycles there is no point of entering another cycle because the only difference is going to be the start point and the lengths are going to be the same so in that case we mark it we're using a marker which in this case is negative one and when that is there we're not going to detect that cycle anymore so let's see how this looks like in code and i think it should give you a better understanding all right so we're going to start off by initializing our uh result and this result is what is going to have the maximum length right so in this case that was before and this is what it's going to basically start so let's initialize it with a value of zero and now we need to get the k values and this is going to be for k in range length of nums so this gives us all the k values from 0 to n minus 1. okay perfect so now we need to find the current length of the set that we're currently building so set k we want to find its current length and we're going to initialize it with zero now the first thing we do is the number we go to is going to be nums at the index k now the first thing we're going to look for is have we already visited this cycle and the way we do that is if it's equal to negative one so if it is equal to negative one we do not do anything so the condition here is while nums k is not equal to negative one then in that case we're going to look at the other possible values and check the new cycle out okay now the first thing we're going to do is we're going to increment our current length since it's going to increment by one over here so we added by one and now what we're going to do is we got to change so currently uh k has a certain value but we got to change that value to k to the new index right to the index numbers k and the way we do that is we just give k is equal to num's k perfect now another thing we got to do is we're going to change the value of nums k to negative one but one problem by doing this the numbers case equal to negative one we change the value of k over here so what we're going to do is a simple fix is we're going to store the value of k in a temporary variable before changing its value to nums k and change that value to negative 1. perfect so that's what we're doing and that's it for our while loop so by the end of this all of the numbers should have become negative one and meaning we've explored all of the possible cycles and while doing so we're finding the current length so the final thing we're gonna do outside of this while loop is we gotta uh change we gotta keep updating the value of result so we only have the largest value so the way we do that is pretty simple so result is gonna be the maximum between the current result that we're currently having and the current length that we found for the set at the value k whatever the value k is and now outside of this well all we have to do is we got to return the value of our result so submit this and as you can see our submission was accepted so real quickly the time complexity here is going to be big o of n because over here we're going through uh so that all the possible k values are basically from zero up to n minus one so big o of n is the time complexity and the space complexity here is actually going to be constant space because whatever we're changing so when we're changing it to negative one we're changing the nums list itself right we're not changing anything else so it's going to be constant space in this case so that should be it and hopefully this video did help you and do let me know if you have any questions
|
Array Nesting
|
array-nesting
|
You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`.
You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule:
* The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`.
* The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on.
* We stop adding right before a duplicate element occurs in `s[k]`.
Return _the longest length of a set_ `s[k]`.
**Example 1:**
**Input:** nums = \[5,4,0,3,1,6,2\]
**Output:** 4
**Explanation:**
nums\[0\] = 5, nums\[1\] = 4, nums\[2\] = 0, nums\[3\] = 3, nums\[4\] = 1, nums\[5\] = 6, nums\[6\] = 2.
One of the longest sets s\[k\]:
s\[0\] = {nums\[0\], nums\[5\], nums\[6\], nums\[2\]} = {5, 6, 2, 0}
**Example 2:**
**Input:** nums = \[0,1,2\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] < nums.length`
* All the values of `nums` are **unique**.
| null |
Array,Depth-First Search
|
Medium
|
339,341,364
|
315 |
Hello Everyone, today we are going to solve the question on Questions Page Account of Smaller Number After Sale List on 23rd July Challenge 220 In question we have to tell the name of Agri Forest and we have to tell that it is the husband of Egg Particular Index which is number six on the right side of it. What is the button of how many smallest number williams model number inside right side so multiple logic can sleep in so that entry binary tree and sort thumb but like subscribe keep in mind that subscribe if you subscribe your limited in the answer If we increase the number of account which is less than the balance on the right side, then we will know that this particular number is smaller than that on the right side. So, first of all we ignore Balbir and deleted the answer and only that answer. An English phone number is 90, we will tow our answers in it, so now what will we use for this, if we use a studio, then the problem is that in the first column we will add those elements and in the second column we will install it so that when the limit is reached in the last Violet becomes smooth, we have your index, so for this we will make wear today that its length will remain above the number plate, the solution will be trucker, hotspot will be long, the value of salt will be there, pimples which limit its value, its index will be above in the column. Are you thinking that Swami Tarlu will run now around Sonu Nigam That Land then you will feel the tempo for equal to the meeting and the first, there will be an element in it and tech medicine will be its index. Okay, now let us call a Khan Utpan. Just fill one WhatsApp text and show the number of votes returned by returning clearly. You write clearly that today you will return as if you are turning off today is such that Abhishek the condition will remain that if America is long minded then oh mother please return. If there are not only two, then you will dip it in two, then in the parts you will grate the target of left and right and left, answer right click and then make the last moment chilly, loot with the person who opens the WhatsApp, now we copy it in this. Now we will pass a copy of the address in it, so turn on that from hero to half, there is no last indic input in it, do this and see that there is research that elasticsearch will get trapped in it. Edit left. Okay, now we are on a region. Let's take the lift, from left to right option will come like share and transfer, then we will march from that, we will have to write another function for Hanuman, the main work in this function will be that Aamir will have to check if the one in the loop is greater than the one on the right. Then our answer to the left one is our answer, we will have to class our answers on electronics by taking it on the left, I will turn my account, this is also a how to return in a movie and device that today are left and right Jai If it is hind, now we will make the index by taking 3 inches and click on the right one and one for us which will be our answer, for the answer of pudiyas, I am in touch with that we will do kirtan to me tomorrow, school, his name will die, let's do new int ki. Its length Loot-Loot Class Right clicking the Loot-Loot Class Right clicking the Loot-Loot Class Right clicking the elements on both the sides will be added to it and also who will do this Okay okay now we have to run till Anup till today our index of overlap say laptop Lenovo laptop and quality If it becomes equal then Greater Noida and our right for tailing sir is less till now, then what condition did we write that if the right one is less than the left one then it is our duty to keep the record of wickets at the place madam. Destroying the end which will be left, there is an index in the answer, we will make it plus our work, how bright is the career, he has so many limits, he is less than that, mix us as much as the condition for 130, if the element of the right key which is in the album. If it is less on our left than the city limit, we will make the account plus in the answer and its index is from adulteration and on the contrary, we blasted a bomb due to which the controller shot me and how many pluses we make, how much account will be added to the right. Dot loop - right. Dot loop - right. Dot loop - are what is needed from the current index at this time and all and nutritious we have got the small element from him in the festival of the right so the party elements are the compound model that Edison is the doctor on the records so we will add the year oh madam And if you die or will you add it to the dick, on the left is the flash light and in ours, if there is no animal send butt, it is a grater with torch light, then we are going to be very smart, we have to add it on the right and there is someone in the answer. Plus will not loot and tell me that after completing the training police index has gone out topless in modern way then if in that I come less than taking our laptop and hence keep our 19 this has become ours then we If we add all the closed loops in the limit then we will add the check loot on the face to the face, stop file that I Plus Jai Hind Express movie is there, but if it is not there, then this is the condition, yes, ours is less than rippling. Our mark, which came less from Amazon, is done with our laptop, then we will die, we will add elements from all my rights, A+B+Plus, we will die and return by Shri Ram Mishra, A, now our front here has ended. There are two vitamins in it, the format of answer required is not required in Intel, we need a list, this topic is definitely required, so for this, we will make a software for the final answer, we will add all the problems in the list, the answer is yes and we will return it but tears. Yes, yes friend, the parts have passed, do you keep submitting whether the video is accepted or not till date.
|
Count of Smaller Numbers After Self
|
count-of-smaller-numbers-after-self
|
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
327,406,493,1482,2280
|
71 |
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem simplify path and it is the medium problem of the daily lead code challenge and its index is seven one okay so before moving on to discuss this problem let me talk about how we can what type of concept that is being required to solve this problem you can see if you look out the section called related topics you will find the stack that is we are going to use an stack that is so that is going to solve this problem efficiently okay so let's look out for the problem given a string path which is an absolute path starting with the forward slash to a file or directory in a unix style file system okay so we would be having a path in a unix style file system that is going to be start with the forward slash and that is called an absolute path and we need to convert it to a simplified canonical path okay so there are a few of the things that you need to know that is what is an absolute path and what are the contents that is being filled in the absolute path as well as the canonical path so okay so in a unique style file system a period dot refers to the current directory and a double period refers to the directory upper level that is you can see your previous level like going to a previous directory also if there exist any multiple consecutive slashes are treated as single slash now for this problem any other format of periods such as triple dot are going to be treated as file slash directory names now let's understand the canonical path okay so a path is said to be a canonical path if it starts with a forward slash note that it is only a single forward slash and any two directories are separated by single slash single forward slash and the path that is the canonical path is not going to end with the trailing forward slash and the path is not going to contain any dot or double dot that is single period or double period and we need to return the simplified canonical path okay so let's first understand what is this absolute path and canonical path in detail okay so let me write down absolute path so this path must start with a forward slash as well as this past must end with a forward you can say uh forward slash if i'm not wrong it must end with uh no it is not necessary if you look out my console if i will try to remove this forward slash and then run this code i hope this test case is valid so it means that you can say it means that this forward slash ending of in case of absolute path is not necessary that is the path may or may not end with forward slash okay and it may contain a double forward slash and if order it may contain a dot it may contain a double dot it is actually a period or double period for this case it means that going to a previous directory and for the single dot single period it refers to a current directory okay so this is the case for the absolute path so let's talk about the canonical path okay canonical path so in case of canonical path you can see it consists of only a forward slash like it also starts with a forward slash starts with and every uh you can see every file name or directory name is going to be separated with a forward slash as well as there is no period or no double period double dots okay and path is not going to end with not end with a forward slash okay so you need to take care for all that so let's take an example and understand how we can convert this entire absolute path into a canonical path so i'm going to take this one example so that is a good one home slash sunny which is my name and then we have a double dot and then we have a double forward slash and then we have a sumit okay now it says that we are going to have home then go to sunny uh yeah and then go to a one step back that is over here so this sunny will be deleted then go to sumit right or this is actually the absolute path but we need to return this canonical path okay so how we are going to do that efficiently is nothing but we are going to extract down the file names like uh extract out the string that is present between two consecutive forward slash that is this one as well as this one and this one so you can see my strings are home then it comes sunny and then it comes double dot now whenever we encounter a double dot we need to extract down this string and throw it out so you can see when we extract it out my set of strings would become only home and this is utilized and this is also utilized now next comes the sumit so home and sumit is our final string okay so if you uh convert this set of strings your canonical path you must start with a forward slash then write down home then write down a forward slash then write down submit so this is the thing that you need to do so let me explain all these things in detail in the coding part also because nothing is going to explain over there only thing is about the implementation how you're going to implement all that efficiently okay so let's look at my implementation okay so it would be better if you look out that clear this one because of this ui yeah okay so what i've done is like i have taken a string that is going to store the string that is present between two forward slash and this vector of strings that is going to store the canonical path up to the current point like whenever you will face a double dot you need to pop out the last element of this set of strings that is being stored in this vector st right now you can see i push back this forward slash at the last position of this part because to avoid the writing a lot of cases because you know suppose you have this string let's say slash home slash sunny okay so you have to uh you know you have to forward slash and you can extract this string easily and last you can see there doesn't exist any forward slash over these two positions so you need to write down an extra case for that so for avoiding that you know a lot of code work i will append this up forward slash site over here and this will be extracted easily right so that is the use of this statement now i will iterate over the paths and whenever we will encounter a you know a forward slash you have already a string stored in this s like a string s that is between you know two forward slash between these two any two forward slashes and that substring is being extracted and being stored in the string s right now if as is empty you know you are going to you are not going to do anything now if s is uh you know double dot and this ht is non empty it means that there is some file name or directory name in this string ht like set of string st and s is a double dot you need to pop out that is you need to go to a previous directory right so you will stack dot pop so ht.pop basically so ht.pop basically so ht.pop basically now again if these two conditions fail you need to check it out if it is not a dot and not a double dot right then you will push back that string s into a set of strings that you are going to work upon okay so you will just push back that string as into this vector strings that can be a you know any file name like home sunny summit right and if you are done with that you need to clear uh this string as for uh extracting the next uh substring between next to substring between two you know between two forward slash and if you are still working upon any letter or any digits then you are going to push back this string push back this character into this temporary string s that is actually storing any substring between two forward slash okay now uh when you are done with that in this set of strings you have the you know all the file names or directory names uh going to the destination position starting from the source position like in a sequence manner now you need to convert this into a canonical path so you will pick out this one of the file name or directory name and first put out a forward slash then you will append that file name or directory name now if all those goes well and you are still a answer as empty you need to only insert this only forward slash and finally written on the answer so let me just show out uh how this all going to happen through this example okay now s is initially empty okay s is empty now when you encounter this you know this forward slash you can see this condition will be invoked if s is empty you can see yes string is empty so this will be like entire statement will be skipped now when you come to this home h that is the character edge you can see this condition will be like the program position program will go to this else part and it will push back this h okay now again o m e each time going to this else part because you know c is uh not a forward slash then it goes to that now whenever you will encounter this forward slash you can see you have this s being stored over here that is the substring between two forward slash then you will compare this one you know s is a double dot and this is not empty if s is not a single dot not a period not a double dot then you push back this one you can see this condition will be invoked in this case okay so you will be storing this home in this vector of strings okay again this sunny the same case but when you encounter this double dot you can see this condition will be invoked and this sunny will be popped out so you know vector of strings will contain only home then again you will get sumit you will write down sumit over here and when you convert this one to canonical path you will write down slash home then you will read on slash submit so this will be our answer okay so you can see uh all the test cases will be passed and yeah if you guys have still any doubts you can reach out to us through the comment section of the video and thank you for watching this video
|
Simplify Path
|
simplify-path
|
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path.
| null |
String,Stack
|
Medium
| null |
134 |
Hello hi everyone welcome to my channel it's all the gas station problem this is the work of my favorite problem s well s decision problems very favorite in interviews and this problem gas this man found electricity company interview solution to this problem and tricks and saw her end Gas Stations on a Circular Route Web Edition I guess you have car with unlimited time and cost of cost to travel from station to the journey with any one of the biggest state in the starting gas station you can travel around 150 140 Is Nuskhe Winters Ki Saadi Jodi Constraints So This Is Example1 Se 011 The Video then subscribe to the Page if you liked The Video then subscribe to the two to three four years ago from this is the first president of kar two ago hair after spending costumes Will be for minus one left with three fluid from where will get 15 to 20 2012 - 2nd 15 to 20 2012 - 2nd 15 to 20 2012 - 2nd test first step new year 2069 one plus one two three - you can go to 9 we will do two three - you can go to 9 we will do two three - you can go to 9 we will do mode plus 2 and consumes 409 plus 350 subscribe 10 qualities in The Place Where Will Start and Stop These Places in Solitude Overhead 321 Affair Institute of Amazon 5567 subscribe and subscribe the Channel subscribe Video Subscribe Start from All The Top Entry Will Come from Subscribe Always Tried to Start from More than 200 Total Gas Leftovers Entertain Is Always Looks Great Dane and 10 Reasons Why Some Water Is Used in The Answer Is Not Means That Were Getting This Gas - Cost Subscribe - The Video then subscribe to Subscribe - The Video then subscribe to Subscribe - The Video then subscribe to the Page if you liked The Video then subscribe to the Page if Starting from this Top 100 Equity Derivatives Which Will Be Counted As You Like And Best Of Five video.in That Indian One Season Is Visible To Cover All Staff They Have Total Records Which Can More Direct Time Complexity Of Dissolution Skin Ko Subscribe Like This And Every Time Subscribe Now To My Video Thanks For The Subscribe And Calculating Total One Of The Thing Like This Candle Stand And Fight A Difference And Every Place Is From The Net That At Every Places From Guest Cost Effective Differences Sexual Gas - Cost Effective Differences Sexual Gas - Cost Effective Differences Sexual Gas - Cost Subscribe And Will Only Difference Being Considered It Will Tech subscribe and subscribe this Video give me b hai solution total fuel filter 1609 The point will find a solution from which traversing this dry failure will start from zero stop flight se 21 2011 President Sudhir We will start from here no evil will create Subscribe a page like and you will start from check subscribe school a for all date twisted modi digit subscribe plus one will update you who here from bi plus one key and also retrieved a tank from the phone will also keep track of this all The changes like and total very busy schedule and give they have not been tried this way you will get in hindi and will check tank total is donkey and 10 - subscribe total subscribe now to 10 - subscribe total subscribe now to 10 - subscribe total subscribe now to receive new is so for a for that in tie 20 electronic a Guest or login flat se very we plus 2 and will take also let's check calculate the current consume different from current stock thing gas fiber - co stop is no evidence thing gas fiber - co stop is no evidence thing gas fiber - co stop is no evidence request oo to consume that and e will check ifik c0 s0 will update our and research from Chief plus one and also update design amla here jain method 0n total absorbs pe aap zoom in indian villages of a total 10 inch means bir valid in the indian flag code that i have used in english test cases for this platform in this dashrath stadium in this code i own Apps Update So Severe Running One Farooq And Where Taking Care With Help Of Tubelight Important Time Can Total Software Come Up With Solution Dissolution Of Time And Space Complexity subscribe The Channel thanks for watching
|
Gas Station
|
gas-station
|
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104`
| null |
Array,Greedy
|
Medium
|
1346
|
143 |
Hello hello everyone welcome back to my channel suggestion or going to discuss the problem hands free mode as it is very interesting problem relative problems yoga ban on head office in least 23 can be represented on the other hand English team in Rio the list to be N follow inform oo hain surya tu report delete means of the force node search notesheet come in section saliva for absolutely smooth 15year and liquid love you may not modify values in list love you may not modify values in list love you may not modify values in list notes only no details visit to wick not like she will change a person not need To change the not need to bring notes and preparing them so let's see problem is sweet angel in sharing this event was so how to reach this to come forward bases do tubelight se know welcome mere set alarm show karo a posh month will give positive And alarm welcome jhal and enters second ki in din se khela suit and third place means for it's not from the electronic and from the front and back lekar subah final output hai to newly created see how we can make this from being destroyed so itni see what they Are Doing Basically That We Ca n't Do From the Beginning to 99K Micro Board Avot Ayush Singh Initially Voiced by What We Can Do Something Like See Do Not Know Why We Need to Give It Up 90 After Five Years of VHP Will Get Into And Not To Win But What Happens If It 12345 Something Like This 110 Vinod Rathore Picture Nod From Air Attack In The Second Vihar To Take Medicine Print 110 Ajna Me To Take Leave From Distic Head The Ab Half Minute To Take Notes In This Gazette That in the water before election department to table of fear this list on this side of things will be doing so in order to make to say platelets e-billing list from the beginning and e-billing list from the beginning and e-billing list from the beginning and receiving list the not regret not no question is that you will Not want all I am so divided in English fonts middle all this month will be coming late affair mirch again on * * * * * * 53.25 Vid oo will find the middle 9th 53.25 Vid oo will find the middle 9th 53.25 Vid oo will find the middle 9th english middle east that sidled english into two parts for play list A Dog in English The Second Interest is Sudhir West But You Must Be Thinking Technical Tips Also Divide Darling Latest Hair Take Someone Middle English Language Start From Thumb and Lag Readable Are Getting 500 To Connect With Five Simple And They Wo n't Be Published I Want More Things That One Page For One Month From This Least 10 Minutes In Fluid From Attack To Meet Me To Let Sutli See What Will Be Going To Do Phone Per Temple Of 123 12345 10 English Man 10:00 What We Will 12345 10 English Man 10:00 What We Will 12345 10 English Man 10:00 What We Will Do It Is a that various divide from here from you will divide from middle to will find the mid point of liquid no doubt in the middle of language that and divide some will make to language 123 for delegate for five with another in this that Indian woman reverse Same request premises bluetooth setting list 1005 vikram thakur ki internet live in march ki tourist places and ad som one to three ki and fair will watch and will get d for adults to select how we can point middle east to difficult middle order in english So for finding in middle elementum meter not only will be using a fast and low point approach a teenager will take how to find ur very simple e will have 200m which will points don't drink which will give one too slow will point to head twelve verses end Fast 12.2 Head to Head in the 12.2 Head to Head in the 12.2 Head to Head in the sacrifice of every time you will give one tip is it will not want for word and passed with tips will earn muttu submit ki ifico * nice ifico * nice ifico * nice ki ifikse request oo not equal to 9 and hai and pass vikram request oo R pass neck vikram shrank to 910 aloo phal par a tweet stop and they all no point in the middle end and share slow win the power to welcome easier and faster in ubuntu server want to speech tamil nadu will work in the end of twin bluetooth somavanshi And Difficult Not Irrational That Compliant To Beneficial Planets Top Blue Jeans Top In Subhash And It's Those Way Loins That Is Your Middle Note Harmonious You Need Not My Dear Friend Newly Appointed Divider Of Booty Divide Into Liquid Fennel Which Method To Make Into Two Parts Shop First Electric Variable Forest Which Will Toe All The Head Of The Least One Platform List Then Follow Heads These Are Available For Possible To Head That And What They Also Second Liquid Lipstick Second Visible And Will Affect In English Essay In English Health Is These 49 Various Poisons Oye Next Two States Will Be Id Am Id 32428 Do We Need To Video In Next That Like High Court Torch Light Photo Good Night Them At Web In Nal Hai According Tour English Year Created After Falling Leaves 123 Labs Can Share This Chant And In Its Profits And Monitor First 14.21 And Second To 14.21 And Second To 14.21 And Second To Ek Amla Mein To TV Where Is The Fastest Fast Food And Drink For Vivo v55 Went Into Her [ __ ] Was The Meaning Of Me Budding Hotspots Morning Le See How Will It Very Simple A Sodid Latur Least One To Three Layer And For 54354 So What Will Do The Cost Of All For Watching Servi This Is The First And Second To Positive Way Final 152 The Fourth Free Life In A Boat Lift One Will Come In The World Cup A Right To Post For Me So I Want To Connect One With Python With Someone Will Connect With 5152 Connection Will Last For All You Need To Do Is To 10 And Will Form Next That In Temple Timings In Temple Run Part-22 Now They Can Lead To Connect With My Next 9 News Room That Aapke New Year Mintu Is Method 295 That Vindht U Need To Connect 512 To Be Difficult To Find Bittu Disconnection Will Just Want To Meet U To December Posts Will Take Another Jain Temple To That And Will To Appoint Technique Second Next 10 We Can Easily Connect 525 What is 5 second text five still second that 5.5 second next suggestion want to love you two was that 5.5 second next suggestion want to love you two was that 5.5 second next suggestion want to love you two was stored in temple run phone per temple means second next 9 point to temple thanks disconnected office collection stop so it is 152 disconnected morning your during this award-winning to award-winning to award-winning to us a nominee to you forget to post election yeast why we basmati for rest for this year and hear cost less hair and second rich and a song that know you are the to duty not like this wo palat 1.4 aka but for What We Will Do this wo palat 1.4 aka but for What We Will Do this wo palat 1.4 aka but for What We Will Do In Forest This Post Will Know What Earthquake Temple That Temple Was 2nd Second Vikram Temple The Second Will Come Toe Tempt Treatment Facility Chapter Existing Stool Test That Plant The Above Article Directly Very Similar Toe Stop Watch And Accessible Angle of Sudarshan Choudhary for watching if you know how to reverse in English Summary of trouble finding the middle of the snow point where in the head and fast will find some will close in a slow has net voice of cosmetic product in at Least To Visit Us At Least To Refill Passing Second Class Having Reviews And Will Get New Facts After Digested And Select The Winners For That Is Broke In This Connection Break Liquid Who Is The First Head Coach Record Broke The Tutorial Point Will Not Been Changing Her Because It's Not Changed Because It's Quite Wick Not Returned To Meet It's Not Seen Torch Light 910 Vihawal Dance Step Mother For Middle East And West Indies Tips Towards Middle Eastern Acquisition Which They Have Listed And Will Not Bay To Total 12345 Half 1234 subscribe the world will a small effort facilities available 1 second ho gayi ka vriksha toy ho kuntub do approach for every problem and co dividend please comment me and like it please like share and subscribe my channel and hidden
|
Reorder List
|
reorder-list
|
You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000`
| null |
Linked List,Two Pointers,Stack,Recursion
|
Medium
|
2216
|
363 |
Hello everyone welcome back to my channel Kunjbihari is going to discuss my own problem the problem in 4 inches is maximum material triangle no longer knowledge day off problem no problem is a combination of volume maximum and the second problem is maximum knowledge by combining these two this is The problem is a combination of both, if this is a problem, then let's see that in the problem of the incident, we have done a across and matriculated, okay, we have given tomato puree and an interior from friends to tell us, click on the maximum subscribe button like If you see this one will keep just one this one can fold a single okay that's just more this one plus minus two Sandhu's article in the morning on how more or less is good, then let's see how we will do it. When this question of maximum prosperity comes, then we have to find all the wrinkle marks in it that what will be the maximum, it is okay, then in that we What do we do, we make two points, one on the left, one like, okay, we keep the one on the left as English, we will go to the length on the first column, okay, but we kept this one which is tight and in the beginning right here. It is glue family, okay, and what will we do not take ads, in which we leave our elements, okay, so here we have two days, so we will see our size will be made, you will not think that the size of the pictures is reasonable, how to see here, first of all, we are here But the right here is our whatever is in this and this is that I am fine and after that the right is what will be ours which will be our channel this is ours where your cigarette will go i.e. which return we are cigarette will go i.e. which return we are cigarette will go i.e. which return we are taking first. Only this one is here, now we will write in blood, we are taking this one, this is how Riddick said, when every android has come here, then now this will come in my value sense, in those studies, who is on the Corresponding Index 1000, who is here at the ends, then one. Plus 20 minutes here - two plus districts Plus 20 minutes here - two plus districts Plus 20 minutes here - two plus districts will become - so now our new Hey will become - so now our new Hey will become - so now our new Hey will become - so we will give we will fry in it that - so we will give we will fry in it that - so we will give we will fry in it that maximum morning sum which Absolute Daily HD ticket after doing that which our light then forward Will come here and what return glass are you seeing, we are seeing its good, okay, so how to make it in this, our A is quarter inch plus one, it will become two or three - 211 place 121 Now in this, our maximum is - 211 place 121 Now in this, our maximum is - 211 place 121 Now in this, our maximum is Shambhunagar. Dainik Urdu will continue like this, now the one who went right and our enter has reached, the one who is our light has reached here, so what will we do now, we who left, died, left us, who moved forward, who was on the left, will now go here. And what is right is that there were no laptops here in the beginning, so what are we doing now, we are just suspecting the bill and what will happen after that, it will sit and then we will see about it, similarly we will forward it to left and right. If so, then what logic is formed in a loop which is useful for our allocation, the left one for potatoes, which will go from our point of view but from as many columns as there and if the one that kills these gooseberries for ghee on the right, it will go from our left till the columns, okay. After that, what we are submitting is this one will have a loop in this fort which will go to every form and whatever element is there in that block will be added to the previous one, whatever is in front of us, then one more look will be added on the right. Till the time interlock A for I goes into our daily life and whatever is our current value, whatever is this value, we look like a replica of our previous one, whatever Mara Saawariya Girl Sapoch, we add to it, see this was the court. Look at how I am looking, first of all, it looks sensual on the left, from zero till college as we discussed and then if it looks like one, on the right it looks like money till call. It looks like this, from N till college and after that it looks like air cleaner. We have been living every day because this is us etc. This literature is ours every day, so we are breaking whatever element is ours in it, sir, it is ok, after that, this logic here is ours that we should take our maximum in the morning and evening, record it. So let's see how to extract it, how can we extract it, okay, we will use it to extract it, first we understand the free in it, what we will do, let's take this example - 2 - what we will do, let's take this example - 2 - what we will do, let's take this example - 2 - 211, I have taken this Ranger in the name as if I thought that My songs are there, these three are not satires, free roles, there is chicken in our matriculation, so now whatever concept applies here, it may be very relative or free function, whatever you call it, test it and see if we have it like this. Our id often thought this amar jain act that if I have traffic samyak calculate at this time China can see that jubilee tips evening means like if I have them tips till z i it means that we have from zero index till z The time of all the elements is fine, that is, if the time of all the elements from here till here should be age relative, then it is fine, if we support that we have some positive understanding and we also have less lip balm eye, then it is fine here. If we do this one from here to here from here to Jo hai uske samajya song is back so we are with that if it's included daily vardo's then we can take this time if what we wanted is cabaret dance its prosperity kuru then if horoscope tip understood - cool at samaye this which is if horoscope tip understood - cool at samaye this which is if horoscope tip understood - cool at samaye this which is white Coming in front, it is related, okay, so it means that we can take the time of what is being formed in the morning from our eye plus point to Chetak, it can come in the answer, maybe the answer is that if we rearrange it, what about it now? If we do, then let's know, if the horoscope is considered active, then this is the complaint, this is plus on the other side - Gaya and laser in equal to two, this is plus on the other side - Gaya and laser in equal to two, this is plus on the other side - Gaya and laser in equal to two, this is our milk under the finger tips, amazing, ok, so what does it mean, what do we understand from this is our sleep, this is the question. We will consider the wound as relative, we will have it, both of us - will do well, both of us - will do well, both of us - will do well, okay, and we will find a relative solution for someone who is whatever support Singh's difference came to value, we will find someone who has tips, we are looking for someone who Great by value, take this one now great or for school we use lower bomb is a lower what do we do hit like we have any value this we have hair two three four 500 and we say no bar for Roast us, if there is Cheeka in it, then if there is a President in it, then he will also give it, like it is equal to two, otherwise it is A, like there is no woman here, then it will be bigger again, whatever will be, which will be the exact article, next bigger will be again. From there we see 4 is okay so here we will want to use why 9 will be used then here we have Greater Noida Authority i.e. whatever we just find diet and Authority i.e. whatever we just find diet and Authority i.e. whatever we just find diet and our greater should be daily vomiting whatever it is in vain then this value What did we find? We found it and time to find a value which is equal to this value or above its value. Hmm, there will be shadow fight. Okay, so that is close. So let's see how this player is using it. Whatever we have is - to - Whatever we have is - to - Whatever we have is - to - that you - to - the and electric, what will we that you - to - the and electric, what will we that you - to - the and electric, what will we do in this, we will take the complaint of preferred Russia and make a set of our own, because we will search for it, we will fold all the relatives in it, only then You will be able to find it when there is no one in it. Okay, so first of all here is our intercourse or - two first of all here is our intercourse or - two first of all here is our intercourse or - two clips of and this is ours here, so let's braid all the romantic songs in the set and with the message of the last one, I will show the rest of the melody ni nakhara. I will show you the sim which is given in the middle. Here on the head came - reaper - sugar - Here on the head came - reaper - sugar - Here on the head came - reaper - sugar - 2 - side - throat related - side 2 - side - throat related - side 2 - side - throat related - side and look here, came here 11:00 and look here, came here 11:00 and look here, came here 11:00 minor, came here - commission and 11: 00 - 116 minor, came here - commission and 11: 00 - 116 minor, came here - commission and 11: 00 - 116 Comedy All is well, that is, it is understood as magnetic, six, okay, and we had decided that we will remove the tumor. Understand relative - that we will remove the tumor. Understand relative - that we will remove the tumor. Understand relative - less lip balm has come and that is we should sleep in our layer, sorry here - that would be here - that would be here - that would be laser friendly. Got tips song I say i.e. whatever friend Got tips song I say i.e. whatever friend Got tips song I say i.e. whatever friend we have now will understand that 6 - in this we have now will understand that 6 - in this we have now will understand that 6 - in this one yellow our at to ki at to yagya - two one yellow our at to ki at to yagya - two one yellow our at to ki at to yagya - two i.e. of - two we have to remove allu and i.e. of - two we have to remove allu and i.e. of - two we have to remove allu and bond whatever is a frustrated amaze whatever node in that It will come and the value of our CSI is that e, so you - shut up, now either - ho or is that e, so you - shut up, now either - ho or is that e, so you - shut up, now either - ho or increase it - it is in Somerset, that is, it means increase it - it is in Somerset, that is, it means increase it - it is in Somerset, that is, it means our value, which is next to our apk file, our CSFI, next to our - to CSFI, next to our - to CSFI, next to our - to whatever word. Okay, after that, this is Manorama 's i.e. so 's i.e. so 's i.e. so what will we do now, we will take out the sum in the morning which is our finger, understand it as comedy - cognitive which is our finger, understand it as comedy - cognitive which is our finger, understand it as comedy - cognitive samaai hai, that is, understand it as relative, is our six the teacher here, it is not like this when we had added eleven - quality. The society is saying - If this is true, then you will die. Six plus two is 16, that is, our time has gone in the morning, the maximum time in the morning, in which the District President of Roorkee, but this is good at this time, he must have understood this. Main, consider someone to remember this as Chiku relative - Creative and equal to Komal has - Creative and equal to Komal has - Creative and equal to Komal has come with active, this helps us to know what we have to do. Larva has been taken out because garlic is equal given, equal if equal quantity, taken out on both sides, equal and If we take it out, let's see its logic, what did we do, we made a set that looked like Amazon went in front of us, it was as if it had become to me, all these songs are ours, so the maximum time to find us in it is that the alarm set has passed from this attack. Took it and I had made a summary of our back cover letter from your writing and we will go to every element, okay and what we will do is to go to every element of our evening city and add it, we will check in relative time, we are doing Got the clip, took out and our rings, what will we do now and she was taking out that school and I took out, remember this, we took out the silver, we are the one who is ours, take it, however come the brother of the old white cleanliness would be its lord. This vegetable - K means running from - K that lord. This vegetable - K means running from - K that lord. This vegetable - K means running from - K that Tuesday we took out the sugar in the hydrate loose press and if it is ours any value means exit then we in the race in our answer that whatever our sense of has lived but what do we do Scenes and J - ES file which is what do we do Scenes and J - ES file which is what do we do Scenes and J - ES file which is ours now - - - send torch light letter to that address that has value and he will be surprised by SMS and add it to his set on every less relative evening in life like we are here - K - Side like we are here - K - Side like we are here - K - Side I did not show this, after doing this, all the buttons will be there, I have shown the main answer, so basically this is our approach, let's see what is there in it, this is a very interesting fact, now see the call here now. We have one loop, so a call came from a thief on multiplex channels, he is going to Bigg Boss, so a call came in this too, ok, it's fine and one of ours is going to Rohtak, so it is a disease, ok, and then Our yes ji's place happened and then our people also this every evening its length is so anti and this note whirlwind is our rage in the log regarding this time is fine a 139 Pandey Janta Mian so this is our further complexity this Question sir, it is ok, now here I have followed in the question what is the number of roses much larger than the number of oil i.e. the roles which are in this number of oil i.e. the roles which are in this number of oil i.e. the roles which are in this habit, so what do you say to the column, hello how to make it, you can ask me a question. You can ask, see what we saw in the beginning, we are keeping the problem fixed, we are keeping it left or right, we are going tight on each column, by doing this, questions may come in your mind that we Abraham declared the columns, we finished the loaves. Column fixed us let us roll like a guinea pig if we have this matrix here we take equal and right and let us water with my bat and we with a tractor we are making the front and we make columns like columns we column Let's add Kolam from above that this Amit came out with it because if we do it like this then it will give no problem or this answer will be given, there is no problem in the answer, this answer will come butter because the portion maker had said that after the number of days. The number is from the forum, so if we do it like that, then they will give me 11000 rupees daily in the call to a person made of clay * every day * and here it is give me 11000 rupees daily in the call to a person made of clay * every day * and here it is give me 11000 rupees daily in the call to a person made of clay * every day * and here it is given to us and in its place and lots of law college or good, okay, so roles. If you agree with us then here we are multiplying twice and every day here when we were multiplying only once, then which one is better, this one is more chopped because it remains if it is forced here, that is why we shift the volume. It's okay to enter this approach, wait, you must have understood, if you liked the video, please like, subscribe and give advance deposit.
|
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 |
1,863 |
hello everyone so in this video let us talk about a easy problem from lead code the problem name is sum of all subsets or total so the problem statement goes like this that the zor total of any array is defined as the bitwise door of all its helmet okay now what your overall problem statement is that for a given array you have to find out the sum of the zor totals of all the subset of that particular array so you just have to find a subset or a subset for that given array and then among all the subsets you have to find out the zotude okay from the subscripts you will get like separate arrays then you will just find out the zor of all the elements in that particular subset and just add a total of all of them and just hit an answer now because as you can see in the constraint n is pretty small okay like the total number of the total length of the nums is 12 only so you can just do it in a very good first way just find out all the different subsets and also for every subset find out it's all of all that now how can you find out the subsets now there are multiple approaches you can use bit mask also for here my bitmaster also tell you with a small example let's say that you have an array of site let's say three or let's say four so two three five eight so you have and you can say array of size four now what you'll do eventually is that to find all the subsets you will make a mask for it by Master means that you will make a number that represent this particular array and if you want to take let's say 2 and 5 as a subset so you will mark one and all others are zero so this is all numbers now to find out all the possible subsets what you can do is that you can iterate over from one till 2 to the power of 4 all the numbers if you just iterate over all I must have one to two to the power 4 which also means that this is so what you can do is that you have to just find all numbers and when you iterate out all the numbers what you'll do is that this will form a four bit number okay so which means that it is a full bit number and it will iterate over all the possible like combinations you can say which is like zero one ten zero one zero like zero one and so on so different combinations different subsets which means that either in the first case I will take just eight the next case I'll take five the next is I will take five feet so these are the bit mask for this array okay and then you can use this bit mask to fire all the different subsets and while you are building the subset you will just find out the zor also and just add the Zora for different subset and that's it previously because the concern small you will do this in a variable first of all so what we'll do is that this is total in which you will find out the total this is the total length of the array now you have to do a bit wise you can say iterate over all the possible subsets so you can generate the possible subsets from 1 till 2 to the power of n you can just send it to the power of n like this also one left shifted n times which is just equal to 2 to powerful n okay now you will do the for Loop over till that time now what you'll do is that for every subset this is used to generate all the subsets so for every subset you will find out the current total zor so for that you will be storing it here now you have a particular State you can generate the state from whatever I you are on which I've told you these numbers one two three four five has different bit wise you can say uh representation and that bit wise representation actually represent the bitwise state and the state is corresponding to a subset in that particular array so what you can do is that when you have this number it is I you have to extract out every bit of it and from that bit you will tell that whether I will take the ith number in the array or not for that corresponding software so what you will do is that you will iterate over all the bits because it's the N bit number you will iterate over all the bits one by one that is also representing the and state array okay so when you're dating over every element in the array that is of length n you will check that whether I will take it or not take it depending upon the bit that is set in I so how you can check out you will do an and operation of I with left shifted 1 this number of time this eventually just check out whether the ith bit okay or not sorry okay so in the ith number whether the GTH width is set or not okay if the jth bit is set which eventually means that I have to take the GTH element in the array and for every element I will just check out whether I will take it or not take it in the sub array like current sub array if I were to take it what I will do this will turn true if this will actually this will do the like positive number if it returns a portion number what I will do is that I will do a zor of that particular number with the current total that is just used to build the zone of the current subset after doing a for Loop of uh you can say over all the current numbers in the array and forming out the zor of the current subset uh using this I have the current subset now I have to add this current Subs because it's not the subset for it the zor of this current subset in the total because I want the sum of all the source okay I just add the current total in total which is eventually the answer and the end algorithm answer that is storing out the sum of all the results so this is the current zor of the current state you can see current bit mass and this is adding in the total and the end we have the total of all results okay pretty much simple that's the overall logic that this is doing a follow and this is uh iterating for all the bits okay so this is let's say o of n Only but uh because of Interest are small you can do this in a very simple view also but that's it all right this will eventually just pass out all the technology as well so that's it that's the logic and the good part for this particular problem if you still have it outside this particular problem I will see you in the next one day recording and bye
|
Sum of All Subset XOR Totals
|
sum-of-all-subset-xor-totals
|
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**.
* For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`.
Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`.
**Note:** Subsets with the **same** elements should be counted **multiple** times.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`.
**Example 1:**
**Input:** nums = \[1,3\]
**Output:** 6
**Explanation:** The 4 subsets of \[1,3\] are:
- The empty subset has an XOR total of 0.
- \[1\] has an XOR total of 1.
- \[3\] has an XOR total of 3.
- \[1,3\] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6
**Example 2:**
**Input:** nums = \[5,1,6\]
**Output:** 28
**Explanation:** The 8 subsets of \[5,1,6\] are:
- The empty subset has an XOR total of 0.
- \[5\] has an XOR total of 5.
- \[1\] has an XOR total of 1.
- \[6\] has an XOR total of 6.
- \[5,1\] has an XOR total of 5 XOR 1 = 4.
- \[5,6\] has an XOR total of 5 XOR 6 = 3.
- \[1,6\] has an XOR total of 1 XOR 6 = 7.
- \[5,1,6\] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
**Example 3:**
**Input:** nums = \[3,4,5,6,7,8\]
**Output:** 480
**Explanation:** The sum of all XOR totals for every subset is 480.
**Constraints:**
* `1 <= nums.length <= 12`
* `1 <= nums[i] <= 20`
| null | null |
Easy
| null |
4 |
Ajay is like Hello Guys Money members, Sachin Gautam himself is going to ask this question, the name of which is Media will ask for a note. Okay, yes, we had asked this question in the previous video in a like and manner, Media After SM question, we have come up with it. By applying logic, basically you have been placed in 200 tests and you have to tell them madam. Okay, what did you welcome by putting likes? Basically, we have searched both the juices and further told her that at that time the face size is different. This was done, I had told the media in front of him, okay, like if I had this content lying with me, 3480 appearing, this content would have been lying with me, you would have made 90 pieces of these two, first of all, by merging them, it becomes ready for me, okay yes, this Now the match is made with me, because the size of Amar Shahr is appointed, so he will lift the middle element, okay my madam, there is a limit, okay, so last time we had said in the complexity of the function that 200 is only for enjoying it. It will take time for you but today we are going to discuss its appointment upload, which we will do and write. Basically, it is fine in the login class, so we are going to discuss it in this way today, but how will we do it right? If yes then basically what will be the position to do, once see what will be tried to do, what is our head going to do, we will see the name, how it is taken out, then just see how the middle is taken out, all the people in increasing order, 19 pictures in the middle. If you take out your media then like do this gym, on the left side you have all the small ones. Read them in any order and here is the biggest element for the small ones. Justice with the right hand side, then you have all the small ones. If you pass the smallest element of people with big hair and this big one on the left side also, there are five cloves on the right hand side too, then don't you think that your medium is fine since these two limits are formed and if the stitching was such that on the left side There are six people on the right hand side and only five people on the right hand side. Reference to you, it is the biggest bandh of the city, details and medium, this is how medium is described, if you will give life, then what am I saying? All the small people on the left side are in mother. If there are 10 cloves in this face, combined, I have 10 logins, you have five small people, that is on the left side and when there are five people, that is from the right hand side, I should say, by applying this technique, we can also give our face the meaning of these two addresses. It will be a scene, just try to engine it a little, I will visualize it, I will not really merge you, I will visualize the button, we have to fry that moment, it should melt or not, okay, if you see the combined of these two juices, then above. The people of Remedy are not running and eight nine knots total four cloves, so I have to keep the smaller ones on the left side and the bigger ones on the right hand side so that the day I can do this, I have to leave after a minute. If it goes well then mummy will be able to create such a celebration in finding me on the network and plus by continuing to create the creation, as if after searching once, you will find such a moment that yes brother, people are really together, they are on the left side, no sir, me. Along with the people who could do small industries, then which are these holes and this one person, I don't know how the question is going in my mind, I want such a celebration, okay, what did I do in this way, these people are on the left side of the orange line. Neither will all these be the smaller ones and those on the right hand side will be the bigger ones, but instead of this, it could also have been possible that you have these three people at the top and these four at the bottom, this is possible on the circulation. These three younger and these four younger brothers, all of them on the left side are bigger than the people, this celebration can also happen, so how to find out whether the circulation is ok, otherwise you can definitely find out if the celebration is ok by trying to see the numbers. Okay, Rimjhim herself, now I have made a celebration, it is a validation because it is a verification, it is a qualification of the bank truths, I will test whether this is a verification or not, then see, to test, I need that these people who are with us, this together. People, I am younger than these seven people, look, they have to support me again, so I said, okay but I need to prove it and not a 182 together, not B1 B2 and written, all these people are smaller creators than people 384 506 420 506 Why write something here because you know that these people will be smaller than your people, so there is no need for us to do this whether they are small or not, they are definitely smaller than your nutritionist, it is not okay because rested, I will see you ok what means Not only this, you had to know from the people lying here, you also had to know that these three people, let alone every other person lying here, how would you have found out, you will see that the biggest element here is if the people here If it turns out to be smaller than the smallest element then all the people behind then the reports will be small. You know that if the question is when will the flood happen then it will happen when to is lesson is morning floor together B3 is lesson equal to 8 if These two conditions are the correct name so I can say that read these seven elements on the slide and they will definitely be younger because on what basis did they trust in the secretary, these people are younger than these people but these people are the ones who invite you along with them. How will you be able to please us? Just look at the biggest element here. If the biggest element here is smaller than the smallest limit here then the ones behind will be smaller. Is the total right for you? Yes, similarly, these are the ones below. Four people are smaller than these four people, there is no doubt about it, the records are sorted, but are these four people bigger than these three people? So to test this, you will have to see that the biggest element of these is 10 small watch, so if B is smaller than 383, so neither will we be able to say that the people here on the left side are smaller than the diseases on the right side, and if the coconut is like this, then you can tell who will become the medium, think about it for a while and see. Madam, see who will become your medium. Look, the people on the left side will be the biggest one and the smallest one on the right side will be the monkey. For this you can become your media. If you find it then I just have to write this here, okay Jin, so if I create my media here then how will I create it, I will say that which can be the stone inside the biggest one on the left side that when A is two and B is one of these two There can be any one, so I said that the maths of a Docomo Biti will give it to me, but the value of the biggest guy in the set, similar to the right hand side, can come here and if this is the celebration qualification, everyone is talking about making banal. If it is happening then I will take out the minimum Ethyl from Madhopur and its fabric details media is ok yes this is my ok then this is when you are the total number of elements, if there were others then do you know how it looks if the total elements are going I am left. There is no fear on the side, he can do it comfortably, okay, no problem, okay, if we talk, do not do the same quickly, that too simultaneously, how is it formed, how many people do I have, you understand me, that total after a minute. If there are people on the face, then I will keep it on the left side. Basically, I will keep the people with me on the left side. If there are good people on the right hand side, then I will set such people. Okay, so now how to remove them. Watch the video. There are people on the left side. If there are good people on the right hand side, then on the left side. Which will be the maximum battery saver meeting? Okay, so I need an innocent child of electric years inside to take out my media, so taking out that is not a very difficult thing, no, how will we take out that medium, on the left side, these people come with them, I want the biggest monkey among them. Neither a two nor if you make a competition for sale, then this is near the cross, we will take maps here. Do minutes on the previous then the situation was when we and the size of the face is going to be your life so this is all we have to apply we have to see this every time on cigarette shankar and only and this direction verification effects and find out the medium okay and now if this What would we have done if there was no virus circulation? Would we move towards verification? It is not necessary that this question is a velvet one. Whenever there is a celebration in Bullet, how would we move towards verification? And we will learn that from the example. If you pass then it is okay then I hope you must have got the idea clear about what idea do you want to put here, we are right in the problem then it made you feel a little side that you want to take a vacation, I should take it to Rishikesh, so now let's see how to. The circulation at the front is the latest because if this condition was not there then this small mark on the verification would not have been a qualification otherwise I would have known that no brother these people are not together but when I would be making some other celebration that I would see. What happened, what am I doing wrong? Either it would not have been smaller than two, three, four or it would not have looked smaller in the proper way, then in such a condition, you are wrong Yogi. Now just think about what can happen, once I write, assume that what would have gone wrong. Whatever it is, your big one has gone out, eight and a half years old has come out due to the explosion, it is also a force, he himself has troubled me by talking to me, mourn carefully, my big one has gone out too, this is sports, so for the sake of justice, balance here for a while. It should be written so that the message sitting in your mind is the same for the person who is using it, so here also I write positively, day, do something, night, one more, small but small questions only 17, ok, and that's all. If it is bigger than before, then you think for yourself whether the blood circulation should be taken on the left side or on the right side, will validation take place on the left side? Will like the medal on the side, cute because you did not do this celebration, you did a little wrong, A to you, this officer is very big in not doing elementary, your vacation should be of such a type, only then understand my point, small people are left with you. If you talk on the side, then when this scenario would have happened, we would have said that brother, if there is any reaction then I am not here, I should be on the left side, dat menu eight hi, you have to pick it up and put it on Math-One, right now, I have put it on Math-One, right now, I have put it on Math-One, right now, I have taken you in this, I have not even told you just. Imagine, you get the hand for the first time, now it is not going into the nerves, now the device is not going to go tomorrow, only the moneylender is asking how the definition would be, let me tell you right now that A to B, if B has increased again, then the name has increased, friend. You should select a little more elements of the Bhi wale star because the Bhi wale Remedies are liking small elements and to select more limit of the Bhi wale star, you should select less elements of the A wale racket and to select less elements of the Bhi wale star. You should shoot the light of this celebration on the left side. Okay, if that aggregation is pure 10th then it would be the right Yamuna Nagar reverse case. If this situation is wrong then you should like the celebration on the right hand side. Okay, on the table you should click on Exam. Let me show you who it was and how it comes, so I just went to the app in the first condition, but I came to the second condition. Do you understand the yogi in the first condition? And now let us see, it is okay to do the second condition. Saturn, who became the first one, moved out and we got stuck in the second one, so getting stuck in the second one means that yours is 13 and I should write it like it was written here b30 has become greater, one has become greater than last night, okay something like Here it is on the phone, here it is eight, here it lies seventh, three and work ok, here it is 9 and IS, Mr. Everything is selected, till now it was a small in three, four wheeler finance was done, but Savitri smaller reduced note from this in the nerves because so much has passed. It is not smaller than, you should select a little more limit and to collect a little more limit, you should shift the line of celebration to the right side. Okay, so we kept shifting the line of celebration and kept seeing that the day You got the verification that day by applying 21 such forms, how will Sapna Madam remove the fate of either or the other, okay then there is no problem in that, a day will come when you will definitely get the celebration, okay then wait for that day. Till the time of celebration, India should approach the harshness of winter and the day it will go into circulation, we are going to do this by releasing its semen. Now how will we clear the exam, for this we will have to see an example so that I can give you the value in reality. I can write about the declaration of celebration and show how the shooting has been done. Let's make an example of this. Let's try reading a live example. Let's turn on some values mode and try to make the middle part. So, as if it will be given to us, the latest will be given to us. How much time will it take to do the middle part, what is the process we are adopting, how will this application chip work, what should I talk about, you have understood it, you will see it passing on the example here, okay, so I am giving some examples like this, relative free 912 60 I am a serpent, okay. If I get the first share of Remedy, then I will take the second lemon for eight. This is my traffic jam Pulsar, exactly like this example, the values daily in the bus values daily in the bus values daily in the bus are fine on that, fine, so like I would have taken something here, Hans 760, the food, meaning, think carefully about this photo. If you take it, there will be no such problem, then for 145, you can take only a few, but here it will go a little faster, so you will get 26 2860 ku, so let's write it here because okay, by applying the method of first and second, people will get this. 70 people above 60, these are the people with reference, this is not like this, if you do the biggest and smallest flats in the list of these people, then your 90 should be the latest, don't trouble Akbar, if something is fine, then he will see in which way. Let me talk about the celebration, what is verification hair distraction, correct order, five, these people are two Jagmal options, so the latest is how do we approach this survey, do we get Shimla forever or not, let's see by using our concept. You can apply this once, okay game, that this is this, you immediately write the example here, these taxes are 12345 to 6 7 8 9 4 thousand, second according to 0123 45 to 60, I will try, I am above in which I am walking in a little. So this is what I have kept here, I have kept it here, see this way, I have put the question here on the meaning side, so let's do this, how to know that will like it, then you have got it, 155 are yet to come, otherwise you will know that Where do you like graduation on the right side, then it is not a very difficult task to find out, it is a simple question, I write it in marks, you have found out the minutes using low plus, Hi Bittu, ok, now you know the reason, how many limits do I have to pick on the right side? Element weakness means not in the right hand side because basically for the left side, you have to do two elements from the upper one, how many elements do you have to do from the lower one to make the left side, so I subscribed but got it a little wrong, how many elements have to be done from the lower one. If you want to pick up then the elements from back to back are also okay, then how many limits are you going to pick to make the left side from this, then how many total elements do you have to disregard the passport, total alarms. If we were talking about that then you comment. It has come from him - but it is not you comment. It has come from him - but it is not you comment. It has come from him - but it is not like this, look, you do not have this 14887 total scriptures, both the legislators should be on the left side, 127 - minutes, where on this upper right hand side, where will he like the 127 - minutes, where on this upper right hand side, where will he like the 127 - minutes, where on this upper right hand side, where will he like the index, so I take the index once. Now you have Mitthu on the right hand side, you will go to the soldier intake - 205, right hand side, you will go to the soldier intake - 205, right hand side, you will go to the soldier intake - 205, so these indexes are coming, one index is yours here and one is intact. Okay, if I make a celebration raw for you, then that celebration is from the one which I have just extracted. And two induction this is your meghwal and 6111 your bell intake is ok elements of but in the whole edifice of people are to present in now person celebration wale don't that application violet what should have happened for 90 1028 this status It is a 126 shirdi electronic shift straight 2612 not small, it means that you will get more of the upper elements, slightly smaller elements, you should pick more of the same elements, therefore, the right hand side will suit your celebration in the same direction. How will I deal with this? Equals to meet plus one. Okay, Jeet. So when you people keep one more name Sumit Laxman, then what will become of your vacation? If you also raise this question on the bill, I have kept it here. I am on plus one. Okay now. Have taken it out once again, then this time the stones will be erased plus fiber to interest index number is correct so this was my I have taken out the element in the morning pick from fear in the left side DSC to click on the left side how many elements are picked then we Do you understand that brother, check that you have got the net value, basically this is the fold, neither are there four elements in fact, from here this pass is complete in the spices, so basically here the celebration started, go to 9416, this city will be the element. Children, how much intake - potli element pea, then intake - potli element pea, then intake - potli element pea, then how much will be the value of the vine, the real ok, so there is circulation here and the vine is welcome, if you have it, then don't look at this, try to understand that when my hum is removed from here, he is in that. First I make the development, so I have also come here, apart from these, I am selecting all the celebrations in this way, okay, this is the understanding, control and Africa and up, then do this thing, okay, this is our next celebration latest, that is okay. Or no, okay, let's test it quickly, then thirteen in the morning, 1024 yes-yes, okay and don't morning, 1024 yes-yes, okay and don't morning, 1024 yes-yes, okay and don't listen, for it's not seen smaller than 2015, it means that the small elements are still there, it said, hey, it's near, you have one, it's a little. More elements should be picked, you should move the graduation from yours towards the left side, so I will pick it up and put it on Mitt Laxman again, this time I got it, my low is going to come here, okay only this time, my call here is correct. Now you have to look carefully once, okay, now you will go to your, where will you get the submit, then it is correct on this index, you have removed it, now you will see that okay, it disappears, it means there should be a pass valley in a minute, it means this above. Do the response element, the upper one is here, the lower one will start selecting the time two because the total is 14623, sit this 75 upper one has given, the lower two elements will be left, okay yes, the bell icon is your two but details in text ads Paris Time and S Indexes minute and you will say that the question is this one of yours and I think this is the application, if you click on the letter, then first look according to this weft joint, what you have to do, then look carefully, you have got this math - it has become With this, you have a got this math - it has become With this, you have a got this math - it has become With this, you have a bell, you are bell tied and what you have to check is that the element lying on mid minus one should be smaller than the element lying on the index of bell. This thing is that the element lying on bill - mind is that the element lying on bill - mind is that the element lying on bill - mind is smaller than the element lying on the index of mit. There should be distribution and validation of test witch proves. The people lying on the left side are smaller than the seven others lying on the right hand side and we have got our celebration. It does n't take much effort to take out the media after the celebration. How to take out the medium on the left hand side. Is the biggest but because must admit total length of tab which is seven tomar face because your size is done even then only two people will be there. The biggest element on the left side is 4470. Who is the biggest limit of 600 on the right hand side? The limit is small, 1922, who has become small, 1972, for this hair media and this was your media, in this way you will be able to remove the login plus animal media is not valid, what to keep in mind, you should keep this thing related to celebration in mind, celebration has come, if it is okay. So you can understand that you have got the middle and if that application is not right then basically you will have to work a little harder, then you will have to see whether this celebration should be run in Titu year or again keep the relation in the right year. Okay then you will have to do this. You will have to see if it is correct, so we are doing it in the login place end because we are putting 22. Well, that top wrapper, search water, okay, yes, I hope you have understood this thing, what do I want. That you can change a message and part it with your hand is fine, it means that my celebration went on for a while, something like this example in which the secretion started from here and then moved towards the left hand side and then it moved forward like this and then And has the focus shifted to the left side or not? Understand that the hand is responsible. Once you do the parts in the acid example, how will you understand all the chords as to which case can happen? Okay, basically, what you said about the major focus is very true. After taking out the circulation, keep these four people under your control because these four people will tell you that your vacation is valid and if the celebrant is happy then they will cross it and if the celebrant is not then you will have to look for verification, right. So let's try to fold it once, if there is wealth growth, then some more, how would I like to pass on one name to you, but after writing that, okay, so I hope you are getting a brief understanding of it, you would be feeling good. So okay, I will try to fold one thing myself, do some airport. Okay, so let 's type it together. This one is there, 's type it together. This one is there, 's type it together. This one is there, so what do I need? What I need is just 2.01. The sellout is there, so give me two points like this, the one 2.01. The sellout is there, so give me two points like this, the one 2.01. The sellout is there, so give me two points like this, the one above me. But - I will organize a celebration, I will above me. But - I will organize a celebration, I will above me. But - I will organize a celebration, I will see if it has come, otherwise I need all these things, so first of all, I will prepare lo chili or keep it in zero and half, what should I keep and in the development ok section, Hike app, but it is ok till now, as long as you request from it. Till then I have to do my work, first of all I will finish it and let's do one more work here. I will only need a lot of total elements, so till then I will take a little watering plus to-do till then I will take a little watering plus to-do till then I will take a little watering plus to-do list. So this is what we will finish. Let's keep it, okay yes, we can also use a big one, okay, so potatoes, so soldiers, till then, what do we have to do, first of all, we have to take out our meat, how will we take out the meat, it is a plus, but it's okay, so people are a plus, but I Took out my middle, now I have to see how many limits I have to pick on the left front side, also how many limits I am picking on the reference side and if you read this above, you can also do this that this one is On the left side, how many limits do you have to pick? Okay, so how it will happen is that the total elements are like this, take your Y2 and from that - on two take your Y2 and from that - on two take your Y2 and from that - on two of these Remedy, according to your test, click on the previous year, that thing is okay. Yes, this thing is done, my friend, now let's try to understand once more if it would be right to write this team back to just imagine, you have total tera elements, hello, a little even once, see, it was fine but I want to show you for more. Just imagine, you have a total of 13 elements. Okay, so for the first time, I am telling you how much I have got. I will show you by putting it on the previous page. Here I have given this dimple. Okay, for the first time, I am giving you the media coast. Isn't it because of that, how much total elements are there by keeping the left foot in the bell and this is sick Chhoti Bittu is 6 - complete test Okay yes, this little bit does 6 - complete test Okay yes, this little bit does 6 - complete test Okay yes, this little bit does not come right, just like that, by placing the elements with the left foot and I am the one who has piled on the game website, I am when we did this and Number permit system and scalp, so for this I need to work harder, what will I do on that, I will write soil plus one that if a little if you have a total little element, we have a docking that I have been placed on the left side, people are okay with that. I want this, okay, so this scenery has come to me, this left side boundary wall, my real sisters, method, okay, now Meghna, who has taken out some of her elements, four elements, this composition is located in the rally which I have here, pass the next example, this one in Jio 4G, this one I have worked out this, I will try it first, if I give you my points right now, then mine is on the left, there is more left here, okay, so I will do a comparison, otherwise I will write that look for tuba balance aggregation to be the aggregation. What thing was necessary for you to have? It was necessary to have this thing that I write once money and ask you that idiot left minus one its relation to right hand side means lower alarms which after suppressed left gun point and shoot points electronic Meaning of my off things and talking about the above rate, not only listen to it once and here there was a pin but also write its name why mess with it, so keep this name of this also here also ABC is called AP. Okay, that will be a little more minutes. Okay, so the ones who are teaching the element on the bell lift index should be smaller than that, the one who is showing the index lying on the left minus one of mine, the soldier and the morning one, the partner should be together and understand and this is the left. This left minus one okay this left and this blood - - verb - if this is happening then my blood - - verb - if this is happening then my blood - - verb - if this is happening then my you write this here I am trying ok yes so here I will write the real that okay this we understood now also I have been left The element on the left side of the minus one element Laddu Shubh Lagna is equal to two wedges, if such a woman is being born, then it is the education qualification. Okay, so if this thing is happening then you will get the celebration verification. You will get updates on this movement, so you can get your medium returned from here. Otherwise, I will make the media. Okay, yes madam, because if it is possible to double, then double the name and make it double media. The thing is, this double medium is just a little bit. It is free that we have developed different from how many people are going to be there in your chilli-masala, how many people are going to be there in your chilli-masala, how many people are going to be there in your chilli-masala, then it will take more effort for us if the total number of elements mode on to this effort is given number of people in the machines of semolina road which indicates. And also indicates that if you have more number of people in the simar face, then if you have even number of people in the mar face, it is right, the kind of matching address, how is it formed, pick up the left [ __ ] maximum, then the how is it formed, pick up the left [ __ ] maximum, then the how is it formed, pick up the left [ __ ] maximum, then the laptop maximum, you will get this left minus one and also Which one is bigger on the left - right and is bigger on the left - right and is bigger on the left - right and how to get the community tight coming home on the right, it is 1/2 inch on the left and the belt, so the 1/2 inch on the left and the belt, so the 1/2 inch on the left and the belt, so the strong tone is also not right, which here I make it my medium, how do I want maths You can write 'in' on the left hand side 72 times. want maths You can write 'in' on the left hand side 72 times. Take out two or three withdrawal matches in Africa and then it is ok if you take out the 'in' on the right Take out two or three withdrawal matches in Africa and then it is ok if you take out the 'in' on the right Take out two or three withdrawal matches in Africa and then it is ok if you take out the 'in' on the right side. Otherwise, how will I be taken out on the left side? Set the lips, the message will be inserted. Maths Are O 's Math Dot Maximum Basically Did. 's Math Dot Maximum Basically Did. 's Math Dot Maximum Basically Did. What kind of partnership do you have in the Not Match, to take out the innocent child of the year and BDS, both the people from the left side Left - Bullet - left side Left - Bullet - left side Left - Bullet - if this one is made electronic, this one is left - the owner if this one is made electronic, this one is left - the owner if this one is made electronic, this one is left - the owner and along with it, the diseases are also bean left - and along with it, the diseases are also bean left - and along with it, the diseases are also bean left - but if you get a competition done in these sections, then you will get your Laptop match will be known right. To find out the deficiency, there is a question in the match dot, that is, by playing one, that portion has been made. By doing medium practical, the tension is quite high. The concept looks a little like that. In this, in the media states, you are two applicants left. To a large extent, I am seeing in the messages that a little bit is fine, yes, we are right, to remove the deficiency, you have to do this thing of left and b ride, 100MB, left, right, left and this, you only have problem in commenting. Now media is media plus and there was table and if you don't do the table then you will get props if you don't get it, okay, this is this letter and if you have and number, right side, left side, face wash, April maps, we have taken out the gift, then copy this. If given, then copy this and finish it in the media, will the album of A [ __ ] come in the media, okay yes, when our album of A [ __ ] come in the media, okay yes, when our album of A [ __ ] come in the media, okay yes, when our application has come, then we had organized our meeting, we have learned, when the celebration valid has come, will return and the media is happy. -Khushi, we got our medal. If our happy. -Khushi, we got our medal. If our happy. -Khushi, we got our medal. If our protector does not come, then any of these conditions will deceive us. Yogi, when the condition has deceived us, then check out which condition we got soaked in, then I write here that I too must have been like this, one 's absolute - instead of being a liter, the mind has become greater, it is 's absolute - instead of being a liter, the mind has become greater, it is 's absolute - instead of being a liter, the mind has become greater, it is okay with the flip, the difficulty is now either this stitch must have been stitched, must have become a senior, friend, only one thing must have come, that this pension must have been passed. Is it true that if both were present then it would have worked like this, it means that for so long one or the other one is false but still I write here to explain that let's write this condition that also left minus one might be greater. The playlist is done, okay, so now in this situation, see where you should go, then we will do a little device and come back again, a little longer, we should keep revising, they neither do Himachal, okay, so I will tell you. Look here, it was my first time celebration, isn't that my celebration, it was big, it was made relative to me, okay for the first time, yes, it was my left, this was my left, minus one, Saurabh is very active, isn't it. This left of mine was this was my Bill Gates and this is our left too - this is the my Bill Gates and this is our left too - this is the my Bill Gates and this is our left too - this is the first time, ok ji, which nation cheated us in this condition that look left - also closed The that look left - also closed The that look left - also closed The left is small but the bean is left - the plant is left is small but the bean is left - the plant is left is small but the bean is left - the plant is not smaller than the love, it means the hairs are shorter and the one which is smaller, you want the one on the left side, you want more limit on the left side, to shift the chinu circulation towards the right, you need a log. Picking up and placing it on Mitt Plus One, Sita's Kiss, if the question is shifted to the right and is suitable for send, then we came to know that by writing which condition, we will get our fitting done, hence, we understood that if this condition is there. Not this bulk condition and pass. Which garnishing did we see? Yes, according to the celebration, we saw that again there is no problem in writing. If you understand while writing, then boil water well and the mistakes will be reduced in your left - mind. water well and the mistakes will be reduced in your left - mind. water well and the mistakes will be reduced in your left - mind. Bay left and this villain smile so error minus one so I was the smallest since point but bean left - Manjudha Soy was point but bean left - Manjudha Soy was point but bean left - Manjudha Soy was not small on the contrary it was big so you should select an egg and element then for that you should keep your celebration as Rajdhani Night. If you want then whenever left minus one becomes greater than late as in spinners and 20f minus one was selected by you then it means you should flatten one more element then to select 1,000 hum element then to select 1,000 hum element then to select 1,000 hum you should pick up the log and keep it on withdrawal. Okay, let me put a comment here and say that Dare there are more elements to be difficult to think about the left parties in left which originates from. Comment all these things and if this condition was there then think something. Left - 9th bada gaya. Dehra mor think something. Left - 9th bada gaya. Dehra mor think something. Left - 9th bada gaya. Dehra mor element ko pick from being made to whip ne laddu is correct to participate so here I will write dehra more elements and tu bhi period in left from which are from being okay what does it mean and how is it to the left side You will keep it by minus one, okay, this was ours, this was this, but this thing will always be fine that this means try this, you can also add this as if you can come to you, so I want to show you an example like this how it will work. First of all, what we have taken, first consider it as a regular exam, there is a little question that if you are not an enemy or still do not feel like going to Math, then what will you take, then we have given just a little condition - then what will you take, then we have given just a little condition - then what will you take, then we have given just a little condition - rest, we have given Major Gaurav Thakur. It's done, it's just a little condition sense that you need to keep doing it. Okay, let's take a quick look at it, I have come here with so much lesson for you. Okay, so this part of the court comes with the latest drawn. One of our regular example kilometers from such a close distance will be fine. Okay, so this is a little regular example for such people also, everyone is selected. It is not necessary that it is big, it is always written like this in this area and it will be small in a little bit. He has become a scientist. Okay, okay, let's not hire anyone. He takes it to his head that we will save space here for writing. Okay, let's disassemble our iron once. Initially, I have kept the alarm. Rupal and Hi. Basically I have kept it as Don't lamp or Don't drink. I have kept it so that I can easily do the odd-even thing. Generally can easily do the odd-even thing. Generally can easily do the odd-even thing. Generally we keep it in Don't - here we keep it in Don't - here we keep it in Don't - here but I have kept it express this year on purpose. Okay, that is the reason for keeping life happy, I knew that there would be an extra element here, what you want this male caste section should be made like this, first do one element from this, okay then let me tell you, for this reason, if you want the other He wants to match with the side, he has his own conditions - pension should be done at the time of every test own conditions - pension should be done at the time of every test own conditions - pension should be done at the time of every test - this thing should be there Sasaiyo, there is - this thing should be there Sasaiyo, there is - this thing should be there Sasaiyo, there is no other problem, okay, so let's see for now, but what should I keep in Lo and what should I keep in Hi, is it right? So I, that's why I kept zero and that's my real intention, by the way, I kept it in Hi, your Hello friends, good tips, okay, this is how I kept my electrical, I am standing here right now, lo, it is here, Hi is here, so when I first I will take out my left bar and do this - keep it on one too, then let's keep the thing, there and do this - keep it on one too, then let's keep the thing, there and do this - keep it on one too, then let's keep the thing, there should be no problem. Okay, IS-RAW will not have any problem, IS-RAW will not have any problem, IS-RAW will not have any problem, we will be fine, how are both of us, keep it, now it is written like this, let's do it anyway. So his don't thing, should there be any problem, it is just a game of plus minus one, should be caressed on the media, straight down, let's do it with force, okay, so I take out people, achieving the goal, okay, so you have enactment, you have kept mine, here is yours. Hi here, if you have removed the left then you should drink it in the left plus is sithu Rajasthan ok so for the first time April left make this right, abe next to the laptop you have also taken out the laptop is this remedy total how many elements of 2014 plus one by two is 7 combined Report wrapped also your index number four nor laptop and coming means you got 10 aggregation by selecting 2014 element you have okay this way this one this dot this also you first of all one third circulation white celebration after so now If we look then I came to know about electric, I took out one more thing Elect - Man to elect - Bangaru Elect - Man to elect - Bangaru Elect - Man to elect - Bangaru Laxman answered these questions of saints I will know whether there is a celebration will or not then I saw this on the left - 126 then I saw this on the left - 126 then I saw this on the left - 126 Tubelight This is the status just before condition You are fine, you have already collected the left minus points. Leftist is fine. By doing the second one, your power is there from which you came to know that there is no verification. Aman Shanti saw that you will get circulation. So I came to know because left minus one is your greater than. Have you placed it on BF from left? Let's keep it on plus one and please like this with Mitt Laxman that you should not be VAT and if there was plus one then that is the name of vinegar, I will fix it, okay if you understand then there should have been egg instead of minute, okay Okay, so he will go and fix it for me, so now let's take a look at it. Is it close for now? I picked it up and placed it on the ground. After picking up the latest ones, I keep it here. Okay, happy time, I will take out mine. What is it, I have it lying there. For high there is 6 and if we find out the value of A global, then how will L come, people are lucky, back to it, index number four is fine, then this is ahead of you, number 19, four, if you have removed the belt with its help, then how much is the belt going to come. The bell will come, is it real, neither is it insult or circulation, something like this is happening, okay, so the first race has given you four elements letter, on the other hand, this one has given you three elements collector that if I make them powder and show them to you, this is the belt. This minor and this bell - Mana Latest Chakli Apni Celebration - Mana Latest Chakli Apni Celebration - Mana Latest Chakli Apni Celebration Ok Egg - 1st Lesson Diye Butt BL Maheshwari Ok Egg - 1st Lesson Diye Butt BL Maheshwari Ok Egg - 1st Lesson Diye Butt BL Maheshwari Motivational Bell - Magan If it looks bigger from the left Motivational Bell - Magan If it looks bigger from the left Motivational Bell - Magan If it looks bigger from the left then it means you should make a smaller more element. You guys pick it up and put it again. Will give on air plus one, so that what is going to happen, due to which people will get up and come here, my circulation and right hand side has gone away, okay, so here I am, now you have a five, hi, I also have a pipe, equally, here, I am having an affair, hi. The message is read, ' equally, here, I am having an affair, hi. The message is read, ' equally, here, I am having an affair, hi. The message is read, ' Hi, please do it. Hi, one more time, run mine on schedule. Okay, so we have you, there is nothing wrong with it, so here are the others, prepared in this manner, this time I will get mine done this time. Let's try to get it done in Delhi, earlier it was going well, I, the people here, yes, here, okay, first of all, how will we come to get it done, okay, then you will see that you have it, I mean it is from above that you and I are my last one. Both are agro, so I had made this question, how much have you got this time? Okay, okay, this time, put the egg in your plus, yes, if you remove the hair, it will come in 25. Okay, yes, let's go. There is no problem, the exam was done after seeing the sign, we have how much to come in Japan, we have seven minus points, now we are running in many conditions including us, 15 came, do the response element above, select Limited below, this is your pair. And this is it, you all are also okay, this is done egg-bun and you all are also okay, this is done egg-bun and you all are also okay, this is done egg-bun and this is done your bell-slaughter. Now what will you this is done your bell-slaughter. Now what will you this is done your bell-slaughter. Now what will you see that this circulation is correct, so we are feeling right to me, we trust our conditions and minus one kiss. Lesson BF OK Bell - Bane, for this lesson it BF OK Bell - Bane, for this lesson it BF OK Bell - Bane, for this lesson it means that sometimes celebration is perfect. For celebration pack, take out the media of this medium - Novia - Take their out the media of this medium - Novia - Take their out the media of this medium - Novia - Take their marks to get the element out. See what Muslim tea you have. Minimum balance of seventeen and armenia or egg and bell nineteen ki 7 plus note to wear bittu we are getting perfect medium so on regular example it is working fine right now let's see that it is always correct meaning First of all, let me correct this thing that I have written here, so it has not always been correct, this which you absolutely confidence rates, absolute confidence, we are writing this, right minus one left - money, all these things. One minus one left - money, all these things. One minus one left - money, all these things. One should not write with confidence. Do you guys understand that whenever you are using indexes from outside, you have to be a little careful whether the next word is there or not, then such situations can arise when the indexes wallet name So I am telling you once how you should take the exam and pass it, you will have to have a little patience, the question is a little more important and the basic way of doing it is a little bit okay this is it, have a little patience once in the exam and Watching is not fun without it, okay, so I hopped you some old exam bag, fun, in a way, I had my own media, I made one, I will leave it for the exam, okay, so once, I am going to have a little free 1956 12:00 little free 1956 12:00 little free 1956 12:00 or some ice cream okay. So, here's my other example to show the symbol, I want to show you at this time how the celebration will be, the circulation will be of this type, it is not meant to select the people on the left side, it means like this. A little bit of people, if all the people like the Islam picture on the left, then something like this, a little more big relationship is okay here, the whole increasing and by type, so it is of this type, so let's see how it should be, come with your correct answer. The house digit should be seen only once, that's it, okay, so here, first of all, I will take the index, so 2012 is free and this review is 0123. Okay, and quickly write whether the bulb is needed or not. Okay, so let's take the index once. First we have taken out total elements, this time it is a total limit question, this time you have listen, okay you have come and first of all take your electrical wire, please get it, I will make it, then people keep it according to your style and length, keeping in mind the previous days, okay. So I also put it on my face, there is no problem in that, you can put it here too, I am not worried about infidelity anywhere, I have to get the work done by you media person, neither we can write that thing nor invite, it will be beneficial. Why would I be able to say see now? Let's see once. Okay, so try your electrical mane, how do people write? It is white. Okay, yes, this is the second pilot found on the people side. Index number two, you should select the layer from the top one, so take that. Your hi is here and a week now this guy has come ok so here your left has come ok and electricals got his bf taken out so total element plus one butt kiss let's do this I want to have relations with electric shetty latest 575 - Two way Sril is fine, latest 575 - Two way Sril is fine, latest 575 - Two way Sril is fine, even if there are five ratti wooers on the left, then that bell will be its own here. If I talk about vacation then celebration is this app. First of all you will test whether its circulation is ok but see why this app is not working. Loot viewing was basically left minus one off but those who should be picked up will keep it done so I have picked up this one and now take out what I have done here and here, if I talk about it is because minus one is still a little And the elements should be selected, so you guys will pick it up and put it again on this plus one. And here, what we had placed is our Hi Ko length tree, here is the unit on Twitter, so one and a half celebration is still not received by you and if you had stopped. If you are decorating the celebration, if you have got some circulation then go to this light and if you have not found this application, then that is the reason why it was kept there, now let's see, here is the latest point oil, so I have found this out. Try this, I have four coming to me, what is yours, I would say wait a little dip, what has happened, according to A, the trees above should be raw silk, absolutely correct things meaning, the four people above are right, so small that all of them It should belong to the left side, but it does n't seem right, so that's why I kept the phone in it, latest point BL, so its outcome is hands- kept the phone in it, latest point BL, so its outcome is hands- kept the phone in it, latest point BL, so its outcome is hands- free - to arrest, that too, stitched it free - to arrest, that too, stitched it free - to arrest, that too, stitched it here, now after a little while, you started understanding what I wanted to say, this is I would like to say that brother, you can use this mail, here I have to write this article about how to write this, there is four in the loop, no more lo and hi, I will still come inside, if you are a sugar patient, then here you will get this information. It should be understood that before using the value of Intact Slightly Wear Death Index, you should have checked it. Okay, before using the index W, you will set it so that I could not write the leaf, but that is nothing on the right. So when there is nothing on the right, ca n't I consider it as infinity? Ca n't I consider that there are two here? When sorted, there would be infinity on their left and right sides. On the left side - Enfield On the left side - Enfield On the left side - Enfield Types of Understanding Infinity. You are right with what I am saying, for example, it could also have happened that whether you want to select all the previous limits or not, then it is very important for you to keep this in mind, so definitely keep this limit in mind, now Anna, do not do all the tasks in time. I will get it okay, once it is open now, I will try to bring big smarts here because Alex, you have that infinity of Syed Abul in your hands equal to Agro Trains. If I talk about celebration circulation, then 10,000 talk about celebration circulation, then 10,000 talk about celebration circulation, then 10,000 celebrations at Yaad. Ok, so now I will see why my answer is correct, so Retail - 118 is also less than MS Word OK Year - Retail - 118 is also less than MS Word OK Year - Retail - 118 is also less than MS Word OK Year - One Bell and Bel - Mind When there is One Bell and Bel - Mind When there is One Bell and Bel - Mind When there is nothing in the right then less remuneration for this thing and Bel - Mind When there is nothing in the night, thing and Bel - Mind When there is nothing in the night, thing and Bel - Mind When there is nothing in the night, then that bandish was always the small one, so I took the infrared loot in oil. Okay, so because this white celebration of media of this small ego should be taken out from the egg, because here the total number of elements and keep it for you, then you What will we do left message, four medium left matches, first of all, the maximum of tenth and twelfth - morale - maximum of tenth and twelfth - morale - maximum of tenth and twelfth - morale - but once you answer, if your medium should come, it will keep the condition in mind, so think a little thoughtfully about the index which you have lost. Kothi Chehra is correct, so I am going to fix it once in the final, that is why I am telling you this again and again, give two examples in our room, we will not talk about it, first divide the star masala, first what are you going to do in the cheque, then more. This is the serial example of Man Ke Laddu and if this example is correct then you will write your part on all these things then or if there is a part then you will be able to submit it by searching and following this condition etc. I will be a little successful then here I would like that you I am feeling a little scared even before using the laptop belt, how to do something, so I am here, I really check the four variables, before writing this condition here, I take out the name a little and according to that, the value of the variables is fine. Yes, in L minus one, I will put a little before taking out and similarly, before taking out A, I will put in a little in Africa like this, before taking out, I will also put in left - and before taking out, I will also put in left - and before taking out, I will also put in left - and before taking out, Madam, there is ghee, so these things give us a little You should write it thoughtfully, okay yes, you all can find this left minus one and this is the left two value, I say it is greater than zero, if this is the calibrated period, then you can find it on the left, you cannot find it the other way, instigate because. If it is Vivo on laptop then brother Alex - can't get the mind out, there is Alex - can't get the mind out, there is Alex - can't get the mind out, there is nothing on the left side, everything - nothing on the left side, everything - nothing on the left side, everything - set it towards Enfield. Okay, so if the situation is like this then I am on the left, I am in Sonipat, I will put the rice, send me interior dot mail, I will contact you. If it is started, if there is nothing on the left, then Wicket Readers - Celebrity, if there is then Wicket Readers - Celebrity, if there is then Wicket Readers - Celebrity, if there is nothing on the right, then Vacant Plots in Freedom is working there too, then this left minus one can be taken out only if left Grand i10 if electrical Suzy which is So how to get the admission - It is So how to get the admission - It is So how to get the admission - It is lying on 110 tracks - Infinitive Energy Mitt Ok so lying on 110 tracks - Infinitive Energy Mitt Ok so lying on 110 tracks - Infinitive Energy Mitt Ok so you can get Antioxidant Pay Mean Value Recipe from here and if it is not so then we can easily get this one left money done, okay yes. This is the same, after doing first and second, there was a little fear in the left while coming out, there was no electrical in the middle, not somewhere, the one on the left, which is poor, has a different index, it could n't be made equal to the don't lens, when it happened in our example, is n't it? Look, in your example, the fodder was kept for Rs 1 lakh, so if it has reached par from here, then you know what you should keep in mind that brother, then the egg cannot be taken out, that is related to the question. If the balance has reached par, then it has to be given this amount. You have not forgotten to replace with value and second thing, if you do not reach then you can easily pick the value of lie in a given, so it is mind that the thing is also left, so friend, this is the condition Senapati, okay if you win, then left now and also left - Even first, I write the left - as per my left now and also left - Even first, I write the left - as per my left now and also left - Even first, I write the left - as per my wish, it is okay, whatever I take first in the wheelers - then if I write the app, take first in the wheelers - then if I write the app, take first in the wheelers - then if I write the app, balance - closed, Delhigate, ok, then it balance - closed, Delhigate, ok, then it balance - closed, Delhigate, ok, then it can also be taken out in the left - utensil, when left receives this can also be taken out in the left - utensil, when left receives this can also be taken out in the left - utensil, when left receives this notification, ok, if the yellow clothes If K is equal then also in the left side and minus one, you will not get anything on the left wall, so you should add W here in 2008 because it is sorted the other way, you can also use the value of left world from the side. Can do ok when for left also you should keep in mind that bill B.Com game is not done, if left B.Com game is not done, if left B.Com game is not done, if left ventricle is done then what should you do, interior dot maxwell should be used because there will be nothing on the right hand side, it would mean No, this is the stage of sewing when you also have to use all the red chillies. Okay, yes, see everything, we have basically fitted these conditions, but I have come to know that can such a situation be possible, so And before using it actively, please check, otherwise we are taxed here also, okay, so what will we do here, if it is not so, then you can use electronics comfortably, okay ji. I will not do anything to us, I will just go down and write this Saudi Syed in the mail where she used to write 'Mr Care of Yourself' Saudi Syed in the mail where she used to write 'Mr Care of Yourself' that I am feeling a little scared after looking at the dish and where she used to write 'Mohammad and where she used to write 'Mohammad and where she used to write 'Mohammad Directly Delhi', I will give it, ok of course. Directly Delhi', I will give it, ok of course. Directly Delhi', I will give it, ok of course. Beg Gulf - Mann ki baat raha hai, so Beg Gulf - Mann ki baat raha hai, so Beg Gulf - Mann ki baat raha hai, so what will I do? Been left minus one end. This one here, oh friend, there is one more thing, so one, we will go to the bus and now we will click here. Okay, so now I know above. I have taken out the finished roti properly. Left - I, Left - Bandh and BF - are taken out Left - I, Left - Bandh and BF - are taken out Left - I, Left - Bandh and BF - are taken out from the mind. Okay, yes, Right comments are taken out by Left and BJP. Okay, well, this is the situation. If you try to get upliftment taken out today, then here. Even if the laptop is Mexico, this left minus one of ours is also left - if the maximum of the mind is minus one of ours is also left - if the maximum of the mind is minus one of ours is also left - if the maximum of the mind is correct then also the importance of left minus one is right. Even the items are not completed brother, let's start some work, so this left minus one should come here and here also. I had written the article that whatever alarm I have set is correct carrier, here also I have written it on the left side, so BF - I have taken it out and this is on the left side, BF - I have taken it out and this is on the left side, BF - I have taken it out and this is on the left side, now we are a little ok, I am not so confident but Uttam can do satellite on it. Okay, so now there are no chances of making a mistake, so let's try it, let's apply a little bit, we have made it, the above ones are going on, we have also taken it out, okay, one more thing, I would like to tell you that keep this in mind because the negative will go in the mean cases. So and you also need to tell me this, let me say that if you have 10 elements in this array, 2398 1838 force one should not appear, even though you have some elements, something like this is fine, then when the first element in your array is While doing bar selection, it is as if you used to select four limits till the left side, by selecting me and total by selecting you did not mix something completely and when you made your buy two, then from buy two you used to send some elements to the left side, something like this in stitching, then I am telling you this. Mantra I want to say that possibly this can happen as long as the emperor comes towards one side then to pick this left message first limit negative energy in the bottom player means upper one if yours is big see this decide the field if I have extended the above address to you, so this will be a bit of a loss, considering that this pass is a bit big, there will be no escape and left miss element left, if you don't ask then it will be like this, see what I showed you Army. I give it like not A 12345 here you have in not visible you will have to loosen it a little more or if you want to do it like this then I will take it so that I always have something left, it is okay for the first time it will be locked and blessings from God. So you have this total, you have it from above, see this from here, there is so much hatred at the bottom, how late is it, Shruti Doubts 4 - 3 tt, it is fine now Shruti Doubts 4 - 3 tt, it is fine now Shruti Doubts 4 - 3 tt, it is fine now - without directly selecting a limit from the policeman, - without directly selecting a limit from the policeman, - without directly selecting a limit from the policeman, I completed the total. For this meaning, give a little time for a minute, don't rush, it is fun. Samakhya Mission 25. Look at this, the one above has commented more elements than the one below. Properly, it can be with you that the remix below has given that child a wave in this letter - If it is closed then either these conditions should - If it is closed then either these conditions should - If it is closed then either these conditions should also be opened properly or else I would say that you should ask for a small ray from above so that you will have to read and write more. You have this gym here which is above me. Hey, the answer will be small, there will be a fixed amount of elements so that this thing is always positive, but sometimes it can be found in negative, like this request has been made, now you have taken out the total elements, you have the one above the total element plus and the one below. 2 Total Element Se Aapke Hain Na Lo Hai Aapke Vivo Par Hi Hai Aapke Sample Is Apne Nikah To Aay Baitho A Good Hai Tu A Girl Aaf Nikala To Log Plus Hai Bay Tu Kitna Dayalu Free Three People From The Above Is This Electrolyte Upvore If there are 3 such flats then how many people will be selected from the bottom one, so that the number will be 125 5 - so that the number will be 125 5 - so that the number will be 125 5 - Two people will be selected from the bottom one in this basic soil, the left toe had come to the induction, at that time, do not panic, in such a situation, they should - Keep this in mind that yes, when the bell comes up, the they should - Keep this in mind that yes, when the bell comes up, the they should - Keep this in mind that yes, when the bell comes up, the real can be earned only to infinity or anything on the right side, but as if this question is not your balance, if what was there had turned out to be bigger than this, then a little bit of power sacrifice penance and matters will be imposed on you. Opposites were happening like now and for sure, sorry too, so for sure it is going to remain small, okay yes, but what, the condition of this becomes a little different, it does not mean that I have not made my own example because now we know. Firstly, the section which is always smaller than the bell, will approach from the left side. If you approach the qualification, then there is no problem because even if you approach like this, select admit in that one, they will keep it with you, isn't this situation ok? If you win, then talk to him about this only. So let's assume that whatever forwarding you are doing will come into it right now, but I will show you the real results of the test right now, what will I have to do, so that I do n't have to stitch your code a bit, I will just do this. Okay, yes, I will just do this. That's right, by doing this you guys will get a little bit of code stuck in that area. After a few weeks, it's true that once you see how much is going to come in the laptop, then it will be your property. Hi, how many total elements are going to be left to you? You don't have hotel element. Now, hi, your 1010 occupants, you have five, okay, so five people will be selected from the top one, it is correct, take this small one, multi-purpose, how many are there, get multi-purpose, how many are there, get multi-purpose, how many are there, get one free for ₹ 90, get ₹ 1 free, hi, where is mine? It free for ₹ 90, get ₹ 1 free, hi, where is mine? It free for ₹ 90, get ₹ 1 free, hi, where is mine? It should be Hi Mera 1968 Par Total Element I have 9 inches from here ok now let's come then take plus Hi Bittu in my mail for real me kya aayega link plus 125 - Power Begum Services Naadi mein 125 - Power Begum Services Naadi mein 125 - Power Begum Services Naadi mein four sets from top one from bottom Select one thing is closed, there was no problem here but value verification is not clicked, why were they not there, then it is definitely smaller than the bill, it is lying on the bell in the flight but it could have happened that the B Note was from F4. If it gets bigger, then you increase the celebration to the left side. In that scenario, now you work like this, from here, do it one more time, but if I show it to you, then when you people pick it up and put it on one Laxman, then here I come and fight. This time, if you take out your egg, how would it come Atlas-5 by two eight six, isn't it, and Atlas-5 by two eight six, isn't it, and Atlas-5 by two eight six, isn't it, and how much bell would have come when you would have come from lunch - do it how much bell would have come when you would have come from lunch - do it how much bell would have come when you would have come from lunch - do it 9 means the line is basically 5 - 6 - but then we succeed a little. is basically 5 - 6 - but then we succeed a little. is basically 5 - 6 - but then we succeed a little. It takes about this because here I have been chatting only with heroes and with length, there is nothing on the left or even this is my flat belly, when I reached the right spot, then I can tell you that it is not so. I am sure that it will not work, you will have to apply some more conditions in it, now I am only here because I want to say that there will be a little more limit in the previous one, you will be able to compare the second one with the edit, if I get such a ray, please. Quickly you know what it does and it just does it, then by cleaning the egg, it becomes ours, it becomes this and this, and now why do we suffer from diseases, because the ones above are fine, my Bani Sir will go on leave. Mine is working - it Sir will go on leave. Mine is working - it Sir will go on leave. Mine is working - it works only on the upper one and on the lower one, it never happens that the limits for selecting the remedies you have are also negative, this cannot happen, then okay, so here I am giving you a situation and She wanted to explain that now the final situation is that even though there is no other situation here, keep thinking about it and see that if the lunch of one becomes longer than the length of the other, then you will have to select so many elements like this. I used to go to some children, here also I am saying that your element is of objective type, so in that case you will get a little stuck because this big water Saraswat will be running with the main accused water and you will be successful here in this minute. I would like to say that if it is so, then we will insert this one also, we will clean both the laces, okay, so I will insert one of you in time, basically one of you and after that this one, I do n't know, this thing can be done. The water exam is done, I am giving the reference, I will just hand over the reference, I have started looking at different places, otherwise I will get this beamer inserted, wow, I will get that beamer inserted from the temple side, okay, now we will throw it out of this station, now we There is no fear of such a situation, this too will work fine, okay who is we will do all the conditions - we will do all the conditions - we will do all the conditions - after this I don't think it should get stuck in any dress, let's run it once and see the final, let's run it one more time. What are you saying? Okay, no problem, some symbols etc. are also showing some mistakes. After checking, quickly take line number-23 and quickly take line number-23 and quickly take line number-23 and in the public opinion, your result is Dots, Media and Internet Mill, Bollywood, this question is okay. Between the first or second thing that seems to be put here OK now is the time ok had happened ok valuable might not have been left birbal is saying mistake might not have been included a yes and here I am also left Have to do on chicken fish bill That the answer is looking good right now, let's submit it once quickly, have all these desks got 10 in it? Okay, all of them will discuss, okay so I know the video is a little number one. But the thing is, first of all the solution is a little tricky so it will take time in the intuition journey, after that the second thing is that even after getting the indication, there are many conditions which are difficult for women, right here you are finding out this. Yes, but you should check whether it is the case that many people at the top are selected and many people at the bottom are selected, that depends on the values because we will not know that at the top, we will be able to find out only after seeing the values. That's why I did these things so that we could see that if the eggs had reached the uppermost point, the extreme right hand side of the beautiful right hand side, there are infinity people present on one team and on the left side, send a reminder and send a message to him. After which, how should we discuss about it, after discussing about it in this kind of head, there are more elements in the house, chemical elements with fat, neither can we get stuck a little, we will only get the address and element selected and that too inside. More than this, your abstract jhal used to tell you this and was making the bell - jhal used to tell you this and was making the bell - jhal used to tell you this and was making the bell - because five people had to do tilak on themselves, so it cannot be shared from above and ours like this, so for this reason I wrote one more thing. Here, by the final key, there will be no less elements in the one above me, according to which this is how because the left side is never negative and we will be able to get our proper celebration in each task. What you want this is that you people should meditate on this. After spending a little time, I gave the same amount of time to my video. By doing Velvet Day, the coins are much more. Okay, and the juice that we have extracted, the even length and length of the Accept Example, after writing the Real Example, how can I use the real name? How to run all the tests by using your own or cord? The mind of the computer can think about the test, so this year there is a cord on the test case. Okay, after that you write your entire test. So come on, you must have liked its solution, in the next video. See you with the next question. If you like the solution then please click to subscribe the channel. Okay, happy jhal.
|
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 |
49 |
okay guys let's solve 49 which is group anagrams it's one of my favorite problems so we're given an array of strings and we want to group The anagrams together and you can return that answer in any order so we have strings is a list of various strings and we want to return a list of strings where each inner list is all of the words that are anagrams so t e and eight are all going to be over here because they are anagrams of each other bat did not have any anagrams so it's on its own and tan and n are also in here because they are anagrams of each other and they give you a stupid Edge case that doesn't really matter if you have a list of just the empty string that is going to be a list of the empty string now there's a lot of rabbit holes you could go down but one of the first paths we could think of is sorting all the words so if we sort Nat we get a then n then T if we sort tan we get the same thing therefore these are anagrams of each other e is going to turn into a and eight will also be a they are also equal to each other and therefore those are anagrams and these are anagrams although there's kind of multiple problems with this one is that it's very slow because if you had n many words where n is four here and if you had M which is the length of we'll say the average word b n * you have to sort each average word b n * you have to sort each average word b n * you have to sort each word which is n * m log M so that's word which is n * m log M so that's word which is n * m log M so that's actually pretty slow we're probably going to have n * m because that means going to have n * m because that means going to have n * m because that means all the characters but we'd at least like this part to be m not M log M so what we'll do instead is get the frequency count of each of the words so here if we call this dictionary f we'll have n one of those a will have one of those and we'll have t we'll have one of those as well if we were to calculate that for Tan that is going to be the same dictionary dictionaries don't really have an order so it doesn't matter what the order of the keys are but they're going to have the same keys and the values or the amount of letters we have are going to be the same so instead of using that the sorted versions are the same what we're going to use instead is that we'll calculate the frequency dictionary for both of those things we'll call it f for natat and we call it g for Tan well they're going to be the same thing they'll have the same keys and the same values and since they are equal to each other that means they are anagrams Now by grouping things we mean we want them to share a common key really because if these both have the same key pretending that this dictionary itself is a key we'll just call it say a for now and this is B well all of the things that have a or that frequency dictionary we could make a list of that stuff so well Nat would have you know this dictionary and we could also have Tan in there as well and we'd also automatically group well all the dictionaries that are like B well those are going to be together so we'll have the eats we'll have the eights and anything else however the problem with this is that you can't use a dictionary as a key that doesn't work because dictionaries are what we call mutable they are mutable meaning they are not hashable a dictionary's key must be what we call immutable so we can't modify the memory therefore it would be hashable so what we do instead of the dictionary is we'll make an array of the 26 English letters so of 0 1 2 3 all the way up until index 25 so there's 26 characters we'll initialize this to be zero cuz we're going to get the count of all the letters and then we'll just say hey n well we'll figure out that index it's around like 17 or something and so we'll add one to that count so we have you know there's one n for a well we'll add one to this there is going to be one a for T we would add that in there as well and then we have this array well that doesn't help either because arrays are also mutable but as soon as you make it a topple which you can do very easily you simply just call topple on this array once you have that as a tupple it is immutable and that's why they exist in the language so then after we have this key which is our tupple anything with this common key we're going to make it either you know the first element of this list if it's the first one otherwise we'll just append to this list saying there's another anagram of this type and that way it sorts the grouping automatically for us because then you can simply just return the list of the dictionaries values you would just need to return the list of stuff you have so for our code this is actually a great time to use what's called a default dict so from collections we will import default dict and if you haven't used that well I'll show you and they're really cool so we're going to get our basically our return thing but it's going to be our dictionary where we do the grouping anagrams dict is equal to a default dict which takes a list so we'll use that in a moment but we'll say for each s in the strings so we're going to go through each of the strings we're going to build up this count array which is starting at a list of 26 zeros so we have the list of 0 * 26 we go through each of the of 0 * 26 we go through each of the of 0 * 26 we go through each of the characters in s the string we're looking at and we'll set count at the or of C minus the or of the lowercase a and we can set that to go up by one what we're trying to do is associate the character with the index and so lowercase a should have an index of zero because or gives the asky value for the character and here it is actually just the value of 97 if the character is lower case a well that would be 97 - 97 which equals 0 if that would be 97 - 97 which equals 0 if that would be 97 - 97 which equals 0 if the character we're looking at was B that would be 98 - 97 which is equal to that would be 98 - 97 which is equal to that would be 98 - 97 which is equal to 1 so it just automatically gets the index corresponding to the letter so we're going to bump that count up by one saying that we saw one more of that character and we can get our key which is equal to I'll make it hashable or IM mble so a key is a tuple of the count and we'll set anagrams dick at the key and we can immediately append s so what this does is well we haven't checked if the key is in the dictionary yet but with a default dict we don't need to we set anagrams dict at the key if that key wasn't already in the dictionary it would immediately put it in the dictionary and Associate its value with just an empty list of one of these it immediately makes that key with the empty list if it wasn't already there otherwise if it was there we already had a list of a word so we just append the new string to that existent list and then after that we just simply need to get all of the dictionaries values together because each dictionary value is a list of words and we can actually simply return the anagrams dict Dov values because that's exactly what it would do it would return an iterable of each of those values sorry I seem to have brackets there that's not quite right if we run that we are going to see our solution works and if we were to submit that would work as well so the time complexity of this while this is constant we make a dictionary we go through each of the strings so we're going to say that's n so n many strings this is going to be an n in here and so we make a new count array this is a big constant of 26 but it's still a constant so no worries we go through each of the characters in The String we're looking at and if we were to say the maximum string length was say m so far we're at in n * m we go through each of the in n * m we go through each of the in n * m we go through each of the characters and we update the count this is constant making this into a tupple is simply going to take you know 26 times and we return the values which is not going to be definitely more than n * m going to be definitely more than n * m going to be definitely more than n * m so for the space complexity we would have well our anagrams dict is going to take up a lot of space and so we have well we're storing 26 things as the key and the value of it is going to be a list of strings so we're basically again storing all of the characters and so that would be n * m as well otherwise that would be n * m as well otherwise that would be n * m as well otherwise known as the number of characters we have total I hope this was helpful and have a great day guys
|
Group Anagrams
|
group-anagrams
|
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
| null |
Hash Table,String,Sorting
|
Medium
|
242,249
|
1,814 |
Hello, how are you? Well, we're going to do an l code today instead of doing the next linear one, we're going to try to get in there and start maintaining a streak of doing the problem of the day. Let's see how long we can keep it up. I 'm not very good. to maintain streaks 'm not very good. to maintain streaks 'm not very good. to maintain streaks Unfortunately But well let's do today for a change and this problem says that given a king of positive numbers we are going to have to look for eh And if we define a reverse function what it does is put the number back to front We have to look for a pair of indices that satisfy these two conditions but that one index is greater than the other. This I guess is so that we don't count it double, right ? And the other thing is that the number plus the ? And the other thing is that the number plus the ? And the other thing is that the number plus the inverse of the other number has to be equal to the other number plus the reverse of the first number we must answer the pairs the number of pairs of indices how can it be too much to apply this formula so here they give us a case 117 so one plus the reverse of the other is equal to the other plus the reverse of the first well the way to do this exercise there is already a trivial way that is quite evident which is to grab and throw everything out the reverse you can perhaps have the results to calculate it so many times and do the math each time O It's going to be n squared and it doesn't make much sense to do it but we're going to try one an idea another implementation idea that I think could be eh Let's see if we can do it In linear time when I see this here I'm going to go to the ID let's go Let's copy this here, create our nuo by doing html in and what interests me is this formula that I think we can find an optimization for, I leave it here for reference. I mean, we know that for it to be fulfilled, this good thing is basically solving an equation, we can't grab and put a number we are going to put we pass this down here this I am going to pass here by subtracting It should be equal to the number to the second number j and I am going to pass this by subtracting and this equality should be maintained So what am I going to do I am going to calculate For each number, the number minus the reverse is going to be saved on a map. In reality, I would be interested in leaving it because I am going to have it repeated, so let's see if we can put it here. If I have all these numbers, no. So for each one, 12 For each of these I am going to do the number minus the inverse and I am going to save it in a set and for the East set So I am going to have 12 here I am going to have saved 12 - 21 which 12 here I am going to have saved 12 - 21 which 12 here I am going to have saved 12 - 21 which is going to be a number minus 9 and I'm going to save What happens is that I can have another number that also gives me 9 So what am I going to do than save them in a map so I'm going to have the map here in one menu once and if I have another result I 'm going to grab it and I'm going to increment here the 'm going to grab it and I'm going to increment here the 'm going to grab it and I'm going to increment here the frequency every time it is núo appeared to me. Then for each time it appears I am going to determine if this number already exists in the map with that index with that with is here I am going to grab the number of values it I am going to grab the number of values it I am going to grab the number of values it has and I am going to add it. Add to the amount of the total running, let's say the total, and do the same thing like this with the next one, with each one, then we would be iterating the input elements only once. Let's see, let's implement this and see if it works well. Ah, we have to apply the module. I'm going to leave a comment later because I forgot This is just like that but good to have a minimum of decor eh well then let's start let's go through the network first we can start Decorating go creating the map I could make a bar this but I'll put it to To make it clearer, I know one who is newer to this. So let's do the function. How annoying is it to do this? How do we do it? Well, I'm going to do it for a while now and I don't know the most optimal way, but hey, let's use it. I'll make the suggestion. We don't see how. so here we have the on the map we are going to put the number minus the reverse dir and I am not going to directly but I am going to use by because I want this to accumulate if I do not know highly recommended instead of computing the value and seeing if it is added or not the add list I can directly put integ zoom here and this takes me the frequency e and the first thing I have to do before adding it is let's define the r they scared me with that there could be so many results that could be returned let's go to declare a long this is going to be the accumulated amount of results that there are and this is what we are going to return here after formatting module 10 to 9 no I don't know why they honestly know and what we are missing here Sorry a little messy I That's it: little messy I That's it: little messy I That's it: Check if the map contains Let's see, let's grab the elements that it already has and add them to the total that we have accumulated and add it to the collection and let's see if this makes sense or not I think it could be It's going to work, let's try it. This era was deuta media. It wasn't easy. I probably prefer it. Yes, well, it seems like this and what's wrong is actually the module of all of this. It's a parenthetical issue. It's the I have to make a module of all of this. together No, not that separated and I'm good at things let's upload it Ah well it's more It's accepted well it's a little behind but well maybe this part that I'm doing here of the Stream builder and everything is not too performant but well it's the way to solve it What I found, at least if you find a better one, tell me later, I'll upload all the code, thank you. I hope you liked it. I'll see you in the next one. I was curious if this solution wasn't so good because of having to do it the way it was. This is doing this inversion of the order of the numbers So I'm going to try with an alternative function that Ah I saw that I had made one that gave this one a superb result. It's going to see if it improves. Well, with that it goes down almost by half and remains between the more or less normal values so well that part I probably normal values so well that part I probably normal values so well that part I probably saw was not very fine but it seems to me that it would be better
|
Count Nice Pairs in an Array
|
jump-game-vi
|
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`
Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[42,11,1,97\]
**Output:** 2
**Explanation:** The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
**Example 2:**
**Input:** nums = \[13,10,35,24,76\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Medium
|
239,2001
|
572 |
welcome back to uncle Jess today's question is Luke code 572 subtree of another tree we're given a tree and we're given a sub tree and we need to work out whether this sub tree can be found within this tree now this question is very similar to the code 100 same tree which I've made a video for now if you want to go check that out before trying this question then go ahead and do so the trick here is each position within this tree we need to check for this subtree so we're going to have two recursive functions one is going to check whether this is the same sub tree so we'll check say at the root here we'll check three four and five to see whether this is the same and one is going to recursively go through each of these nodes and so let's drill down into it right so how can we check to see whether this sub tree for example is the same as this and this is where we'd be using the solution to leak code 100 same tree firstly we need to check the roots right if they are different so if Val 1 doesn't equal R2 then this will return false like in this case or if one of them is equal to null so say we were compound four and one with four one and two well the right child of four is null and this is equal to two so if one of them is equal to null then we can return false and lastly in the most simple case if both of them are equal to null then we can return true so if both Val 1 bulb two then we can return true so these are all the base cases that we need and these base cases will be checked within each recursive call so firstly they'll be checked at the root level we can clearly see that value one doesn't equal value two so we return false from this then we move down the left side and the right side we carry out the same function from this starting point so 4 is equal to four great we recursed down the left side the right side and we can see that the left side and the right side are both equal to each other then obviously it goes down to nulls the values are both equal to null so we can return true from this so this sub tree right here is going to return true we also need to check the right subtree so the right five we can clearly see that the first node doesn't equal the node in the subtrue we're comparing to so from this we return false now this is a really important point when we return the values we need to return whether the left subtree or the right sub tree returns true so we return true or false so as long as one of these subtrees returns true we're going to return true from this and time complexity for this one is going to be of M times n because for every node within this tree we're going to check whether it matches the sub tree so it will be M times n where m is the number of nodes within this sub tree and N is the number of nodes within this tree and then space is going to be M plus n so let's code this out so for each node in the tree we have to run an is same function to see whether at this node within the tree if it's equal to the subtree so if we take root one and root 2. it's root one and root two are both equal to null we know that we found a match so we can return true if root 1 is equal to null or root 2 is equal to null or root one vowel doesn't equal root 2 Val then that isn't a match so we can return false and then we need to recurse down the left subtree and the right sub tree so we're going to return is same passing in root 1 dot left root 2 dot left and is same passing in root one dot right and root two dot right so both of these need to return true in order for the subtree to be the exact same then we need another function to go through each node within the main tree and recursively call from each node to check whether this subtree is the same so if we call this DFS we pass in node when we call it we're going to return it so DFS pattern the root to the main tree if the node is equal to null we can return false then we need to call the is same passing in the node and the subroot and if this returns true then we have found a match so we can return true from this DFS function and what we said in the solution run through is we need to return whether the left subtree or the right subtree returns true so if one of these subtrees returns true then we know that this tree has a sub tree that is equal to the sub root and that's it submit it and there you go don't forget to like comment subscribe it really helps out with the channel and I'll see you in the next one
|
Subtree of Another Tree
|
subtree-of-another-tree
|
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise.
A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself.
**Example 1:**
**Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\]
**Output:** true
**Example 2:**
**Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the `root` tree is in the range `[1, 2000]`.
* The number of nodes in the `subRoot` tree is in the range `[1, 1000]`.
* `-104 <= root.val <= 104`
* `-104 <= subRoot.val <= 104`
|
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be:
isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
|
Tree,Depth-First Search,String Matching,Binary Tree,Hash Function
|
Easy
|
250,508
|
368 |
hey everyone today we'll be solving Le problem number 368 largest divisible subset in this problem we are given a set of distinct positive integer nums and we have to return the largest subset answer such that every pair answer I answer J of elements in the subset satisfying these two condition either the answer is divisible by J our answer J is by answer I and there can be multiple solution we have to return any one of them okay now let's try to understand what the problem statement is saying uh using this example here first of all we will be given an nums of distinct positive integers it is a set so having a distinct element so from this nums what we have to do is we have to figure out a subset that should be largest and that subset should be following these condition that every pair in that subset every pair is going to so satisfy this condition let's say the pair is a and b so either the B is divisible by a or a is divisible by B so AI AJ either the a AI mod AJ is equal to Z or AJ mod AI is equal to Z so if this is the case that subset is a valid and we have to choose the largest subset that is possible so if I try to get all the subset of 1 3 it should be 1 2 or you can say 1 3 1 2 3 or if I considering uh one element also so it would be 1 2 3 and the empty set okay now we have taken all the subsets possible here there will be 2 three as well so here what we have to do is we have to get the largest sub such that every pair is following this condition so first of all let's take the largest one because if that is the that is our answer we are going to stop the checking so 1 2 3 let's say 1 2 3 here the pairs are 1A 2 2A 3 or 3A 1 so here whether 1 two is a valid pair or not yeah 1 can divide two because we have to choose any one of these two condition yeah one can divide two that is a valid pair two cannot divide three it is not a valid pair 1 can divide three yeah it is also a valid pair so as all the pairs are not valid so 1 2 3 is also not valid so we will not consider 1 2 3 now comes to the subset of size 2 1 3 1 2 3 here 2 3 in 2 3 is not divisible by 2 so it is also not valid this is also not valid 1 and 2 we'll check for 1 2 and 13 is are these two valid yeah definitely L because one can divide two and one can divide three as well so this is our answer either you return 1 two or either you return 13 the one size one length uh one length subset we don't need to check because we have a two length answer so it its answer can be 1A 2 or you can say 1A 3 anyone you can return this is our problem statement and these are the constraints given to us all the in are unique and the range is like this and this question has been asked in Amazon Microsoft Adobe Apple Bloomberg so it's pretty important question okay now let's have a look on the on this approach what we did here what we did is captured all the subset to power n time and for every subset we check this condition on every pair if we are getting every pair that should be n sare and checking this condition is order of one so this is going to be the time if we are going with the Brute Force but we cannot afford this time we have to think in a better way so we had 1 2 3 as our nums first of all we have to do check this condition on every pair that array of I is divisible by AR of J or ar of J is by ar of I if we have to reduce this statement to one like one condition so in that case it should be uh the case where a AI is less than AJ that is the previous element is less than smaller than the later element so to have to make that what we have to do is we will be sorting our nums so if we are sorting our nums in this way now we have to like find the subset of largest subate of largest length where um array of I let's say I is a bigger Loop array of J equal to zero J is the smaller Loop inside I now like how do we do this so here we will be thinking in terms of dynamic programming considering the smaller example first so one let's say if the nums is having this element one element do we have to do anything yeah no one will be our subset and one will be our answer in this case so if it is having two elements only one and two so for one we already know the answer that this one is the answer this answer is specifying that the biggest answer biggest subset we can get that is ending with one so for two what we need is we have to see what is the biggest subset that is ending with two if it is ending with two so we will be checking what are all the elements before two that are dividing two before two there is one element which is one is dividing two it means the elements the subset ending at one will also be the part of that subset because if one is dividing two it means all the elements in this subset are dividing one and all the sub all the elements in this subset are dividing one and one is dividing two it means all the subset in this uh answer is dividing two so we can take this subset and put it here and add two as well so 1 and two will be the answer or if I take we have given 1 2 3 we know the answer of one largest subra ending at 1 is one and largest subset ending at two is checking from left to right what are all the elements dividing two one is dividing two so we are picking this subset and putting it here and after that adding two so this is the subset where every pair is following our satisfying our condition 1 is dividing by two yeah satisfying condition now let's come to three here what we have to do is we have to see for the like for all the elements which are dividing three so from left to right we will check for all the elements whether one is dividing three if one is dividing three all the pairs all the items in this subset is dividing three so we can pick this subset putting it here and then adding three as well this subset is going to satisfy our condition now we have all the answers or all the subsets valid subset ending at I index and we can among these we can capture the maximum subset so the maximum subsets are these two so return any of these I hope this approach is clear to you this is a dynamic programming approach this is the same logic we are uh using to find longest increase in subsequence that uh we have to find the longest increase subsequence ending at one then longest increase in subsequence ending at two the same kind of loing is applying here so let's uh work on a bigger example so that will be more clear to us let's say we have this 2 3 4 9 8 this is our array and let's say I is equal to Z in the starting so for I equal to 0 first of all we will see what are all the subsets before I there is no subset the empty subset is there it means two is the only element that will be added to that subset because in this two subset every two elements are dividing each it has it is having one element only so that uh that mean it's already falling satisfying the condition now we know the answer ending at two and like all the subsets and ending at two now we have to see what are all the subsets that can be our answer and ending at three for that we have to look on the smaller problem first these are the smaller problems and we'll see whether there is any element which is dividing three or not no none of the element is dividing three and before that make sure that this array is sorted because we are our we are building our algorithm as per the condition that this array is sorted so if it is not sorted do the Sorting arrays do sort nums sorting in the increasing order so once it is sorted in the increasing order it will be like this 2 3 4 8 9 this is our first step this is our second step we are using two Loops two nested Loops one for I and one for J okay now let's come to the point here we need answer where which is answer of the answer with subsets ending at three so before three know no element is dividing three it means there is no valid subset or pre-existing in the three it will be or pre-existing in the three it will be or pre-existing in the three it will be the only element it means for 2 and three the valid answer is three now what we'll do is we will check for our candidate subset which is ending at four so we will again try from left to right and we'll see what are the element dividing four 2 is dividing four right it means all the elements in this subset will be dividing four so we can directly take this subset and then addit four as well so 2 and four will be the two elements ending at four so if our array was 2 3 4 our biggest answer biggest possible subset could be 2 and 4 now we comes to eight we will check for the elements from left to right again which are dividing 8 so 2 is dividing 8 right it means all the elements in this subset will be taken to here so if we take here and then add it yeah right now again we see that at four the elements are we will just take two for now at four the elements are two and previously we have captured the elements one it means two are bigger than one so we will be considering this subset discarding this one so we consider this subset so from all of these smaller elements we consider two and four it means two and four are the elements which will be dividing eight so if I add eight here it will become 2 48 that is this is the subset that is our that can be our candidate and we can return the subset from the problem now we check for all the elements all the subset ending at 9 we will see what are all the elements which are dividing 9 so three is only element dividing 9 it means we can have only this as a valid option three after that we can add nine so ultimately it will be 39 nothing else so now we have captured all the subsets ending at a specific position and here if we see that this is the last the largest one so we can directly return this one here in the Lis we were just storing the length of the largest increasing subsequence the basic L problem here what I can do is this is a list and in every list I am storing a list so the data structure here used we what we can use is list of list you can call it anything or you can call it DP as well so here in this list whatever list is having the longest list that is our answer so 2 4 8 is specific uh is following our condition here 2 4 is a valid pair 48 is a valid pair and 28 is also a valid pair so we will return 2 48 from here okay now let's try to code this problem and what is the time and space complexity of this approach the time for this approach is that we are maintaining this uh list 2 3 4 8 9 and for every index I'm iterating all the smaller index so it will become order of n square and what is the space complexity space is also going to be the same at every position we are storing a list and that list can go up to n size so it will be of order of n Square so it's way better than the previous approach which in which we were uh extracting all the subsets now let's try to code this out first of all we have to sort our nums array arrays do sort nums let's capture the length of this nums do length now we be iterating over this nums array before that let's take our DP array list of integer DP is equal to new array list okay that is fine I we also have to initialize this list for I = to 0 I less than n i ++ the same for I = to 0 I less than n i ++ the same for I = to 0 I less than n i ++ the same number of uh list we I will be adding uh the same as the number of element in the nums array so DP do add new array list okay now DP array is prepared I will be iterating over our main loop I equal to0 I less than n i ++ for every ith element I will be ++ for every ith element I will be ++ for every ith element I will be checking all the smaller element to it so for that int J equal to Z J less than I and j++ so for every smaller element I will j++ so for every smaller element I will j++ so for every smaller element I will capture the subset we have captured so far maximum subset we have captured so far so to capture the maximum subset I will take another list integer do integer list of integer maximum subset equal to new ARR list okay so if there is no subset in it in that case it will be considered as a empty subset so now for every Jal to 0 to J less than I we will see if nums of I divided by nums of J is equal to zero and the other thing is that our maximum subset is having a size smaller than the current subset maximum subset do size is less than the dp. get J do size if that is the case we have a new uh candidate which of bigger size if you get a new candidate we'll be updating your maximum subset equal to DP dot get J okay got it now here using this Loop we have captured our subset so far and now what we will be what we'll be doing is let me tell you like using an example let's say for 1 2 3 we are at two and we our maximum subset capture so far is one so first of all we will be adding one and then we will be adding two to our new subset so maximum not the maximum sub d DP or do get I right so first of all add all from Maximum subset DP do c i now add nums of I okay now all the elements are captured and here our main logic is done now what we have to do if we if you keep on doing this ultimately you have to make one more iteration to capture the maximum subset so instead of cap doing one more iteration just capture here along with the loop because we have captured DP of I only once and we are not changing that so we will see uh for that we can take two variables int answer do length answer length let's say it is zero and answer index let's say it is minus one you can initialize with it with any values any smaller values so if answer do length is less than DP do Getti do size so we have found a bigger subset it means we are going to capture that so answer length is equal to DP do get I do size and answer index is equal to I so ultimately this answer index is going to store the index of largest sub array so for that I'm going to return answer idx sorry DP dot get answer idx okay now our coding is done try to submit over sample test cases okay it is working fine I'm submitting the problem it submitted successfully hope you understood the problem thank you guys if you have any doubt you can comment down below
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
1,203 |
hey everybody this is Larry this is day 19. is it now I lied day 20 of the league code daily challenge hit the like button hit the Subscribe button drop in this card let me know what you think about this poem uh just a quick minor update um uh yeah the tailbone the contest earlier today uh for me it's earlier today even though I did sleep and take a nap in between so hopefully that makes things a little bit better so we'll see how this goes today's problem is 1203 sort items by groups respecting dependency I don't know if I remember this one but the this thing seems uh familiar now remember this was very hard during the contest back then but nowadays I feel like people are way more practice uh problem number 1203 was a long time ago maybe it was a similar Farm I don't know maybe it was a VC I don't remember anymore all right let's take a look uh all right so you have n items belonging to zero M groups okay and where groups to buy is the group that okay yeah that makes sense and negative one if it has no group the items and the groups are zero index the group can have no items belong to it okay return a sorted list of the items such that the item that belongs to the same groups are next to each other and assorted this there are some relations between these item where uh between before item is an item containing order items that should come before I've item in the sorted list okay so the dependency list is um it's item based not group based I have to sometimes I get confused I feel like one thing and I'll let me know in the comments if you've been doing this or you do this sometimes because I feel like recently I've been okay on the algorithms you know maybe a little bit whatever but reading has been kind of been terrible too uh like I don't know like I just read a poem and then I do it and then it turns out that I was doing the wrong problem or something you know and that's been kind of affecting my uh my just like competition I don't know I mean I don't care that much about the rating per se but you know as a competitor you know you want to still want to do you know as you can so anyway uh all right so let's take a look at an example what's the N and M again uh so we have n items and shg is the number of groups all right and then okay so you have oh yeah they don't use a zipping but what's before item before itemized that should come before I so that's one should be six okay um so I mean all the groups have to be the same so this is very weird I think but oh like I don't see the reason of groups or whatever is there uh not possible or empty list if there's no solution okay so yeah so basically I think the confusion that I have right now is and I don't know maybe I feel like recently I've been kind of doing this where I doubt myself too much which is that uh I think I look into the question a little bit too much of asking why it's like why is this why are they phrasing it like this it doesn't make any sense but I don't know I guess it is what it is instead of accepting and just kind of go into it um it's something that I don't know and I apologize if I'm talking too much about myself um but I hope that it is uh Illuminating and at least some other dimension if not this particular form in that this is how I get or I try to push myself to be better I don't know if I you know a small incremental step by step but part of being better is kind of identifying what your what Your weaknesses are what you haven't been doing so well and try to um consciously improve on them right um and at least On My Level and this is not meant to be I'll move back it's just me right it's uh you know like when you're starting out when you're beginning obviously it's quite called DC to identify because you're like oh I have to be better at binary search I have to be better at uh sorting or you know other stuff but at a certain point you're like okay well I'm solid in these things so that means you know there's this kind of abstract Concepts that you still have to be better at either it is writing better code and by better I don't even mean complexity but just could be me it could mean either uh more precise um correct precise being correct the first time and then there's like speed and then there's even just like writing tighter code right because the less code that you write for a given problem the faster that you can write it and in theory the fewer um places where you can have typos and debugging and so forth um to a degree obviously you don't want to go off the whole thing but uh but yeah so for me I'm just also trying to you know I'm thinking out loud how to identify these kind of roadblocks if you will and try to improve on them a little bit so yeah so for me I for me the little confusion that I have with this particular Plum instead of just maybe accepting it is wondering why they're in separate groups at all because there's no reason that anything should be in different groups um so that's a little bit weird but yeah but that's fine then right so then now maybe we're gonna say uh um don't you think that's a little bit tricky is the negative one groups I guess if you have a before and a negative one so you can't just do it before in the group um I think the two ways to handle it implementation wise I mean ideal wise is fine right this is just gonna be a top logical saw it uh I should have said that a little bit quicker and earlier I it was in my head but I just I think I got a little sidetracked but yeah this is going to be top logical sword when you have basically items or whatever it is and you have some prerequisite before doing them and trying to sort them in some order based on that dependency um as that's how I kind of phrase it in my head obviously the uh the lingo or the vocabulary can differ depend on how you want to phrase it but yeah for me I think like the two basic ways that I would think about implementing and speaking of implementation one is kind of separating out with special Logic on the groups and the individual items meaning groups of negative one and so forth um but for me it's probably it feels easier to just um to just create random groups that doesn't do anything is what I was going to say meaning that like for I'm looking at this example one you could say the item zero instead of group negative one it could be group I don't know a thousand and one or something right um and I think that should be good because you just treat it as a group of one member so yeah um okay so yeah so now we can do something like for index uh a group a g for group and then maybe b i for before items in enumerate uh a sip of the group and the before items right and basically we want to put something like um how do we want to phrase it all this is actually pretty straightforward in terms of if you understand topological soil so maybe about group groups as in the group members as a list because they have to be next to each other anyway so you can treat them as one and then the other thing is I guess maybe four items in a group setting instead of uh so group before or something like this um but this is I guess these are items so maybe we have to kind of um no I think we're okay it's just I think this is okay it's just that it makes certain things a little bit confusing to debug but it should be okay so yeah so this is also collections that default detective list and here I think it's easy to kind of do it this way but it's kind of easy to use if statements but I'm gonna use a helper function and maybe a cached helper function um I'm not going to go over uh memoization this far this is not even that necessary to be honest but I just feel like uh I just feel like this would be nice I don't know I mean is that a title just using it you know creating in a way it doesn't really matter right so yeah so basically get group of uh the item X I guess yeah and then basically if group of I'm just checking to see if zero based or one base I mean I think it's disabled based right or zero indexed okay yeah if this is you go to negative one then we just return a new number which is G uh yeah um yeah because G is the biggest number in the group or bigger than the biggest number in the group so then we return this but then in command uh we have to also do not local otherwise we just return group of X and that should be good enough for us to handle and basically now we just have to set up the uh the graph and this is very standard topological sort uh but I always forget so basically if so that I'm trying to figure out which degree is which um so the big one before after now I actually want to start after actually um and then we want to do group degree degrees or degree and this is just a counter but sometimes I do this in the wrong order so I'm just trying to think for it but now uh we can do G we append index uh and this is wrong actually whoops uh G is the group hmm oh I see I guess I can just to get group of index um and that will look at group sub X which is actually G so we don't use this directly so that's why I was a little confused I guess we don't actually need it right so we get the index we append it to the groups and now um the number of so group degree is actually like almost another way of phrasing at given though I'm using topological soil or graph whether X or vocabulary this can actually just be grouped um free wax I guess right like basically yeah I'll go over that in a sec and now for item in bi and before item then what am I doing so that means that the get group of this item is so this is before so Group after of here is reappended with get group of index so we still do everything in group and group pre-work of get group of index we group pre-work of get group of index we group pre-work of get group of index we Implement by one right uh this should be okay but I'm just double checking um I think one thing that oh not double checking but I'm thinking for a scenario which I'll kind of explain a little bit it's not a big deal but these are kind of very minor things that goes through my head when I'm implementing stuff like this uh and just things to look out for right because one thing that I was thinking of oh then you know and this that's pretty much the setup and then the next thing that I might do would be says for key and group pre-work or something like that keys and pre-work or something like that keys and pre-work or something like that keys and then something like if group of pre-whack that key or a sub key is equal pre-whack that key or a sub key is equal pre-whack that key or a sub key is equal to zero meaning basically this is the pre-work uh or topological sword pre-work uh or topological sword pre-work uh or topological sword algorithm right I mean there are two ways to do it I'm doing it with um uh breakfast search or with a queue um it's not breakfast it's just a secure but I'm doing the cube based topological sort and this is the way that I would look it up and that's what I was thinking in my head but of course this would actually never pass because in this case um the default is zero so if it's zero then the key doesn't exist because we only um only increase it by uh we only create a key of it the item has a value of one or greater basically so this would actually never be true and that's what I was just thinking for so that and of course the alternate way of writing is just you know writing it uh for right and remember this is the new G and my new G I mean this is after the groups I've been at it so it should have all the groups uh hopefully anyway uh yeah and then basically if group and in that well I guess this could actually happen just in a way but it's fine I suppose I don't have to worry about it that much yeah if this is equal to zero then now uh we have a Q you can invoke I as the group right uh yeah and this group is the group ID so just want to make sure that's true uh yeah and then now this is regular topological sort so yeah I'm just gonna bang that out uh we also have an answer thing um so cute that Pablo this is the current group ID that we care about and basically when we pop it we put it as the answer so answer dot a pen uh groups of G and this is actually an extent because you wanna basically add all the elements in groups sub g into extent and the order within the same group doesn't matter because by definition they're next to each other anyway so I guess because of the order that we insert them it should be in sorted order but that's just a side effects side effect yeah and then now basically for new G or next G maybe in group after of G uh then here we document the group because now one of the prerequisite is done so that's why we kind of do this way and then now if this prereq is equal to zero then now we can actually append this thing and then at the end we just return answer and we should be good except for if it's not possible I suppose right so yeah so basically if length of answer is equal to n then we return answer otherwise we return to the empty because it's not possible because we didn't take all the classes so I say classes because I'm still I always think about course like uh like um course description type thing uh okay did I do let me know right wrong way well apparently it's just not always sunny uh what did I do well hmm that'll be funny if I just kind of uh misunderstood and maybe before come before that no that's how I interpret it I think yeah that's how I interpret it because sometimes I get to directions wrong but all right let's take a look then is it the pausing but yeah this is the debugging part of it you know it happens to the best of us or at least me feel free to fast forward apparently people don't know that you can fast forward and leave comments about adding this point out but you know this is the live portion this is I want you to see that I'm struggling this is intentional because you know uh if you want to see a perfect explanation video or an explanation video of someone just pretending they know everything uh from the get-go then know everything uh from the get-go then know everything uh from the get-go then watch another video anyway uh yeah so group two at zero that sounds very good three is one I don't know uh yeah actually that's right group one is two and five this seems okay so what am I doing wrong so two this is definitely okay did I do the order one hmm that's very weird actually wow did I add this in the wrong thing hmm did I do I correctly do it in anything um oh I guess this should be a set I think that is a mistake that I made because uh yeah so this should be a set but because if it's not a set then this increments multiple times so I think it should actually delete multiple times if it's not a set so I think that still should be good but we're still having some issue of me being silly but that still should one thing at least right so zero having zero is not good did I misread some parts of the problem with group 0 3 and 4 oh I did make a mistake hmm okay so I definitely made a mistake here on assumption so let me reset this for a little bit um and I like I said in the beginning well I mean this one is an algorithmic mistake because I assume that you can group them together but within the same group their dependency is why um so this is why this depends on itself um but I mean this part is not that bad it's just that for you to group up to process it differently that's all uh yeah and that if we have to do some modification but the idea is that yeah when we process each group we basically do a top letter A topological sword within each group so we have to process the edges a little bit differently I actually didn't realize this case though it is an example um so actually algorithmically I think the overarching algorithm we're okay but uh overarching algorithm is okay and there's even the structure is okay but this is I don't even know if this is an edge case when this is example one but uh but we definitely have to handle it so okay um so this is so we have to do something like so we only do this part if they're not in the same group if they are in the same group then we have to um so we have to do something like uh I mean we just do the same thing really item after is we go to cook and item pre-work and then here then because they're in the same group then item after uh item we add index yeah and this is not the good version you have to be careful and then why do I even like uh yeah is oh yeah and that's basically it with the setup and then instead of just lazy extending because I thought that you could just put them all group together uh we can yeah but before that I mean I know this is gonna be wrong but I want to because before we have the wrong answer because it was not processing this part correctly but I just want to see that uh basically this if statement should allow us to process it correctly even if within the same group we or not correct so that's why I wanted one real quick and then see okay yeah so now uh it's wrong because six has to be before three or whatever but at least it's processing the groups correctly so that's how I know that I'm making good progress and also the other thing is if it is not showing up as what I expected um then I can fix it now before kind of by giving more code and make things even more complicated right so yeah okay so this point now instead of just extending we now um process this group right so yeah ah man this is kind of messy isn't it I'm trying to think what's the best way to write this code instead of just like writing even more but yeah okay fine I just write IQ for item Q uh okay fine uh for I and range uh um but for I and uh what's it called groups of G right so for each item here if item pre-work of I is equal to pre-work of I is equal to pre-work of I is equal to um zero that IQ is good to do right and uh yeah this is kind of awkward to be honest but it's fine uh and then now item is equal to cute IQ that pop left and yeah and then basically answer that a pen item right and then now we do the for next item in item is an item after items after uh inconsistency here but yeah uh item uh yeah if item pre-whack my eyes you're gonna if item pre-whack my eyes you're gonna if item pre-whack my eyes you're gonna do zero then IQ not a pen and I okay right so this is basically it's a little bit yucky it's a little bit recursive but yeah that's basically the idea um there are a couple so it doesn't have to be ex you know the same because there is still just like no other stuff right um but yeah basically it's a it's an interesting two level top logical sub first on the group and then within a certain group uh the item so let's we'll talk about ooh I was gonna say we talk about complexity next but apparently I have some wow today it's been uh hopefully I'm getting all the wrong answers out of the way here and not doing the contest which is in about half an hour but uh what is going on here so okay uh let's do huh not gonna lie I'm a little bit surprised but maybe there's an edge case um or maybe even the typo there's so much typing 65 lines of code so it's quite a bit uh but yeah okay let's see print oops crunchy so let's see uh so it only does two groups it never does group zero why is that tell me why see uh so pre-work oh no that should be no that's not what I was running on um why is that all right let's see good pre-work good pre-work good pre-work no not that development after so after one is zero two is zero you know that sounds right and good playback should be two right oh this is three so I have an issue here somewhere oh I see because this is basically the same thing that we were saying earlier because this is now um a set um because I think I detoped it here okay I think the set doesn't really make sense yeah I mean I think this should be a list I think oh here the set is fine but the group part has to be a list um yeah because basically it was doing that and then we're subtracting only because it was adding multiple times but subtracting only once so that's why it was not working I don't know what the subtraction is but uh but I think converting to a list should fix it uh as long as I also fix stuff like this yeah I mean I think for consistency I'll make everything a list yeah okay what a silly mistake um I mean and it's something that in a in an amusing way I caught already in the other thing but I didn't really trace for all my there's a lot of code um I did fixing it with set I mean doing it with set fixed the other issue with self whatever but I think I just end up introducing a bug with that uh apparently the first time I did I didn't have any books how'd I do at that time probably the same thing yeah I mean I just more longer things but it seems like the idea is going to be the same uh yeah all right yeah uh hopefully I mean this has been a very long video so if you've been watching hopefully that's been kind of you know I mean I don't think there's anything um I think in the theory part of the problem is pretty okay but there definitely is a bunch of easy to mess up implementation as you kind of see even with minor nuances uh even if you know what you're doing or if you think you know what you're doing I don't know maybe I don't know what I'm doing so what's the complexity right um so the couple of things well I mean this one just is all of one for whatever for each item so that's linear and all of well just over linear or G uh o of N I guess actually right uh this is also linear everything is all of one for each item so this is just going to be linear right and this is you know a number of prerequisite um predicates I suppose so still linear you could use another variable like maybe n plus Q or something like this um this is linear right and because each item can only be added once this Loop is linear and even though there are two while Loops they amortize in that each item can only each item in the original input can only popped once and each group in the original input can only be popped once and pushed once so in that case everything is linear um it's n Plus uh and you could say there's a g as in group but it's not even really because group is just a function of n kind of demand you want to say it and I don't really do anything specific with G so this is just linear and O of n plus Q where Q is the total number of before items you can think about them as query as I do which is why I said Q so yeah n plus Q time and N plus Q space um especially when you do all the list we're just rewriting the input but everything's linear so yeah uh here's the top again and here's the bottom again and hopefully during the contest I don't I start making these silly mistakes uh yeah that's what I have for this one let me know what you think let me know how you did stay good stay healthy to your mental health if you're doing a contest later good luck I'll see y'all later and take care bye uh
|
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
|
1,423 |
Quick guys welcome back to my channel like this video we are going to solve maximum points you can get phone calls so what is this problem statement given here you have been given one card points some points have been given in this and given here But it is given here that it is said that you have to pick quartz, there is a way to pick it, either you can do it from the beginning or you can do it with these and after doing this here, what you have to do is to do the maximum school point. This is your sum of these points, maybe the group of points is correct, that pattern of maximo, look at this as an example, I also understand this, it may not be clear to you if it is on the statement, but here you will understand. It will come in OK, the card has been given its week value of 123 456, that is, you can pick three cards from here, now let me show you how to pick, OK, what will you do here now that you can pick these three cards. Is this a possibility of yours, can you cut the day by either tweeting life in, it's okay, you can either make these two cards, make this cute, you can cut these two cards and this one, it's okay Either you will take one from here and two cords from the end, both of these, then there will be a possibility of taking three cuts. Okay, now see here that I have kept the phone, neither fold, how can you fix it here. But go for you will fit these four cards, take 1234, either you will unite the four, by doing this cutely, what will you do, will you unite with Vilas, okay that is yours, or you will make Trisha break the tree, 2 third last from here But we will pick two cards, now okay, either we will mix two here and cut one, from here, what will we do with the bonfire, what will we do with the frill cut, okay what will we do with the level, so we can do 356 Olympics, this is ours, we You can take if you see here, is your window print tight, is your window tight, is your question now sliding window based, now how will we solve it, we will see it is ok and in this we will see all the swears will fold which will give you this sliding window. Window So far we have seen that the maximum that will be in this window will be our answer. Okay, so how will we solve this? What will you do? Look, what are the people here in Mexico? The maximum in the window will be our answer. Okay, so we will sign first. We will take 123 oath of the voice record. What will be your last song? 136 Now do it exactly, then you remember it started from here, make it cute like this, okay. Institute these two and institute the last one i.e. you are institute the last one i.e. you are institute the last one i.e. you are making a tweet to it. Look for example I have attitude and include, whatever is the name of which index, rough and cute that you are inputting it now, this will give you the form. Ca n't you have a problem and who got the index somewhere, we are cute, this has to be cute, on the basis of that, we will drive here, okay, so we are pressing someone here, 0123 123456789 size of salary, how much is it, edit, what is this, free. First of all, you have this card, you have made Yagya's option finally maximum, we have made it equal here, okay, so here we come, okay, we will make this cute, that is, it is going to be selected, we will make the tube white. I will show the printed ones, we will institute this. When you exclude this, you will institute this, what will you do from then - you will do it, you will institute this, what will you do from then - you will do it, you will institute this, what will you do from then - you will do it, you will free your time, you will do it - you will do it, free your time, you will do it - you will do it, free your time, you will do it - you will do it, okay, you understand, you will do it - you will do it with lipstick, okay, you understand, you will do it - you will do it with lipstick, okay, you understand, you will do it - you will do it with lipstick, three - want and you will add this. If you do it worldwide three - want and you will add this. If you do it worldwide three - want and you will add this. If you do it worldwide then how much will we get, all yours will be yours and it will be 3148 214 and yours, here we will do it at this maximum, at the lowest, is it greater, is there no cigarette, then the maximum, what will be given on the saints, this is this. Done, now we come to this, now what will we do to two also, we will make it cute, what will you do, we will select one, now we will select one is famous, one is doing fact and we will decide on this, five will be untouched, five will be cut, we will input here OK. So, what will you extract from the total society? 1 and 6 means what will you do at that time? Now you - 6 means what will you do at that time? Now you - 6 means what will you do at that time? Now you - people, what will you do with this time - 2 will do - people, what will you do with this time - 2 will do - people, what will you do with this time - 2 will do - what will you do in the 2nd year? One lesson, how much will the total be? Maximum is the best on 1512 2683. So if you set it to the maximum then it is there and again what will we do, we were of Tuk Active, now we will make the forest too, what will we do with this, what will we do with the life tax, we will make this cute and what will we do with the footsie index. What to do, if you do the institute, then you will see here how much will come out, I swear, 561, 500 or not, 1112, what is yours, understand that here twelfth will come out, then we will compare with maximum, how will it give, if it is better, then what happened to maximum too, please update. Updated, what will happen by updating? Shiva ji, I will take the maximum, son, this is what you will do. Now look, we have a window, first what will we do in it, Kumar is going to be completed, what will we do with the first element? First, we will add the first element. Okay time, what will we do first element, what will we do after that, we who came from here are doing our to that cute, then institute this one, then we are doing it to the premature one, he is Bigg Boss, then we institute 5x We are selecting, we are unmuting the products, four, when this is ours, what is ours, now Falgun is okay, when you are pathetic, that is, the one who is institute karezva par tou. In follow I Kumar, the main thing is to improve, then what is the index of girls have improved, what is your fix, you can subscribe to it, so now what will we do, after doing this, we will move to one side from where we will start from what will happen. Yours will actually start from minus one, okay then what are we doing, then here we are taking one, looting it and inserting five, okay then what are we doing with zero, here we are doing this That's why we will rise up and we will go from you to the ends, otherwise - how far will the descendants go, will they go till zero, otherwise - how far will the descendants go, will they go till zero, otherwise - how far will the descendants go, will they go till zero, okay, what will we do with minus one, we will go from jo to jo, but will go from to the old people, okay now How to decide this from here, how will it come out, see more than this from side to side - will you do it or not, what will happen to you, it will be more than this from side to side - will you do it or not, what will happen to you, it will be more than this from side to side - will you do it or not, what will happen to you, it will be free when your I2 will remain two, now from here - you will do seven - will remain two, now from here - you will do seven - will remain two, now from here - you will do seven - side, and if there is more, what will have to be done to bring six I here But whether you have to add or not, first you see, here you will calculate the intake - 6 3 4 plus in2 is the speed intake - 6 3 4 plus in2 is the speed intake - 6 3 4 plus in2 is the speed point, if it is two, then if you add it will be fine, then 4 - k any intake - what is be fine, then 4 - k any intake - what is be fine, then 4 - k any intake - what is in the east, 1805 nickels. Yours will go again to the public's plus eye. When airplane mode is on, you will do four plus 0 of your photo. This will come out. So, who are going to use this index, what are we going to do with this, use this, who are going to use this index, what are we going to do with this, we will make this cute, we will input this, okay sliding. This is what we do in the window, now let's come to the coding part. We have coded all the inches that we have taken from here and have solved till K. Okay, from death to dedication, we have climbed the index of Assam for our file. What about the maximum, everyone wrapped up this time, okay, then we did that - we okay, then we did that - we okay, then we did that - we went till Istart classes, which will be our K-start went till Istart classes, which will be our K-start went till Istart classes, which will be our K-start and will go till here, we explained it to you here because we are here because 2 - from because we are here because 2 - from because we are here because 2 - from Bluetooth to Now you are going till Gya, you are having an accident, Bittu, where will you get it, you will get it from minus one and from here you will use follow, you will go till your zero comes, okay, we have taken this here and then in the system. What did we do to make the eye points cute? That's why - we do to make the eye points cute? That's why - we do to make the eye points cute? That's why - What to do in time and what to do to the points eye, what will we do to make it cute and what will we do to respect the institute, what will we do to the daily size minor plus what did you institute? Now given that I have got the maximum of everything in both of them, I will do the maximum here, I will update it here, finally, what will we do, the maximum will I stunt here, let's run the airport, do it, submit that young man, any of them, I will message you on Please help me, please like, share and subscribe, it's ok, thank you.
|
Maximum Points You Can Obtain from Cards
|
maximum-number-of-occurrences-of-a-substring
|
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain.
**Example 1:**
**Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3
**Output:** 12
**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
**Example 2:**
**Input:** cardPoints = \[2,2,2\], k = 2
**Output:** 4
**Explanation:** Regardless of which two cards you take, your score will always be 4.
**Example 3:**
**Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7
**Output:** 55
**Explanation:** You have to take all the cards. Your score is the sum of points of all cards.
**Constraints:**
* `1 <= cardPoints.length <= 105`
* `1 <= cardPoints[i] <= 104`
* `1 <= k <= cardPoints.length`
1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.
|
Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce.
|
Hash Table,String,Sliding Window
|
Medium
| null |
740 |
hey everybody this is larry this is day fifth of the leeco martial challenge hit the like button hit the subscribe button join me on discord let me know what you think about this prom and today and general life um yeah so i today is my last evening in median uh medellin uh so ah i am uh not 100 sober say but we will let's face this problem together um i'm probably also doing my video tomorrow a little bit slow so hopefully that's okay uh hopefully you know it's not uh demanding but i'll probably do it from new york i believe and that's my i don't know this thing is really i don't know i don't have i don't think so but we'll figure out how it works i mean this is how async internet works so i think we'll be okay right um yeah so today's problem is delete and earn so okay let's see what are we deleting what are we running so okay so we have three i should actually read the problem um yeah like i said i'm not 100 right now so that's how that goes um but yeah okay so you give me the numbers you want to maximize okay pick any numbers up i and delete it to earn numbers of my points afterwards you must add every element it goes to num sub i minus one and okay that's interesting so basically the i d is i mean this reminds me a bit of the dynamic programming problems in that um um let's see what is n is 2 times 10 to the fourth so but basically the idea is that um you know for every number you only have two choices right or every like unique integer you only have two choices right one is to uh one is to keep the number and the other is to not keep the number right and then skip it so it reminds me of like one of those reservable problems or something like that um i'm just trying to also think better whether um yeah whether we can be a little bit smarter um but let's see okay so i don't i mean this is a weird one because it's supposed i don't know it's supposed to be a medium but i think i have an idea and like i said it's going to be like there are i forget i think you don't need code they call robbers but it's the idea that you know you can take a um and then when you take a you cannot take a plus one or something like that right so that's basically the idea and of course in this case there is a greedy component in that you pick a number you pick all instances of these numbers because it doesn't cost you any more right but in this case you want to pick all the threes because why would you stop at one degree so that's basically the idea um okay so then the first thing i would do is let's see let's just have a calendar as you go to collections dot counter of nums and then now we have um let's just say we have set of nums as let's say we convert this to a list oops and we sort this um i think we have to actually convert this to this again maybe i didn't need this list but um by the way so basically you uh this is my unique how do you spell unique right so here right so we have all these unique numbers and then we have it sorted so now we have four okay that means that we can do two things yeah so then now you go by every index and this is now i think exactly the same as the robber problem uh i call it the bob i mean that's the lead code one right so that means that um you could do a bottoms up you could throw tops down i'm gonna do a top down for now um let's just say go of index right so then now if index is greater than or equal to n then we return zero n is equal to length of num and now name of unique because that's the unique thing and then now we can go um let's say and this is dynamic programming at this point hopefully i made that clear maybe not like my apologies i'm not 100 right now but basically you have two choices one is take current index so we take this uh take is you go to um this index times uh or rather let's see what does that mean this is okay yeah this is the number and then so it's this times counter of unique of index because that's the number of calendar because then you take all of them and then this plus go of index plus uh okay actually it did um there is an if an additional if statement that i didn't cons or i didn't make it explicit which is that um unlike the robber problem we should check that index plus one um for example okay right let's see so current is equal to distance say and then we do okay if index plus one is less than n and um and unique of index plus one is equal to unique of index um plus one so in this case then take is you go to current plus go of index plus 2 because now you want to skip the index plus 1 so you do index plus two else take is equal to current plus goal of index plus one because that means that the next bigger number is already uh doesn't include plus one and of course the same logic applies to the variable form so we don't have to think about numbers of i minus one because by default when we go from left to right going forward that's the thing that you're going to do anyway and then skip is of course just um just go of index plus one and that should be good so then now we return max of tick and skip um and then that should be good we go of index of zero uh is that true i think that's just true yeah so let's give it a run of course we didn't do the memorization part so it may timeout but at least we i want to make sure that oops i want to make sure that oh i'll make sure that at least we return these test cases are actually kind of terrible so it may actually be good even though even if the answer is wrong so let's just do something like funky um and then let's give it a run let's give it a spin uh yeah still my time out like i said and it should um so this looks good for now what we want to do is um do a memorization technique right because n is really big um even if they're all unique it's going to be i guess 10 to the 4 which is what's 10 000. so the 10 000 numbers if you don't memorize it's going to be a little bit sad here we can memorize it by just uh meant to say cash as you go to uh it doesn't really matter what this part is um and plus one no i think n is probably fine maybe not it has cash is you go to force times n right so then now we just have to add some magic which is if it has cash of index return cash of index and then here of course we go has cash of index is you go to true and then cash of index as you go to this thing and then we can return the cash let's run it again real quick i guess i should have showed uh an exponential case but i don't this doesn't even seem that much faster to be honest uh than before but uh but that's because we didn't really figure out how to scale it per se so maybe we can do something like this now because it's supposed it's on the uniqueness so this is a little bit awkward okay fine let's just run it one more time and it was a minute um because the worst case is that all the numbers are unique which i'm a little bit lazy to do i mean you could make do something right for example you can set um nums is equal to um list of x for x in range of um was it 10 to the fourth or something like this if you do something like this then it should give you the example case and obviously this is wrong answer but we only care about the running time and you can actually check to see if the running time would run too slowly by commenting the caching part and this should give you a time limit exceed it and you can yeah i mean it's going to go time to next date i'll be very shocked if it doesn't um and then here like i said if you run it was running in like pretty quickly uh but as you should know uh definitely we remember to remove it and then one more time oh well okay fine um just to make sure that it's right before we submit i just don't remember this problem have i done it before i guess not huh so yeah okay but still it doesn't challenge me enough i guess even uh so several i mean i was a little bit slow i suppose but yeah so the streak is now 704 yeah yay uh and this is my first time solving this problem yeah it's been a while so i feel like since they um they've given a problem that is new to me but man i'll welcome it anytime so what is the complexity right well if all the numbers are unique then and also not sorted then this is going to be n log n so let's write that here this is also this is linear time but this is going to be n log n and that's going to dominate it um yeah let's just write oops and uh o of n log n and here the complexity for here uh remember that index can go from zero to n or maybe n plus one something like that but roughly zero to n which uh is of oops numbers of input uh so each index is of one space because you just store it in you know two different things maybe um and each index is um off one time because at most you're doing over one lookups on all these things so this is going to be uh linear space and linear time and that's pretty much all i have for this one um it's yeah i mean i haven't seen this one before so i'm happy about this uh yeah that video i have let's take a look at the show hint you take a number let's take it all yeah i knew that um i would have just a easiest problem keep track of what the value is of the subset of the input i don't know i am not 100 enough to read that okay cool that's all i have for this one um yeah stay good stay healthy take a mental health i'll see you later bye oops
|
Delete and Earn
|
delete-and-earn
|
You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104`
|
If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M.
|
Array,Hash Table,Dynamic Programming
|
Medium
|
198
|
1,816 |
hello everyone welcome to another video now this video is uh different because it is about strings okay uh but it also has an element of arrays as well which we'll be using uh but uh basically this question is about string and it is quite a simple one the question is really simple uh we are given two things right now uh one is string s and other is an integer K and we need to return a new string with K first words okay first K words like if K is 4 in this uh example you will see first second third and fourth so these four words we need to return now one another thing uh we need to take care is we don't have any space before and after of our first and last word okay so like uh without spaces we have to return that so um the question is really simple let's dive straight into the code that is going to be a little different because we'll be using a lot of uh string functions okay and one another thing that we'll be using is a string Builder okay if you're not aware about string Builder and string buffer I would recommend that you go and learn that first okay because that comes very handy when you are solving questions where memory is uh memory is critical because when you concatenate on a string okay uh the a new string is formed okay in instead of just a concatenation so for because of which uh there is a lot of extra space or extra memory is used which is not the case when we are working with string Builder so anyway let's start with the code so first let's create a new temporary string array okay now how will we create this okay from our string given string s we'll split all the words given based on the space okay so how that happens is s dot split okay and the thing with which we want to split our string into arrays okay so wherever now this space it will come okay it will generate a new um string at that particular index okay if we had given instead of space we had given some other thing like h e so for example so whatever whenever the string will encounter an he it will create a new value in that array but here we will give this now we need our string Builder as well because we will do uh concatenating our K words into our result right so let's create that string okay our string Builder is ready now sorry now we need to append keywords in our string Builder so I'll go from I less than k okay so my string is result I will append um word at ielt position no not word temp at ith position okay and after this if you will see here we need to return our s with like the result with a space between two words so I will append a space as well okay now our result it's a string Builder not a string so if you will uh if you will look at the return type it is string so we need to convert our string Builder to a string okay so what I will do is return result Dot to string now one more thing after the completion of this whole Loop we will have one extra space at the end we need to remove that so for that we'll use trim function okay so let me submit this okay so it is that easy now obviously there are multiple methods with which you can solve this is just one of the method you can go into the discuss section and see different ways with which you can solve right now we are solving it in two Ms if you can see I have solved earlier in zero ms1 Ms okay so there are multiple ways with which you can solve this question but we are right now focusing only on one way okay so yeah that's it for this video I hope you liked it um do let me know if you have any suggestions queries or any problems that you want me to solve from any other platform okay so yeah thank you for watching I'll see you in the next one till then keep coding
|
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
|
921 |
hello guys welcome to my channel and today we're going to be looking at leeco knight 21 minimum add to make parenthesis valid so given a string as of left parenthesis and right parenthesis we add the minimum number of parentheses and in any position so that results parentheses string is valid formally a parenthesis string is valid if only if it's empty or it can be written as a b a concatenated with b where a and b are valid strings or it can be written as like this where a is a valid string given a parenthesis string return the minimum number of parentheses we must add to make the resulting string valid so the explanation is really confusing but it actually means that left parenthesis must be closed by right parenthesis to make it valid if like right parenthesis come before the parenthesis it's unmatched and it has to you should like your output should plus equal one so for this example this right parenthesis and this love parenthesis match so they offset each other so they offset and you left where you are left with the right parenthesis that are that is not closed so your output is one so for this example there's three left parenthesis and they're not closed by red parenthesis so that's why the output should be three and uh for this one they offset each other so the output should be zero and for this one um if this parenthesis uh they're matching so it offset each other for this two parenthesis there are no left parenthesis before them so your output should be two at this point and for this two left parenthesis they're not matched with right parenthesis after it so your output should be plus equal plus 2. so 2 plus 2 is 4. so basically this question just means that left parenthesis are matched with right parenthesis but left parenthesis has to come before right parenthesis okay um so there are two approaches one is keeping a stack and like a pending left parenthesis to the stack but the space complexity is going to be om because you're keeping a stack another optimal solution will be one space so a one-space solution is like i have the a one-space solution is like i have the a one-space solution is like i have the number of flat parenthesis and we initialize it to zero we have a number of write parentheses we initialize to zero and we have our count which is our result we re initialize it to zero and for each uh like a character or each symbol in the array if like it's a right parenthesis then um if it's a right parenthesis uh then there are like two scenarios one is like for this example one so if we are at this point one uh one scenario is that if left parenthesis is greater than zero so at this point it's like one right if it's greater than zero then we can decrease the left parenthesis number by one another scenario is that for example it's like right parenthesis and we have no left parenthesis then we know at this point we have to increase our count by one because there is impossible to have a left parenthesis matching it because at this point our left parenthesis is zero right so our output should no matter what increased by one uh else so this means our symbol is uh is a left parenthesis if it's a left parenthesis we just increase our left parenthesis account by one and in the end we output the left parenthesis in the account so let's go through some examples so so for example one our left parenthesis is one at this point um we have a right parenthesis and we check whether left parenthesis is greater than zero it is then we decrease the lab parenthesis count by one so it's zero again and at this point we check if we have any left parenthesis if it's greater than zero it's not so at this point no matter what we have an unmatched right parenthesis so we increase our account by one at this at the end we output left parenthesis is count and let's go through another example so initially they're all zero our left parenthesis is one at this point
|
Minimum Add to Make Parentheses Valid
|
spiral-matrix-iii
|
A parentheses string is valid if and only if:
* It is the empty string,
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or
* It can be written as `(A)`, where `A` is a valid string.
You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string.
* For example, if `s = "())) "`, you can insert an opening parenthesis to be `"(**(**))) "` or a closing parenthesis to be `"())**)**) "`.
Return _the minimum number of moves required to make_ `s` _valid_.
**Example 1:**
**Input:** s = "()) "
**Output:** 1
**Example 2:**
**Input:** s = "((( "
**Output:** 3
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'('` or `')'`.
| null |
Array,Matrix,Simulation
|
Medium
|
54,59
|
1,557 |
hey guys this is steve here today we're going to go through legal problem 1557 minimum number of vertices to reach all nodes let's take a look at the problem first given a directed acyclic graph in dac with n vertices numbered from 0 to n minus 1 and an array address where address i is from i and 2i which means the first element of this 1d array is the starting vertex and the second element of this 1d array is the destination vertex represents a direct edge from node from i to node 2i okay find the smallest set of vertices from which all nodes in the graph are reachable it's guaranteed that a unique solution exists notice that you can return the vertices in any order let's take a look at the two examples here the first one and n equals to six which means there's a total of six vertices and it starts from zero all the way up to five so zero one two three four five and the edges what these edges mean is zero one which means zero is the starting vertex and one is the ending vertex that's how it's marked zero two four two there must be a pair called four two yes four two is here and then three four is here and two five is here so and the output is zero three why is zero three because we need to start from zero to visit one and two potentially five as well and we also need to start from three why because we need to visit three and four and two potentially five as well so we can visit two and five starting from both zero and three but we have to start both from zero and three in order to visit zero one and zero four right because starting from one you cannot visit four and starting from three you cannot really visit zero and one right so this is the reason the output is zero and three so if you notice some interesting things that would be cool but if you don't that's totally fine i'm talking about the solution how do we approach this problem if you don't let's just walk through one more example which is this one second example n equals to 5 which means there is a total of 5 vertices from 0 two three and four from zero to all the way to n minus one and all of these are the edges zero one zero lens three one is here two one is here one four is here two four is here and the output is zero two and three why is that is because we need to start from zero in order to visit zero and we need to start from two in order to visit two right but we can start from like three or zero or two to visit four or one either one of those are all fine right but we have to start from all zero three and two because we need to visit 3 0 2 as well right that's why the output is 0 2 and 3. so if you combine these two examples you can notice that the output is all of those vertices that don't have any edges come coming into them does that make sense say all of these one two four and five these four notes they all have in they all have edges coming into them right you see this arrow all of these four arrows are coming into these four vertices that's why these four nodes they don't have an indegree that equals to zero right however these two zero and three these two nodes they don't have any incoming edges again at the same um for this for the second example zero two and three these are the three vertices that don't have any incoming edges coming into these three nodes right but for these two nodes they do they have incoming those everywhere right so if you recall the other two problems that we described before if you can just search in my channel and also i'll just put a link here it's called cost schedule 1 and 2. those two problems we went through we used topological sorting algorithm to go through to solve those two problems in which we talked about there's a concept called in degree which basically very simple term just we calculate how many edges are coming into this vertex into this node if the in degree equals to zero then we can just add that one into the final result and actually this problem is just asking us to return a list a collection of integers that don't have any incoming address all right now let's just put the this idea so basically we'll just go through the edges and find which nodes don't have any incoming edges and then in the end we'll just return that so we'll put this idea into the actual code and let's take a look so first let me wider open this wider okay now we'll have a hashmap y hashmap the which is going to help us i'll call it in degree to help us keep track of how many vertices that have an integral that equals to zero which means there are no incoming address into this vertices right and the key is going to be the node that has any incoming address and the value is just going to be the count how many incoming addresses we don't really need a list or a set of integers to be the value of the hashmap because we don't really care what those incoming edges are right we don't really care as long as this node has an in degree then it's not going to be part of the final result all right i hope that makes sense let me continue writing this code so first we'll go through this edge address so remember the very first one of this two element smaller index is the starting point and the ending point is the second element so what we want is the end which is going to be the first element instead of the zero at index one right then we're going to update the in degree put and then we'll use in degree get all default get this one and the default is going to be zero and we'll just increment it by one after this in degree hashmap has been constructed so next we'll initialize the final output which is result list and then there is another parameter in the given api signature which is n which means there is a total of n vertices in the given graph and it's labeled from zero all the way up to n minus one so we'll start from zero all the way up to n minus one so we'll check if this indegree contains its key set contains this i if that is the case that means this is not a starting node then we don't add it into the final result it otherwise we'll just add it so in degree contains key i if it doesn't contain this that means this node doesn't have any in-degree address in-degree address in-degree address right it's in degree it goes to zero so we'll just add it result at i and then in the end we'll just return result in this way it also will it will also give us the result in the in sorted ascending order because we start from zero go all the way up to n minus one now let me hit run code to see if it's going to work all right accept it now let me hit submit to see if it's going to be accepted takes a long time all right it's also accepted cool so this is the way to like this is a pretty straightforward way to solve this problem we basically keep track of all of the in-degree nodes if there is in-degree nodes if there is in-degree nodes if there is any node that doesn't have any in degree so we have to put add that one into the final output which is going to give us the minimum number of vertices to reach all nodes i hope this video makes sense and also again feel free to check out those two videos that i made cost schedule one and two which is i would say more complex definitely more complex than this one so hopefully if you go through that one this one will be very straightforward so if this video helps you make sense of this problem then please do me a favor and hit the like button that's going to help me out tremendously and help with the youtube algorithm as well i really appreciate it and also i've made quite a lot of legal tutorials data structure and algorithm videos and also about amazon web services how you can prepare it to pass those aws certification exams feel free to check them out so hopefully i'll just see you guys in a few short seconds thanks very much for watching see you guys in the next one
|
Minimum Number of Vertices to Reach All Nodes
|
check-if-a-string-contains-all-binary-codes-of-size-k
|
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct.
|
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
|
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
|
Medium
| null |
1,026 |
Hello everyone, if we watch today's lead code challenge, a very interesting question has come. Let us see the question. Maximum difference between node and ancestor. If you want to know what is node and this ancestor, ancestors are basically your four fathers. Like if you are a You include yourself, your parents and then their grandparents too, so they come in the ancestors. Okay, so what will happen in the node which is a binary tree? Let's say that I am considering 14, this one is 14, so its ancestor should also be 10. It can be eight, it is okay, not more than that, if you look at seven, the ancestors of seven can be six, three can be eight, so these are all its ancestors, so what is asked in this every note is given a value. First of all, we have given the value, then what is the maximum difference that a particular note can have from its ancestor, then we have to return the overall difference whose maximum is also, that is, find such a node and one such Find the notes and whatever is the maximum difference between them, that difference should be maximum. Okay, first of all, we don't need anything. The straight forward question is, what should be the maximum difference between any two notes. It is possible, but it is not just any two notes, it is not so generalized that I see this 10 and this one. The condition is that if I am taking the difference from that note, then it should be its parent or assistant. Basically in Rakhi it should be above that and linked to it. With lets I will not be able to relate 10 and one because 10 and one are not related anywhere. If I look at one and 10 then it is one. Who is the parent of three and the parent of three is eight, he has become an uncle, you are a family thing, so he is not coming into it, okay, so it is okay to consider this, so let's understand some logic and then let's see what to do. If it is okay then first of all what we will do is if we have to find out the difference then we will have to keep both maximum and minimum. We will have to keep count of both, how many maximums we have achieved till now, how much maximum value we have reached and how many minimums we have reached at a particular stage. And then we will find the difference of both of them, okay, so look, I will declare two variables, I will start from zero, okay, Maxi and Mini, now what will I do, on 8, I will treat both of them with zero and after that, when it comes to the root, then the root. What will it do? It will reduce both the minimum and maxi to their values because there was values because there was values because there was no value before the root. Now what will it do? Now those parents will become their respective children. Basically, what are you guys doing? You guys are placing such an order. Let him visit both his parents first, we go to left and right, then he visits himself, then left and right, NLR, what is pre-order, okay, so place pre-order, pre-order, okay, so place pre-order, pre-order, okay, so place pre-order, now see, in this we went to left, then to right. So what will it do, it will send max 88, it will send 8, what does 8 mean that the minimum is also at, the maximum is also t, here also 8, a will send the minimum is also at, the maximum is also at, now it will compare the values, three will compare the maximum for these. So what will it do, will it make the minimum three and the maximum will remain at What will it make the minimum three and maximum will remain at eight Now this will find the difference of both of them, so how much maximum difference do you have till now? Five is coming, five is still the maximum, what will it do, it will increase the maximum, it will leave the minimum as 8, but the maximum will be reduced to 10, it will reduce the maximum to 10, okay because the minimum in 10 and 8 is a And what will be the maximum? It will be 10. Now find out the difference between these two. The difference is coming to 2. Is 2 smaller than phi or bigger? Otherwise, 5 is the biggest till now, meaning we have phi is the greatest till now, then this one is this. What three will do, it will send its accord here, minimum and maximum, what it will send is 38, now it will compare 38, now one will compare 38, then what one will do, it will make three smaller because if you compare one and three, then one is minimum. And if you compare one and eight, then eight is maximum. Okay, so you have this pair and take out its difference, then how much you are getting. Seven is coming, that is, it is greater than five, now it is greater than five, this means. We are updating our value which is the answer till now. Okay, this preorder is going on. Keep in mind, I am going to lefty and then giving its left. Now look at its right. What will it send here also? Will send 38 for this, there was 38, here also 38 here also, he sent 38, these 3 oops, here also he sent 38, okay now 3 co 8 here, what update will happen here, there will be some update, six is coming in between. If it will update, six is coming in between. If it will update, six is coming in between. If it will not update anyone then the difference will remain the same so there is no benefit. Okay, it will send 38 here. If it will send 38 here, then 38 is also coming in between it and four is also coming in between it. If it is then no value will be updated, meaning till now our maximum is only seven, one will send its further but it will not be able to send, it has no parent, it is not its child, ok, let's come here, we have executed 10, after this we will give 14. P 14 P What will send 8 10 will send What will 8 10 send So what will 14 do 14 will update 10 Will update the maximum How much will the maximum do 8 14 will do How much will 8 do 14 will do By doing this 14 he now found out its difference. 14 - now found out its difference. 14 - now found out its difference. 14 - 8 6 of these two is coming, still our maximum intake will remain the same, it will not be updated, then will this person call or has he gone ahead, he has sent 8 14, sent here also 8 14, so this is 13, so in between that. If it is coming, then it will not be able to update anything, neither minimum value nor maximum, okay, so both the things, you can say that here also it is not getting updated, then the maximum answer is your kitna aa raha hai sen, question is coming once. Let's see what is coming, then see, seven is coming, okay answer, seven is coming, one thing, yes, keep this question in mind, see amazonbusiness.in that it is not 8 for me, if he is amazonbusiness.in that it is not 8 for me, if he is amazonbusiness.in that it is not 8 for me, if he is sending it for both his children. Whatever is the maximum and minimum for him, neither will he send same to both his children, similarly here what is the maximum and minimum for three, it is Thr and T. Okay, so it will send S and T to six and also T to one. 8, after that the values will keep T to one. 8, after that the values will keep T to one. 8, after that the values will keep updating but he will keep the same in his parents' call. will keep the same in his parents' call. will keep the same in his parents' call. Now keep one thing in mind, if you send one by reference, you understand 38 by reference, right? We send it by adding ' right? We send it by adding ' right? We send it by adding ' m' and saying 'pert', it will know that m' and saying 'pert', it will know that m' and saying 'pert', it will know that point, basically you will enter its value further, if there is any change in the function or in the overall program, then it will be reflected in any step which you will perform, okay? If I send this call by reference 38 means I will send maximum and minimum by reference, then here it will change 1 8, so the first call is going to be one, keep in mind, this thing is very careful, here you have caught it, the whole problem is solved. It is a small code, it does not have a big code, you just have to be conceptually strong, if I send 38 here and you here, one will be updated, one will update 8, when the value goes to six, then it will go to 1, 8. You send y reference, what do we have to do, we do n't send 1, 8, we have to send only 38, brother, for this, both our children should be of equal number, brother, this is 8, this has become his brother or sister, whichever parent you believe to be. This is the parent. I will compare it with the value of the parent. Answer means, this is what happened, that's why I said the question. What is the question? Anyone would have said this. Find out the maximum difference between two notes. What will you do? You will traverse the entire graph. I have taken out the maximum and minimum value and given their difference, but it is not so, there is a little trick in the question, I have to find the difference between the set and the child, okay, so here we are matching the answer and the child, that is why we are matching three. We will see, we will see a little about my brother, it is getting updated here, it is okay, keep this thing in mind, so I will write the code to you, after the code, I will keep telling you along, okay, so what will I do, I will declare a minimum mini. And I declare it with the value of the root because we have to take the root absolute value, okay one more thing, let's see its constraints, let's see the constraints, let's say the number of notes will be two, so we have one thing, right, if the number of notes It can also be zero, then you will have to return directly. If you are not root then return then I cannot access the value, nor will I access the value, it will give a null or run time error, so if it sees this thing then I will also return the value to Maxi. If I do it from the root value, then this is the assurance that there are at least two values, so that means I can find out the value of the root, okay, first, I declare the difference, I do it with zero because the minimum difference will be zero, okay, now what do I do? I am calling my pre order, I have called the pre order, what will I send in the preorder, first of all I will send the route will run the entire program, then after that I will send the mini, I will send the maxi and I will send the difference, okay send these three things. I gave it and now look carefully, I will keep the function type as void because I don't want to return anything and I am taking a nut star to the matri. Okay, after this, talk very carefully here, I will not say bye to the mini. I am not taking the by reference, I am not taking the mini by reference, here it means the value will be copied, the by reference pointer will not go here, I am not taking the by reference, I am taking the value, okay, similarly I am taking the value of the maxi also. Yes but I am taking the difference by reference brother, I want the maximum overall difference in the entire program, were you watching ? ? ? So you should remain the same, there should not be any difference there, you have to find the maximum difference in the overall program which is valid in the sense, there should be an answer, there should be one child, okay, so you have to keep it valid, you do not do this in You can declare the difference here also, you can declare it like this, now instead of declaring it here and here, you can declare it here too and that will also work but I generally prefer that I send it in the function call. I am giving it because if you see in interviews then they forbid you not to declare global variable. Ok, that's why it will be better. After this we have to check if the route exists and if not then what to do. We will return it if not. If you do, then we will return it. Now there is a possibility of not doing it. Look, here P One P, we are here P The One has no child, so when one sends, it will send its left child, that will not happen, there will be no tap, so return there. It will go like this, if there is no right child, then it will return there also. Okay, what are you doing now? I have to update the maximum and minimum, first I change the maximum to the minimum, then how will I update the minimum of the minimum which was already there and which is Now the value of the root is, now the value of the root is ok, this is updated, similarly, there is nothing in maxi too, max of maxi comma, see the root value, this is also updated, ok, both are updated, what to do with the difference. What to do, brother, I have to find out the maximum difference, neither the max of difference which was running till now and the difference of maxi minus mini which may have been made now or if it has not been made then it will remain the same and if it has been updated then it will be Change will happen here, okay, what to do after this, I have to return something in it, don't do it because it is void function, I have to call father, whose call is to be made, left child and right child, left child, where will I take the root of left. What else will I do? I am sending maxi and mini. Should I send mini first or should I send mini first? I want to keep in mind that the function signature should be as it is. Okay, after that I will send the difference. So this is the minute detail that which by reference should I send you? Which by- which by reference should I send you? Which by- which by reference should I send you? Which by- reference should not be sent to you? You can answer this question in many ways, but the way I do it, I find it very good and if you also do this, then you will not face any problem. I also call the route right, mini maxi and difference is fine, if I don't have to return it anywhere then my function is called completely. Now one thing, what did I send the difference, if I sent the difference by reference, then the value of difference would change. If it has happened then whatever difference will be there, I am returning the difference because integer is the return type. Let's run it once and see. I hope there is no mistake, compilation mistake, any mistake in writing. Okay, so I have made it full screen. I remove it from the full screen and look at it once, I do n't know where it is, I think there is some bug in it, I refresh it and see, oh hope my code is saved, now it is visible but the code is not coming ok So the code is the same, ok, so once I run it and see, there could be a net issue or there could be some issue or both, it is getting accepted, I submit it and see, it is getting submitted and you see. It can be said that in run time it has beaten 85 and in memory also it has met a good number of people but 47 but one more thing, I wanted to show how many times it has come so I will see when was the last time it came. When I go to my submissions, it has also come on December 9, 2022, that means 2 years ago, not two years, you can say almost, a little more than a year ago, it keeps coming, so if you practice such questions, you will get some answers. There will be no problem, one more thing, I will say the code, I have given the code, gut up code, I have given it in the description, you can take reference from there also and like, subscribe, send it to your friends, ok and support, thanks. tomorrow in new video
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
242 |
in this video we're going to solve the problem valid anagrams on lead code so given two strings A and B return true if a is an anagram of B and false otherwise so just for recap what exactly is an anagram it is a word or phrase that can be formed by rearranging the letters of the other word or phrase so for example we have car and Arc so we can rearrange the word car to get Arc if there's a c over here then there has to be a c over here listen and Silent basically also anagrams and knee and key now one thing to note is that if over here if there are two e's over here then there must be two e's on the other word so the number of frequencies must also be the same so one way to determine if two words are anagrams is to take them and sort the letters just like sorting numbers from least to greatest so after we sort them we both get eil and St and this indicates that silent and listen are anagrams and here is the code in Python we take in strings A and B we lowercase them with the lower function then we sort them and then we compare the results and if they are the same return true if not we return false so the runtime of this code is o n log n due to the sort function and the space is all of n because the sorted function will turn the string into a list of letters what if I tell you that there is a better and faster solution than the previous one well here it is so let's say we have feed and D Phi we then create an array of size 26 and we fill this array with zeros initially so let's say index 0 is for a index 1 is for B and so on after we created the array we're going to go through the first word feed so starting with f we know that f is at index 5 so we increment by one about e well E is at four so we increment 0 to 1. e again this becomes 2 and D this becomes one now we go through the second letter I mean the second word so starting with d is at index three so we decrement we minus now so this becomes zero how about e 2 becomes 1 here or f one becomes zero and E one becomes zero you can see that all the numbers in the array are zeros and this indicates that both of these words are anagrams so you might be wondering how do we know that f is at index five well that's a very good question so here's a way to determine we translate F into its Unicode so the Unicode of f is 102 and we can use the order function to do that then we take this number we minus the Unicode of a which is 97 and then we get 5. so this 5 tells us the location of f inside this array and then we increment the zero to a one if we're going through the first word how about the letter D well the Unicode of that is 100 we minus the Unicode of a and it's always going to be a so we get 97 and then we get three so the location of D is at index three and we're going through the first word we will increment the zero to a one so this solution is all of n because we don't use sorting so it's not n log n like last time and we also create an array of size 26 so all of 26 is equivalent to all of one which is constant time now the first step is to determine the number of letters and that's 26 then we also lowercase S1 and S2 then we check if the length of S1 is not the same as S2 and they cannot be anagram so we have to return false this line of code here will generate an array of size 26 and fill this array with zeros so now we have it in the count variable we Loop through the string one for each letter we get the location of that letter using the formula I mentioned before then we go to the count array and we increment the content to one so we increment by one now again we look through the second string we determine the location for each letter then we go to the count and we decrement by one and at the end of the day we Loop through the count array and if we find that one of the numbers is not zero then we have to return false and if we successfully Loop through the count array and all the numbers in there are zeros then we know for sure that S1 and S2 are anagrams so we have to return true and that's basically it for today if you found this video helpful and enjoy it don't forget to subscribe and also share and leave comments down below if you have any questions
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
1,791 |
we have another question here let's see uh the question says find the center of a star graph okay that's really uh we should receive the question and then we'll solve it okay so uh as the undirected star graph consists of nodes level from 1 to n as Java graph is a graph where the center node is exactly as ish node and two degrees okay so what we have to do basically is uh you have to find out the center of our star graph so what is the center of a startup suppose this is a graph in which one Edge is connected one vertex is connected to uh all other vertexes by n minus 1 HS okay that is what it says the center node is connected to exactly and minus one edges so what we have to what we can do is we can just check s vertex is connected with more than one vertex okay if this vertex calculated more than one vertex that it has to be the center right suppose this vertex is connected with one two that it has to be the center of star right so we can uh do it very simply CL okay let me explain you more see suppose we compare one with two and three and we saw that one is not common but boomsoever is the center of a star it has to be content all the three edges so it is two here right similarly if we come here one here so one is compared here with five and one now we see one is common then if we use it one should be common on because it already said that there should be invents when Edge is connecting the single nodes so it should be that node only so all we have to do is just compare the First with these two and we have to just print the common if you don't find the prison answer with the second one oh and if not in the first one okay so this let me record it for you okay um Edge zero equal to e d H is one slash zero or this is to compare with the another one h 0 zero is equal to equal h once one suppose it is equal then we'll simply return h 0 but if it would if it is not common then we'll simply return I just quickly run this code and see if this works this is the second problem of today and we will be solving a lot more problems just stay tuned and keep subscribing to the channel okay let's see and it is accepted so good luck
|
Find Center of Star Graph
|
richest-customer-wealth
|
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph.
|
Calculate the wealth of each customer Find the maximum element in array.
|
Array,Matrix
|
Easy
| null |
1,385 |
yeahyeah Hi everyone, I'm a programmer. Today I will introduce to you the problem of finding the value of the distance between two arrays of integers. The detailed problem requires us as follows. two integer arrays in boxes d1 and d2 and a number D problem. Request to return the distance value between two numbers A. This integer array has a distance value, which is defined as follows, it is the number of parts. The element of here 1 so that there isn't any value of that or Which the formula is the r value the value of the first place here 1 - give the value of the here 1 - give the value of the here 1 - give the value of the first place here or take absolute value is less than or equal to the distance value A minus point B is the absolute value, so here we are, like this problem has a formula like that's why people call it distance calculation, now you understand how to understand these distance and return values. it is the number of elements in the shell that have a distance from all the elements here or large Hyundai, do you understand this sentence like that ? Well, in the example one day we will ? Well, in the example one day we will ? Well, in the example one day we will see that people For me here, one is 45458 and two people think it's 19 18 and D is equal to two, then please explain here. Now we consider the first elements of R1 to be four, then we see that it is 4. There will be a distance from 10, a strange 64, a main distance of 54, a distance from one of 34, an eighth distance of four, then all of these values are of four, then all of these values are of four, then all of these values are 6534, which are larger than the value D that the beginning of the article said. An so the first element of array 1 is 4 which is counted as a return result similar to the example with the second element, we are difficult because it is only year then the year will have a gap with 19 18 respectively 5 4 3 also all this distance has grown or not year is also a return value Yeah natural for the way your final values here 1 Because we your final values here 1 Because we your final values here 1 Because we see that the value is part 8, there are cases where 8 items are separated by 10, you see that they are only two numbers apart, then 8 - 10 is -2. Take the one I like the most, 8 - 10 is -2. Take the one I like the most, 8 - 10 is -2. Take the one I like the most, which is two. Then there is only a difference of It's only 2 numbers, so it's not big. Hyundai is small, it's equal to D, so it's strange that this number 8 is not a return result. We only have 4 and 5. We will return the number. The two of us just need to calculate the quantity and return the quantity. A If you call it the same way, you can also do the examples 2 and 3 yourself. Okay, then the algorithm to solve this problem I think This is the simplest algorithm that you can see when you look at it: that you can see when you look at it: that you can see when you look at it: you will have a loop inside each other, an outer band filter loop will be the loop that filters everything here one by one and inside there will be a loop. of good sheets, each time we filter we will have the value y which is the variable run here a lazy di run callback or then we calculate the distance of i and j then calculate the distance of the element at the position knowledge is identical to the molecule at the starting position. If any distance is less than or equal to D, then we do not calculate the current value. We do not calculate the current value when we do not increase the known value. our spirit does not increase our known by one unit but if after reviewing everything here or there is no element smaller than b or equal to D then we will increase the variable until we are one and finally, we will have the results returned for the problem. For those solutions, because we will use two loops inside each other, the complexity of the algorithm will be the only thing we want to do. Introducing to you another solution that is more complex and better, to implement this solution, our approach is as follows. We see that if we have the value number 4 in these types 1 we want to find the distance with want to take care of 4k want we want to check the distances with all these D2 molecules is it any guy that it is less than or equal to one Is there a certain value? I think I have to find out which number is the number. I have to find that value, which is the value closest to this number 4, right? That means I have to find a number, let's say in this array we don't have the number 4 or the number year but has the number 3 because the numbers 35 are close to the number 4 and they are close to the number 4. Its distance from 4 to those numbers is small, but it's small. There are two chances to say it's smaller than or equal to the name of the story's life, and if it's bigger, you just need to search in Are the guys closest to the coefficient 4? Well, I will minimize the number of times I fall in love with this piece here or this, right? Suppose in the cases that I see here or hey I just need I consider which guy owes money and I think I'll gradually give four what I see as administrative and administrative work with that guy. You're not the only guy, then we'll become one. If we see the first guy and he's ok. That's the guy. I know guy 1 is close to guy 4. Let's eat noodle soup, but the distance between guy noodle to become 1 is three and even closer to two, so it's like the guys who are far away in this case of guy 8, October 9, I'm not here. There's no need to go through it. If you skip it, you'll be able to optimize your filter loop. It will immediately become more molecular. The idea will be when you check the second element. If the element is in the yth position of the first string, I will prioritize choosing the ones that I feel are closer to the guy here. Well, how can I find the guys in the woods with this guy? Here, I will have a way that is to apply the Binary Search solution. Well, here I will not see the details of what to find and how, you will have to find out for yourself. later ha But to set up the function for that teaching department, I will use the Lan language, we will declare a vegetable noodle variable and I will declare a free variable with curvature first and then we will go to sea. Right away I'm so that I can apply the dark binary search party we need to rearrange the piece of cloth two a at any time we want to be offline to get what you want to apply To get the Binary Search algorithm, we remember that we must have a sorted version. Now I will rearrange the network A, call me to rearrange you guys here and then I will There is a loop that is independent of all work. This version here alone uses Real keywords, let me keep Kali, then let me go now. Now I start, I install the Binary Search solver Well, the idea is that there is a binary search, then we will have to find the A. Yes, the diaper in the middle of the one of the list that we are searching for, in the competition we have to declare a sound that is left and right. Declare the left and right names but don't know. Hey left so it's easy to understand that I kill this left variable, I will declare that if there is no more right variable then it will be the last prince of the piece of tree number 2 then part Its last element Its index is - 1 length from one then I will - 1 length from one then I will - 1 length from one then I will place until this list is smaller than the output, then I will look again. Now I start the binary search By declaring a variable in the middle, this is the point, the middle point of this loop, I will calculate the middle in an easy way + Write Then I divide by 2 then I + Write Then I divide by 2 then I + Write Then I divide by 2 then I will find get the one in the middle Well the next thing is I have to find out the distance between the guy in the middle and the guy in the middle of this job then I have to get it for her absolutely A and So that's it. What Vu Lan has that I haven't done yet is that it has a method to calculate something, but now tell me the method to calculate the absolute value is quick and simple, it has nothing to transport into a The score on TV returns a circular. If it's less than big or not too big, then I'll return it a Dude. If X big or small doesn't go, then I have to go back. If it doesn't, then I won't have anything wrong. So now I'm going to call Phuong, which means I've figured out this evening, I've got the money and I've figured out that the barier is the part of your current prince. Here's a suitcase. I 'm not afraid. I'll deduct the 'm not afraid. I'll deduct the 'm not afraid. I'll deduct the current value. The water position is in the middle of the one here. Hey, now we have to consider the one from last night. Let's look at this calf. If it's bigger than the d one, I'll talk about tennis in class 2b. Have you created a post? As long as I will continue to look for you guys that the neighbors still have, guys that are close to me with little happiness, let me find the happiness that you know often compares to distant guys who are close to me. The value guy, not just thinking about the guys who are close to this guy, will look for you. So compare this amount with who knows if it's bigger than the wrench guy wrote down, then I'll go and then what about it will be left aside. On my hand, what is it? On my hand, on my left hand, make the folds by knowing plus one. If not, what can you say? If I save it's bigger. Because I'm sorting in ascending order, this love bar I'm doing. search It recognizes that it is looking for the guy near it, so I have to compare it. I know that the guy in the middle is bigger than the guy in the middle, so it must be located from the guy in the middle to the end. That's because I've arranged the rows in ascending order, so I have to move this LED to the middle. I'm now in the middle so I can calculate what I know so I can calculate what. The middle one is the short guy + the middle one is the short guy + the middle one is the short guy + the long line. The two of them come out in the middle of the new stroke or the old ty ah and vice versa, we will now on the dai in and the advantage and illiterate learn Yes but there is another case that is If this guy But this deaf guy is not growing straight, so in this case I don't need to look anymore, I go out and ask, I go out and add the process, now because this is a double study, I have to paste the Normally label it here, but with a new label going out, I call it oster Yes Then I will fa I write continue our third Yes and if in the case that it never comes to this sheet then it is I know this is something I need to return to this program, so what should I give it to make it violate the unit? Hey, I checked just now and does it have the unit? Oh Is that ok and I tried here and it is I'll solve the first example. Ok. I have some types here like 7. If it's difficult for me, please go file. Because I don't have the 2.2 here. If you call, you can see that we have successfully solved the one written like this. One comes back as a result of two This is the request, who is also? Now I'm about to run out of money to solve the remaining examples. A and everyone please let me know that I have successfully solved all the remaining examples of the problem. I will analyze a bit about the complexity of this new algorithm that I introduced. The complexity tree of your variables and rearrange the handlock, then we have a The second loop is to filter through. I call N the element of the largest array to create an N-fold filter loop. In an N- an N-fold filter loop. In an N- an N-fold filter loop. In an N- fold elimination loop, I have a Binary Search operation and binary search. is the complexity will be Lock and ah So there will be it's me when I'm on top also it's me when I'm like that then finally we have the final complexity is it's me when hand A and the storage space and we use here we see that we are not using any additional storage space but the size changes as n increases or decreases, right? That's right, we don't use fragments. or what is the edge? So, the storage space we have is a constant. Question 1 technique Minh I will now end the video. If you find it interesting, please give me a like, share and subscribe. Trinh If you have a better guest or if you have any comments or questions, you can post one in the comments section below. Thank you. See you again. Goodbye. Yes.
|
Find the Distance Value Between Two Arrays
|
number-of-ways-to-build-house-of-cards
|
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100`
|
If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles.
|
Math,Dynamic Programming
|
Medium
|
815
|
257 |
hey guys this is it called 257 binary tree paths given a binary tree return our route to live pets a leaf is a node with no children so if an example here a binary tree and the output is a list of string which each node is a string follow followed by an arrow okay so it is to be a ADSs exercise where you need where we need to traverse through all the nodes of this tree and we have to star each node in a list and when we find a leaf node we have to put these in a result verbal we have already done some tree exercise here on the channel I will put the link for the playlist in the description so you can find the other exercises but yes this is pretty simple exercise and if you don't know how to traverse a binary tree I recommend you to do some search on the internet because there are a lot of ways to do this and here we will use an approach called up with first search and yes that's it that's right write some code to see how this works okay so let's start by checking if the input is alleged so this road is no we can return an empty list which I can declare if are they stacking so our result it was to always string and if the root is no I can return the result yes so I think we can go to over receive function here it's a private function will be employed and the FS of we note we also need here I think a list I'll swing a different web and also a result bar wall okay so as this is a recursive function we can start by checking the base case which is when root is no I just forgot to put the root node on the parameters so it really is no we can just return and like fixed a scale okay so if root is not know we can add the current node the current path so the current node is true but all but we have to compare it to a string and after that we can check if the current node is a leaf node and to do that we can just check in both the left side and right side are dope so root of left if you know and also get rolled out right he is known we can add the current path into the result horrible so you can do this by adding the string to join because we have to put all the arrows in front of all the note values do this by added our room here and they print that here that's it for the result variable and now we can and now you can call our records she called our recursive cases so to do that we can call me SS or the last node and also passing the printbed and there is a lot wearable and we have to do that also for the right side in here as we are going back into the previous node we also have to delete the last node that we added into the current path so whatever to remove and then through path - so here we are then through path - so here we are then through path - so here we are removing the last node we added into the current path because we are going back to the previous node and going back because of their recreation here and yes that's it I think this is the solution for the recursive method here and now we just have to call it here in the binary tree path method so the offense wrote the current path list and the result horrible here we have to return the result for wall so it could be if we do not have any type of disease dissolution let's try to run the code and let's try to hit save image yes let's see so time complexity here is yes I'm not 100% sure but I would keep a shot to Big 100% sure but I would keep a shot to Big 100% sure but I would keep a shot to Big O of n where n is the number of an ulti to the stream but I'm involved because of these line here the line territory because every leaf in this load we have to traverse the current path to build a in tis here in this result horrible so yes that's why I'm not sure is we go open if you know please put in the comments and the memory complexity here if we do not count the current path and the result horrible is Big O of H where H is the height of the tree because of the recursive calls so that's it guys thanks for watching
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
643 |
so hello everyone i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product-based company so let's notch product-based company so let's notch product-based company so let's start with the problem today we look at this problem maximum average sub array 1 so we have been given an integer of array nums which consist of n elements and an integer k and we need to find the length whose maximum average value is whose average value is maximum and the size is k so let's try to look at the test cases so let's say if we have been given 112 minus 5 minus 650 and 3 and k is given to s4 so we found a maximum sub array average for this uh sub array that is 12 minus 5 minus 6 plus 50 okay that is this one okay so uh let's look at this problem in a bit more detail okay so basically it's a category of fixed sliding window uh so in order to optimize our n square solution we use this technique to get our answer in o n time okay so in this let's say we have this array okay one two let's say minus five six eight anything so for k sized window let's say k is three so we traverse and we calculate this length for every step that is first it will calculate for this then it for this and likewise okay so in that case we need to find the maximum average value sub array so basically it's an easy problem but just we need to find a slide we need to use the sliding window technique here so let's code this one and it will give you a better insight okay so let's declare a variable that is double answer is equal to zero fine and n will be sum of the first k elements and store our result so the sum of the first k elements will be sum is equal to the nums of i okay and we'll store our average fine so our answer will be nums my divided by k okay and we'll just explicitly make this as double okay fine and let's traverse the array again for the rest of the elements that is i is equal to 0 i less than i plus k minus 1 okay this is for the remaining elements and here what we do we calculate the sum plus equals to nums i plus k minus 1 minus of nums of i minus 1 we reduce the first elements okay and here we are calculating answers equal to max of answer comma double type casting okay and we do a sum divided by k here and this will be our final result and what we'll do we'll just return our answer so uh let me quickly explain what i did firstly we calculated the average of first k elements okay the first k elements and then we in the latter loop we travels for the rest elements and we store the answer and we compared it with the max that we have got correctly so let's try to run this yeah uh so this should run fine and i just added this max condition for double okay so let's try to submit this so yeah it got accepted and on submission it's also accept so that was it about this uh we'll meet you in the next lecture until then please like share and subscribe you
|
Maximum Average Subarray I
|
maximum-average-subarray-i
|
You are given an integer array `nums` consisting of `n` elements, and an integer `k`.
Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted.
**Example 1:**
**Input:** nums = \[1,12,-5,-6,50,3\], k = 4
**Output:** 12.75000
**Explanation:** Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
**Example 2:**
**Input:** nums = \[5\], k = 1
**Output:** 5.00000
**Constraints:**
* `n == nums.length`
* `1 <= k <= n <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Sliding Window
|
Easy
|
644,2211
|
343 |
and in female Betim a part of internal bodyguards there interpret but I can't also Break which I called Christ I may have maximized correct that he's more sane here in front Benfica the even more beautiful woman isn't it who knows television reading there's that one to celebrate this birthday school so I don't even remember where everything kimberlito can coolest court shine nor North am it does n't say where it's called there and it's for minors in London or diagonally in the new product store shred I didn't even clean it you have samba too what can be where tribes for business in the knitting area in the showcase of the world tri Porto Alegre hotel tailor-made Alegre hotel tailor-made Alegre hotel tailor-made way something for I'm going with the environment Where does it read that if not from her I don't know if there is Turma da Mônica Bernardes didn't call me no Ethen the matriarch where logically was born I wouldn't have a wall between Tom and I'm still not proud to see the fight between the agreement p********* Braga Where are you Hi inaugurates new girlfriend fight romantic Hi Helena decrees from Rick clip more than for sure and it didn't even become Cola no but it's not leading the big no but I can't it's not just a 44 year old man in a paw who is not in love with one when she old like the flu The fig tree of the symbol of the year no arrival uniform Ah don't respond at the right time Don't eat viola don't look how much the number house costs this technology in São Lourenço in a new film about national or see that's not where it is
|
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
|
703 |
hey everyone today we are going to substitute for the question case largest element in your Stream So design your class to find the case largest element in your stream note that it is a case largest element in the solid order not the case distinct element Implement case largest cross so case largest taking a digital k and a list numbers initialize the object with a integer K under the stream of integer norms taking a interval so appends the integer bar to the stream and return the element representing the case largest element in the Stream So let's see the example so you are given 4 5 8 2 and so this three is a I think a k so we should return the like a third largest element in the Stream so if we are the three to this input array so we should return four because um third largest element is four okay eight is a largest and the second largest is five and the third largest is four so that's why we should return four and then we remove four and we are three and then next we are the five in the case other five here are the five Alpha 5 and then should be um 8 is the largest and this five is a second and this five is a size so that's why we should return five and then another 10 and then in that case uh 10 is the largest element second is eight and the solid is five so that's what B should become five before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example four five eight two and then k equals three so that means we should return third largest element in the Stream so to solve this question I think there are a lot of ways to solve this question so one way is a sort input stream and then iterates through the stream from the end and then find the southern statement and then the time but that solution should be uh n log n for sorting and they're searching for with a order of n so can we do better actually yes so my strategy is to use Heap so that we can add new value and return the cell largest element in the Stream with order of log n so how can we solve this equation with a heap so in the initialize method and so first of all we create a heap with this input stream and then after that so in this case we should return third largest element in the Stream So that means in this case 4 right so that's why um two is actually out of scope value because this is a false largest element in the Stream so that's why um pop 2 from a heap and then keep four five eight in the Heap so what I'm trying to say is that so every time I keep the value with number of K so that means three so that we can find a third largest element in the Heap easily right so because we have only three number in the Heap so in Python so Heap is a usually mean Heap so in this case um like a pole five eight something like that so root note is uh or I can always sub element satellite state element in the Heap and then um add so let's say R3 to Heap and then so what happened I think uh first of all add three here and then um so sorry three is a minimum number in the Heat current Heap so this three goes as swaps the 5 and C so 5 is here and then threes go up and then compare four and three and the three is a smaller than o so that means four is here and the three it here so that is a ad operation and after that so as I told you I have to keep the value with the number of K so which is 3 but we have 4 here so that's why um until we have three elements in the Heap so in this case uh pop C from Heap and then after that um 5 is go to root node and five and then but the five is a greater than four so that's why these two numbers are switched solve root nodes should be four the left side is five so now four five eight so after that just return root node before so that we can return the like a third largest element in the Stream and then now let go four five eight five two Heap and then so 5 is here and then um so this hip looks good and then after that we have to keep three elements in the hip so but we have now four Heap so that's why uh pop from root node here and then five is going to root node and then so we don't have to change anything so that's why in this case we should be down five yeah so that's how Heap data structure works okay so let's write a code first of all save dot k equal okay the serif DOT numbers equal numbers and then create a heap so Heap queue dot P pi and the self Dot dot nums and as I explained earlier um we have to keep values with like a number of K in the Heap so link this of Heap is greater than self dot k in the case um Heap Q dot Hip Hop and the serif dot numbers so this is our initializer and then let's implement the other method so first of all add a value to Heap so Heap Q dot Heap push and self dot nums and uh and then after that if things of Heap is greater than the serif dot k in the case Heap Q dot keep up and then serif dot nums after that we should return serif dot numbers so in this case we don't have to pop element from Heap just Peak so how can we pick the root node so it's easy just a set index table yeah that's it so let me submit it looks good and the time complexity of this solution should be for initializer order of analog K so where N is a length of nums and the K is a value of K so this is a because Heap operation takes on time and the Heap pop in the while loop is performed K times so each taking a order of log K time so that's why total time should be order of annual gate and therefore other method order of log k so that's because uh Heap push operation takes order of locate time and if things of cell phone numbers becomes greater than k so Heap pop operation is performed with also order over okay so that's why um other method should be order of road gate and the space complexity for initializer order of K so because a heap in the end Heap is a has a like a k element number of K element so that's why um space complexity should be order over k and the other method so in this case it doesn't use any like additional space so that's why our order of one yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Kth Largest Element in a Stream
|
kth-largest-element-in-a-stream
|
Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
Implement `KthLargest` class:
* `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
* `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream.
**Example 1:**
**Input**
\[ "KthLargest ", "add ", "add ", "add ", "add ", "add "\]
\[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\]
**Output**
\[null, 4, 5, 5, 8, 8\]
**Explanation**
KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
**Constraints:**
* `1 <= k <= 104`
* `0 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `-104 <= val <= 104`
* At most `104` calls will be made to `add`.
* It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element.
| null | null |
Easy
| null |
7 |
Fifth, my name is Ayush Mishra and you have given this dress to Nishan. Today we are going to talk about our second problem on the list, the name of the problem is our reverse entry. This is the last problem. We looked at all the names that without VPN. Click on our I button and do n't forget to subscribe here Question Ghr means ghee can be absorbed that Thursday subscribe must subscribe set by reversing all its deletions we call it if on reverse it if it is in the range of 32 bit If it goes out of 1 - 30 then the if it is in the range of 32 bit If it goes out of 1 - 30 then the if it is in the range of 32 bit If it goes out of 1 - 30 then the simple element is to be desired. On reverse, if it goes out of this range - If you want Subscribe Meghnad - 1 - 30 - If you want Subscribe Meghnad - 1 - 30 - If you want Subscribe Meghnad - 1 - 30 hatred then one of my 1200 Ghr is given in that range you should pay attention. Apart from that, neither is it a simple question, what you say, I can tell you that if you want to reverse any anti aging then it is absolutely equivalent to you reverse some trick, now this is it. If I say you have to reverse ABC then it will be done directly whereas if I say put 1234 then it will be two one then what we do is that if we simply tell you first Albert tell you egg is soon first remove the subscribe it is said I took it out and kept it, then I gave it, A B C B Coming, this is my work, so he is telling me that it is also possible that he would like me to repeat it repeatedly, what will we do, we will top it, we will put the last digit in this and that. We will confirm, do something means go and put it, like I will put a spoon here on the barrier named after a person, I can also do this, that will work, okay, we will do it for open pores, so for you, these were alphabets, ABC, so we Screen made me a CEO from this, right now you guys are talking about it, Interior Milli, how will it be, I will cover it, I am taking 123 examples and degree, so if I tell you that 123 I have to find out the last date, then simple your You give it, divide it by 10, then now I divide it by 10, so 10:00 2128, divide it by 10, so 10:00 2128, divide it by 10, so 10:00 2128, okay, I got the daily value from here, so where did the digit come from, how did I do this now, neither media, whenever I have to take it out, how do you take it out? For that, write 5 minutes of intake, you will use planets present in 123, 10th cover models and from 10, you will get morning people, you will always get reminder and at the same place, if you use divide, then what will you get? Question, this value will be 112, so understand one thing. If the last digit is not taken out in the house of 123 then what will we do? We will take out the Mauritius then we will get the last rate. If we have to shorten that number then we will have to directly take out the grams of fenugreek. If you have taken out the number from 123 then next time you will need it. You had to remove it forever, if you change the third number while traveling in the train, you will change it by simply dividing it by two, this can be okay, it says sub division of train is fine so that you can use it, make the number smaller and click on it. If you can then it is very good, how much is an inter subscribe then subscribe 1000 find your diet 30 sim kitna gaya 3 gaya what will happen next time then our reverse is 12322 means 32.32 one reverse then you will not means 32.32 one reverse then you will not means 32.32 one reverse then you will not do it here because if you do it like this Don't subscribe to this channel. Like and comment. To remind you that if it is bigger than me, it is equal to itself. There was no minus sign in the first service of zero. I did not put it. First of all, what will we do to make him one of the villagers in this team? Person 123 If I show you, then the kind of meaning I have here, subscribe this channel to add this link to score, before our channel 20 and subscribe, mine was - before our channel 20 and subscribe, mine was - before our channel 20 and subscribe, mine was - 1 - To remind that the 1 - To remind that the 1 - To remind that the qualification went to the house. Gyanpur had given what we will do in this, we will do a base of absolute value of This is done of our beans - - - - 02 So it's about me beans - - - - 02 So it's about me beans - - - - 02 So it's about me to change that if the answer I have come if it is coming between - 2531 to 2531 minus one coming between - 2531 to 2531 minus one coming between - 2531 to 2531 minus one and if it is not coming then it is okay. So the return tax was 20 of our value pattern, so with me now you must have understood very easily that we have done the whole angle tax which can be reached in a very simple way and with this you will understand well if you York method is being used here. If there is any other logic then you can tell me in the comment section. Now if you have any diet then I will clear it then tell me. If you want to comment then my breath also you have understood the quote well. If it happens then it will be fine
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
282 |
welcome back to the cracking Thing YouTube channel I want to apologize for the lapse in videos my MacBook Pro died on me and by the time I got it repaired from Apple it's now been two weeks later so hence the lack of videos anyway we are now back and today we're going to be solving 282 expression ad operators so let's read the question prompt given a string num that contains only digits and an integer Target return all possibilities to insert the binary operators plus minus and or multiply between the digits of num so that the resultant expression evaluates to the Target value and note that operands in the returned expression should not contain leading zeros so let's look at an example and think about how we might solve this problem so we're given the nums one two three and the target six and we're essentially told you're allowed to place anything between the digits as long as it's a plus a minus or a multiplication and however you arrange you know those values it doesn't matter all that matters is that your final Target is six so I guess let's look at one potential answer here and we can actually see that if we multiply all the values we're going to get six so if we simply put multiplication between all the values we'll get 1 times 2 which is two times three equals six so this is one potential solution and what could be another solution well actually if we add all the values we can also get six right so we can get one plus two plus three uh and this equals six and note that even though we're using single um digits here we could actually do something like 12 plus 3 we could do something like 12 minus three um we could do one minus uh 23 so it we're not bound to just using a single digit right um so essentially what we want to do is we just want to figure out all of the ways that we can actually get uh you know our Target value here and unfortunately there really is no trick to this question what you want to do here is just um you know Adept first search and with some backtracking to generate all possible values so essentially what you're going to do is you're going to start at the first value and you're going to say okay what are the three paths I can take from here on the next value right and there's actually four paths and we'll see why so we can say okay with the one on the next value we can do one plus two or on the next value we could do one minus two and then on the next value we can do one times two I then continue on right so we can have one plus two and then we could do one plus two plus three we could do one plus two minus three we could do one plus two multiply by three and on until we you know exhaust all of our values and then at the end we can actually evaluate all of these Expressions so this is uh six here this is going to be zero so obviously that doesn't work this one is going to be uh seven because we want to deal with order of operations so what we do is just we build all the possible values and at the end we're going to check whether or not they equal our you know value here and if it does then we can add it to our result and we're good to go so the way that we want to do this is we want to like I said do a depth first search and we're going to be using some backtracking here to basically explore all the possible options and what we need to do is we need to keep track of you know our current index because that's going to tell us where we currently are right so we need to keep track of our index pretty straightforward what else do we need to keep track of well we need to keep track of the you know solution that we've built so far right so here you know if we were at the point where we're doing the three our solution state so far would kind of look like the string one plus two right so we need to keep track of where we are at each stage so we're going to say the current result is what we want to keep track of right we want to keep track of our current result and we also want to keep track of the current sum because obviously we don't want to be evaluating um the sum every single time we kind of just want to be doing it on the fly as we go so we're going to say the current sum and that way when we get to the end we don't then have to sum over everything we can simply um just check whether or not the current sum equals the target so and then the current uh number is the last thing that you want to keep track of obviously we just want to keep track of that and the reason that we actually want to keep track of the current number is because you have multiplication and with multiplication unfortunately we're Bound by the order of operations right so if we were going left to right obviously we would process the one and the two first so technically we would have added three and then if we multiply by three we'll get nine but we know that our solution is seven because we need to actually multiply the two and the three first and then add the one which gives us the seven so the reason we need to actually keep track of the current number which when we get into the next iteration will be the previous number is that we would need to undo any sort of um addition that we did before and then we would multiply our current number times the previous number to get that result and then we'll add back the value that we had added previously and this is only in the case of multiplication if it was just PL um addition and subtractions problem be a lot easier but unfortunately uh we have to essentially keep track of um you know the multiplication case here so we are going to need to undo any sort of addition or subtraction that we may have done in the case that we have that and one last thing that we want to be careful of is this thing here right we don't want to have anything uh that contains leading zeros and what might that look like say our numbers are 105 right and we know that we could split this like one plus zero plus five that's fine we can split it like ten plus five but what we can't actually do and if we kind of make some more space here we can't say one plus o5 this is not a valid number we cannot do this because obviously the numbers should not contain leading zeros so we're going to need to add a check in our code to actually make sure that if we have a zero then we want to force um you know going on to the next value we don't want to accidentally keep parsing it as if it was one number right so if we had like one two three we could parse the one but then we could also build a two out of it and then make it 12 and then add the three right we can't do this when we have a zero because again we cannot have leading zeros so we can't do the same thing that we did with the 12 here um and you know similarly if we did one plus two we could then make that two into a 23 if we wanted but again we can't do that with the zeros here so that is how we want to solve it conceptually really but what we're going to do now is we're actually going to go to the code editor because I think it's going to be a lot simpler this question obviously it's a depth first search with BRAC tracking so there's a lot of possible options that we could take here for each path we have basically four routes that we could take and essentially we want to uh you know enumerating this for all the possible values it's going to get real messy real fast and it's easier for me to actually just go into the code editor type this up for you guys uh anyway I'm going to stop rambling so I'll see you in the code editor momentarily let's type this up back in the code editor let's type this up and it looks like Lee code actually has a new UI here it looks pretty clean I kind of like it what do you guys think let me know in the comment section below anyway let's get into the problem and the first thing that we see is that we need to return a list with all of our results here so let's define that variable and we're just going to say res is going to be an empty list now we actually want to Define our DFS function and I guess before we do that we can just return res at the end right cool so we know that our DFS function basically needs to do all of the work so we're going to say def DFS and remember the things that we're going to take in is going to be our current index we're going to take in our current result we're going to take our current sum and we also want to know what the previous value was right and remember the previous value is the cases where we actually need to do multiplication and we need to undo any previous addition or subtraction that may have happened because order of operations okay so the first thing we want to do is actually check that we haven't overran our number here so we just want to add a check that our index is still valid because we don't want to get any sort of index errors so we're going to say if the current index is actually greater than or equal to the length of num then what we want to do is we want to check if the current sum equals to our Target then we know that we found a solution so we want to say res dot append and what we're going to do here is we're going to basically um you know join together our current result and we're going to join the current result and we will add that to our result cool that's what happens when we have a solution and you know at this point we need to return because obviously we're still in this if statement so we don't want to continue going further so now we need to do the else clause and what we need to do here is we need to build out all the possible values right so say we had like one two three we need to build out one we need to also do one and two and we also need to build out one two three so we need to basically go through all of those possible values and then explore all of the sub problems inside of it like I said this is going to be a depth first search problem with some backtracking so we need to keep track of basically all the possible options that we can go down so we're going to say 4i in range uh from our current index to the length of num we're going to say that the current um you know value is going to be the num uh so we're going to parse the current index so we're going to say Cur idx uh from our current index plus one and the reason that we want to do this is remember that we're we can possibly parse out so if we had one two three we don't want to just parse out the one we can parse out the one and the two we can parse out the three you know if we had a lot more numbers we would just keep going so we don't want to just stop at the single digit we want to be able to parse as far as we can possibly go so that's the reason that why we go from the current index to basically uh index plus one so that's going to basically parse them all out so we're going to get the current string here uh obviously this is a string here so we need to basically convert it to an integer because we're going to be working with some sums here so we want to make sure that it's actually an integer so we're going to say the current num is just going to be integer of you know our current string right cool so we've now parsed uh you know our current number and now what we need to do is actually just explore all of the paths right so one thing that we need to realize is that we if we're at the very first number so if we had one two three obviously our current result is going to be empty because we haven't parsed anything in this case we don't want to be adding anything we just want to parse the first value and then move on because obviously we haven't done anything yet so we need to just parse that first value so we can continue with our functions so we want to check uh let's see am I inside my Loop so no we're going to say if not korres so if we haven't parsed anything yet this is our very first index so basically the index 0 in number what we want to do is we want to say DFS so obviously we're going to increase the index plus 1 and then our current result is just going to be that first value so it's just going to be um you know the current string uh and then what we're gonna do is you know our sum is just going to be the value kernum and then the previous value is just going to be kernel right okay so we passed that in and why is it giving me okay that's weird I should turn that off anyway that's what happens uh for the first value otherwise if we have any other value um we just want to proceed normally so let's do the addition case so obviously our index is still going to get incremented by one now what we want to do is we want to take our old current result and since we're going to be doing an addition here we actually want to do a plus here so we're going to add a plus and what we're going to do is we're going to add the current string and so basically we take our previous result we add the plus because remember our result needs to be actually a list of strings so we need to build out this result so this is basically kind of us doing like a string Builder here so we're going to say current res plus uh you know basically we're going to add a plus operator and then we're going to add the current string to basically keep building it out so right if we had like one in our current result then we want to add a plus and then we want to add the two if the number was like uh you know one two three right so that's what we're doing there so that is the part where we actually build out our current result now our current sum um essentially we're just going to take whatever the current uh you know the previous value was for the sum plus adding our current num to it pretty straightforward we're just adding our current value to the old value and what we're going to do now is we need to just update our previous value for when we go into the loop again and the previous value is just going to be our current number okay simple enough now what we need to do is we need to go into our DFS function and why is this yelling at me again prev um no it's right here okay this is weird um let's see if it just goes away on its own I don't know what leak code is doing I don't know how to turn this off this is the new UI anyway uh again we want to increment our value here so we're going to increment our value our index sorry and again we're going to do kerres and we're going to do korres and this time we're going to add to the list a minus operator and we want to add a curse string uh again it's going to do this exact same thing as the plus case except for we want to just add the minus here and again uh this time since we're subtracting we want to say the current sum minus the current number obviously we're doing um subtraction here and now the kernel will just be minus kernel in this case um and that's all we need to do so let us now move to the multiplication case which is the most complex case but luckily we have set ourselves up for Success here so again it's going to be the same kind of pattern we're going to instead of a minus we're going to add a multiply here and again we're going to add the current string pretty straightforward now what we want to do is we need to undo the result of any previous addition or subtraction that we may have had so we need to do that and the way that we're going to do that is we're going to say the current sum minus the previous value oops minus prev plus the current number uh plus the previous value and let's kind of Sanity check this so you guys can see that this works so say our number is one two three and say we had one two and now we're going to multiply by three right so our result up to this case should be three and we want to multiply by three now right and this would give us 9 which we know is not correct because order of operations says that it should be seven so let's think about what our current sum is right our current sum would be three and the previous value it would be two so what we're going to do here let's look at okay what's the current sum so 3 minus 2 and what we're going to do right obviously that equals one and to one what are we going to add we're going to add whatever the current number is oh this should be um multiplied sorry multiplied uh we're going to add to it whatever the current number is multiplied by the previous so we know that the current number is three oops so we're going to say uh you know three times two which we know is six plus one this will give us seven so there is how you get that value and this is how it works so basically this part is undoing the last operation this part is applying the current number multiplied by whatever the previous number was and that's why we have previous in our function here we need it for this case here uh if we were just doing the um addition and subtraction we wouldn't need it but unfortunately because of the multiplication we need to keep track of previous so this is where it comes into play to basically undo the uh order of operations and make sure we get it the right way around so that is the actually we still have to basically Define the previous value so now in this case it's going to be kernam uh times the previous right so that's what we want to do um now what we want to do here is there's one last check that we need to do and that is again for that trailing zero so right for like 105 we can't have one plus o5 it either has to be one uh let's see one plus zero plus five or ten plus five we can't have this o5 here so we just need to check if we've actually started on a um you know a leading zero then we have to make sure that it's on its own we can't continue through this Loop here if the first value here I actually gives us a zero so we're going to add a simple check for that we're going to say if the current num of whatever the current index is actually equals to zero and remember that num is actually a string so we actually need to check for string equality here uh we just want to break out of this for Loop we don't want to continue making it right because again if we look at 105 what this Loop is going to do it's gonna get one or it's going to take 10 or it can do 105 and if ever we started on a zero we don't want to parse you know we don't want to do we want to do zero and five we don't want to do 05 because that wouldn't be correct because again the problem says no leading zeros so that is your DFS function the last thing we need to do is actually call the DFS function so let's call DFS so the current index obviously we start at the zeroth index obviously our current result is empty when we start so we're just going to pass an empty list our current sum we haven't done anything yet so it should be zero and the previous value should be zero because we haven't seen any values yet so uh let us run this uh hopefully I haven't made any mistakes because this problem is quite complex okay it seems to be accepted let us submit this and judging what happened Okay cool so we are done here uh that looks like it was accepted this is a new UI but okay it seems fine the solution was accepted and kind of got lost in the new UI but the last thing that we need to do is actually just talk about the time and space complexity so for the time complexity let's think about this when we go through our recursion there's actually four paths that we can take and it looks like there's three but let's think about this right we can go addition we can go subtraction we can go multiplication or we can actually choose to ignore the current operator and move on to the next one so this is in the case you know if we have one two three remember we can do like one plus two or we can do one minus two we could do one times two or we could simply ignore it and actually build twelve right and then go on with like twelve plus three uh you know 12 minus three yada so those are the four cases right we have the three here where we're actually adding the operator but one is implicit and that we actually just ignore the current number and move on so we can build a higher uh number from the next digit onwards so you have four cases and you know since this is backtracking you know this would basically be 14 oops uh let's see time what happened to my thing here okay it's gone uh so basically we have four cases so since it's you know we're calling it recursively from each one it's gonna be four to the N for the actual DFS part but we also need to recall that when we get to the end we actually need to call Dot join on our result and obviously dot join is going to take end time so our final time complexity is going to be um you know 4 to the N times n so quite a complex problem but as you saw the solution was accepted so you know it's not one where you can really optimize on this um you know it's just you have to generate all the possible options so for the space complexity I mean we just have our result here so our result is basically just going to be a big O of n you know the number of uh results that we actually generate is going to depend on how long our original string is um because that's going to determine you know all of the possible things uh you know in the worst case literally every single possible combination will add up to the Target uh and you know this is the worst case where actually all of the numbers in the thing are zero right so no matter what you do zero plus one zero minus zero times zero it doesn't matter if the target is also zero uh then every single possible combination of adding subtracting uh and multiplying will actually just give you zero so in this case uh the number of you know Solutions we have is going to be dependent on how you know law how many zeros we were basically given so that is why your space complexity here is actually a big O event so let's kind of just add the Big O's here Big O of M uh so that is going to be your time and space complexity like I said this question it's rated hard if you've never seen this before you're probably not going to come up with it definitely took me you know a few times actually looking at the official solution to figure out how this works but I think once you've seen it is quite intuitively simple I mean basically you're just building out all of the possible um Solutions here the only real trick is you know the fact that you can actually build um you know you're not just doing single digit things again you could have one two three and you could parse that as one two three or twelve um plus three or you can even have 123. so parsing that is uh one of the tricks you need to kind of figure out here also you need to know how to deal with the multiplication uh and then also to kind of check this Edge case for the leading zero but it does tell you that in the problem description anyway I'm gonna stop rambling because this video is probably 20 minutes long so that is how you solve expression out add operators definitely a good one to know I think it's asked let's see let's go back to the thing here where is it asked at Facebook and Google so if you have interviews at there um they might throw this at you because it's a hard question but it's not ridiculously hard like this is probably something within the realm of um you know something you'd want to be able to solve so that was the question uh hopefully you enjoyed this solution video if you did please leave a like and a comment it really helps me grow and pushes me in the uh YouTube algorithm subscribe to the channel if you want more content like this otherwise thank you so much for watching and have a great rest of your day
|
Expression Add Operators
|
expression-add-operators
|
Given a string `num` that contains only digits and an integer `target`, return _**all possibilities** to insert the binary operators_ `'+'`_,_ `'-'`_, and/or_ `'*'` _between the digits of_ `num` _so that the resultant expression evaluates to the_ `target` _value_.
Note that operands in the returned expressions **should not** contain leading zeros.
**Example 1:**
**Input:** num = "123 ", target = 6
**Output:** \[ "1\*2\*3 ", "1+2+3 "\]
**Explanation:** Both "1\*2\*3 " and "1+2+3 " evaluate to 6.
**Example 2:**
**Input:** num = "232 ", target = 8
**Output:** \[ "2\*3+2 ", "2+3\*2 "\]
**Explanation:** Both "2\*3+2 " and "2+3\*2 " evaluate to 8.
**Example 3:**
**Input:** num = "3456237490 ", target = 9191
**Output:** \[\]
**Explanation:** There are no expressions that can be created from "3456237490 " to evaluate to 9191.
**Constraints:**
* `1 <= num.length <= 10`
* `num` consists of only digits.
* `-231 <= target <= 231 - 1`
|
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators.
1 + 2 = 3
1 + 2 - 4 --> 3 - 4 --> -1
1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!)
1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
|
Math,String,Backtracking
|
Hard
|
150,224,227,241,494
|
242 |
hey guys today we'll be taking a look at valid anagram uh this problem is a very popular sub problem and uh variations of it show up a lot in more difficult lego problems all right so we'll be taking a look at the intuitive solution for this and then doing a slight bit of optimization to get to our final one which we'll start to then code out let's read the problem so given two strings s and t return true if t is an anagram of s and false otherwise so this is just going to be uh returning a by returning a boolean an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all the original letters exactly once uh now that points to the two lengths of the strings being the exact same we're using all the original letters exactly once and that means we don't have any duplicates we're not missing any so the lengths have to be the same so that's going to be a little edge case that we can already point out so in this example we have s equals anagram and t equals nagaram so uh these two have the same characters this is true even though t isn't different uh the characters in t are in a different order than an s you do have the same amount of characters and they show up exactly once so this is valid um let's say you had anna graham and if you had na gram missing this a then this would be false this would be not valid so let's take a look at how we would actually solve this so what we would want to do is we'd use a hash set or a hash map and in this hash map uh we'll just instantiate it as an object and the key value pairs are going to be the individual characters so the key would be like a um or like n um and the value would be their counts so a you see one two three times so this hash map would have a three times and n it would have it won two times um it would have n twice so that's what our hash map is going to look like um so what we can do is we're uh care count so we're going to set a hash map going through this would be string s and this would be string t so going through string t string s we can iterate it and every time we uh meet a character that we don't that we've not seen before so um our map is gonna start out as an empty map uh but we hit character a which we haven't seen before so we're going to set its count to one then um we'll keep going we hit character n which we've never seen before so we'll do the same thing set the count to one and then a we have seen before so if we have seen it before then we're going to increment it by one so this will be two um and then g r a m do that so on and so forth so this is what our hash map is going to end up looking like it'll have three a's one m one n one g one r and one m and then we can do the same exact thing for t where we'll set a new map um t and this would be like i guess map s uh and then we can do the same thing where we'll count all the characters for each one we will increase the count by one and so on and so forth and at the end you'll notice that uh the maps are actually going to contain exactly the same amount of characters so the key value pairs will be exactly the same even though they might not be in the same order so then what we can do is we can go through each map and we can compare the two uh to see you know if they're equal to each other uh but this gets a little bit tricky um and it's if we're looking at the complexity let's take a look at the complexity of the solution here so the time complexity um we're only doing two for loops or we'll end up doing three for loops at the very end so we'll do a for loop for um s the character is an s and then we'll do another separate um not connected for loop for all the characters in the t string and then we'll do another character array for all the uh we'll iterate through the new hash map uh that contains the characters and accounts for both of these elements so um we'll have this new hashmap but uh a caveat of the problem is that it only contains lowercase english letters which means this hash map can be a max size of 26 which is constant and not really something that we want to consider so the only thing we have to worry about for this time complexity are these two for loops right here um we'll say that these are going to be size n which means that we'll have big o of 2n which simplifies to big o of n so this is linear time which is not that bad then we can take a look at the space complexity for the given example above we've set two hash maps so we're going to create a just two hash maps so we'll have o of two times something we know previously because they're only lowercase english letters we can only have up to 26 so we have o of 2 times 26 which is a constant and that just simplifies to one a better way to approach this problem though we can actually get rid of this two and just end up using one hash set so i'll show you this solution right here right so we have a string s anagram and string t nagaram and we are still going to set a hash map uh counting all the characters because we know that they're the same length if we iterate through uh four then the index i that we're at is um always going to exist at the in the t array so we can just consider uh one iteration we're iterating through four um we're iterating through the link this s array now whenever we see a new character at index i that we haven't seen before in s then we can continue doing what we've done which is incrementing it we can increment it we can set it to 1. but for t what we'll do if we've seen a character that we haven't seen before at index at this same index i we've seen n and what we'll do is we'll decrement the characters in t so n will be negative one and then we'll move on and we'll let i be uh over here and then we see that there's an n in s which we will increment and this becomes zero and an a in t which we will then decrement now this becomes 0. and you'll notice that if we go through the entire length of s array and the entire length of t ray and they have exactly the same characters then no matter what order at the end they should all be equal to zero and that's how we're going to solve this problem at the very end we'll iterate through the map and then figure out if anything doesn't equal zero or return false the time complexity is still going to be big of big o of n and the space complexity is still going to be big o of one but all this does is uh it shrinks it from two times 26 just to 26. so it's a little bit optimized now let's get to the code and see how this actually works so remember the first thing we have to do is set the edge case and that's if either of their links aren't equal to each other so if s length is not equal to t.length then we can just return to t.length then we can just return to t.length then we can just return false off the bat now we're going to look at the actual conditions so we'll let a letters equal an empty object and this will serve as our hashmap of incrementing and decrementing the counts then we're going to iterate through the length of s array remember because their links are equal this means we can access all the elements of both character arrays and then for this we'll do two separate if else conditions so if letters of s i if this doesn't equal undefined then we'll increment whatever's in it um else then we will set it equal to one and then our second input definition is going to be eight letters at t of i if that doesn't equal undefined then we're going to decrement it we decrement every single element of t and we increment every single elements count of s uh then t of i minus else letters at t of i is going to equal negative one uh and now if we iterate through the actual map or a constant letter in letters uh this is going to take all the keys in this hash map then if this letter's at a letter if at any point the value pair for a given key is not equal to zero then we can return false otherwise if we've gone through the entire loop and we haven't returned anything that means they're all equal to zero which is true that's what we want so we submit this and this should work yep that's it
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
1,685 |
hey everyone today we are going to solve theal question sum of absolute difference in a sorted array okay so let me explain with this example 2 three5 in this case output is 435 so that's because we calculate like this so at index zero 2 - 2 + 2 - 3 plus 2 - 5 and index zero 2 - 2 + 2 - 3 plus 2 - 5 and index zero 2 - 2 + 2 - 3 plus 2 - 5 and 0 + 1 + 3 = 4 and index one 3 - 2 + uh 3 0 + 1 + 3 = 4 and index one 3 - 2 + uh 3 0 + 1 + 3 = 4 and index one 3 - 2 + uh 3 - 3 + 3 - 5 so 1 + 0 + 2 and three and - 3 + 3 - 5 so 1 + 0 + 2 and three and - 3 + 3 - 5 so 1 + 0 + 2 and three and uh at index 2 5 - 2 5 - 3 and 5 - 5 = 3 uh at index 2 5 - 2 5 - 3 and 5 - 5 = 3 uh at index 2 5 - 2 5 - 3 and 5 - 5 = 3 + 2 + 0 = 0 so very simple right and + 2 + 0 = 0 so very simple right and + 2 + 0 = 0 so very simple right and look at the this part and each calculation has zero so it means current number minus current number right so 2 - 2 and 3 - 3 and 5 - number right so 2 - 2 and 3 - 3 and 5 - number right so 2 - 2 and 3 - 3 and 5 - 5 so look at the position for other numbers so first example uh first I mean index zero so 0 + 1 plus index zero so 0 + 1 plus index zero so 0 + 1 plus three so we have one and three on the right side of zero right and at index one so 1 + 0 + 2 so we have one on the one so 1 + 0 + 2 so we have one on the one so 1 + 0 + 2 so we have one on the left side of zero and we have two on the right side of zero and look at the index two so 3 + 2 zero and look at the index two so 3 + 2 zero and look at the index two so 3 + 2 + z so we have three and two on the left + z so we have three and two on the left + z so we have three and two on the left side of zero right and so answer is 1 + 3 = 4 1 + 2 = 3 so one so answer is 1 + 3 = 4 1 + 2 = 3 so one so answer is 1 + 3 = 4 1 + 2 = 3 so one 3 + 2 = 5 so that means all we have to 3 + 2 = 5 so that means all we have to 3 + 2 = 5 so that means all we have to do is calculate um these uh two number in this case so that we can get a correct answer so we should calculate like a left total and right total from zero position that is a key Point okay so first of all let me calculate the left total so we call left total prefix sum so start with zero so because we itat from the index zero in the case so there's no left side right so that's why I start with zero but uh to understand my idea easily so let me explain when index number is one I think it's easy so in that case so prefix is an total of numbers we already met in the iteration so when index equal Z so we met two so that's why prefix is now two and then uh calculator left side so current index is one so current number so let's say n equal uh three right and the prefix sum is two so left sum should be um current number multiply current index minus prefix so let me explain U this formula so um how many numbers on the left of current number so now we are index one here so how many numbers we have on the left side just one right two so um that's why um so in this question uh so we have to subtract current number from each number right so that's why n multiply current number multiply index number should be like a total subtraction so the total number we should subtract right so in this case three multiply one and uh this is a total three right because we have only one number on the left side so three is a uh enough and then um so prefix is um current total number of left side so now two right because we have only two on the left side so total should be two right so that's why three minus two should be one right so um when index equal one so left total should be one and I look at the index one so now we are index one and the left total is one right so looks good to understand my idea easily so let me continue to calculate the left side so in solution code we calculate the left side and the right side in the same iteration so let's move next so index should be two current number is five and the prefix sum should be 2 plus three and five right so in this case at index two so we have two numbers two and three on the uh left side of current number so we need to subtract five from both numbers so that's why we need to um so current number is five and we need two right so five multiply two and then uh we already met two and three um so prefix is now five so that's why subtract current left total so five so in this case answer is five right and I look at the index two so we are now here and there's no um number on the right side and I look at the left side so um 3 + 2 is five right this is five so um 3 + 2 is five right this is five so um 3 + 2 is five right this is five and we get five from this formula so looks good now I hope you understand how to calculate left total so uh let me uh calculate quickly so when index equal Z so now index equal Z so current number is two so prefix should be zero right so in this case um so two multiply so we don't need a two right so Z minus Z so 0 minus 0 is z right so look at the index zero so now we are index zero so left side of course z right there's no number so looks get okay next so let me explain how to calculate the right total so we call right total suffix and initialized be is 10 so this is a like a total sum of input array so 2 plus 3 + 5 is 10 right input array so 2 plus 3 + 5 is 10 right input array so 2 plus 3 + 5 is 10 right and the current index equal zero and the current number is two so we use suffix sum to calculate a right sum of current index so suffix sum is total number of right side including current number and uh so actually we apply almost the same idea to uh light total so in this case how many numbers do we have on the right side so simply we subtract current index number from total length of input array so um okay so now we are index Z right here so in this case um total length of right side should be so 3 - 0 length of right side should be so 3 - 0 length of right side should be so 3 - 0 = 3 right and when index equal 1 so 3 - = 3 right and when index equal 1 so 3 - = 3 right and when index equal 1 so 3 - one equal two right I mean 3 five so this three stands for like a 2 three5 and when index two minus 2 equal one so this stands for five right easy so let's calculate the right total so now index equals zero and the current number is two so our right and total should be right equal so suffix minus current number so n multiply length of right side so reng and then so nums input array is nums minus current index number so it's almost same as a prefix right so uh we need to subtract current number two and multiply so length of right side right so in this case um three minus um zero so multiply three and the suffix is now 10 so in this case 10 - 6 = 10 so in this case 10 - 6 = 10 so in this case 10 - 6 = 4 and uh in this case uh we calculate the index zero so look at the index zero so now we are index zero so look at the right side of zero so 1 plus three and we get four right so looks good and then um move next so now index equal one and uh current number is three and uh we start from index zero so every time we move to next index so total of right side should be smaller right so on the other hand left side should be like a bigger right so now total 10 and we move next so right uh range should be three and five right so that's why we need to subtract two from 10 so suffix is now eight so uh we calculate the same thing so suffix is now 8 minus current number is three multiply 3 minus current index is one so two right so 8 - 6 equal two is one so two right so 8 - 6 equal two is one so two right so 8 - 6 equal two so look at index one and we are now index Z one and on the right side we have only two so we get two looks good and then um so we move next so before that we subtract three from eight so now suffix is five and current index equal two and the current number is oops five and then um so now current suffix is five minus current number is five multiply um current index is now two so one so 5 - 5 equal Z so right side one so 5 - 5 equal Z so right side one so 5 - 5 equal Z so right side should be zero so look at the index two so now we are index two yeah of course there's no number on the right side right so that's why zero should be fine yeah that's how we calculate the right total so in the end so when we calculate the left side so in at index zero so zero and index one is one and index two was five and the plus so when index zero right side is four and when index one uh right side is two and when index two right side is zero so that's why 4 3 5 and 435 so all numbers are same looks good yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's WR the code first of all insert result variable with list and the prefix sum equal start with zero and suffix sum equal so sum of all numbers so nums and then start iteration so for I and num in enumerate and nums so we take a index number and a current number at the same time so calculate the uh sum of element to the left of the current element so oops left sum equal so n current number multiply index number minus prefix sum and then calculate the right sum so right sum equal so suffix sum minus parent number multiply length of right side so length of nums minus index number and then so total should be so total sum should be just left sum multiply right sum and then just append total sum so um yeah actually you can uh write like this we don't need total sum like this and then update um like a prefix sum and a suffix sum for the next iteration so as I told you when we move next so prefix sum should be bigger so plus equal num and the suffix sum should be like a smaller so fix suus equal n oops num yeah actually that's it after that return um less yeah so let me submit it yeah looks good and the time complexity of this soltion should be order of n because we iterate through all numbers once and the space complexity is I think1 except this result variable so we use simple variable prefix sum suffix sum yeah so except this result variable um this solution is like a o space complexity this is a stepbystep algorithm for my solution code I hope it will help you understand my solution code DE yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
153 |
hey what is up guys welcome back to another Elite code video today we are going to be solving find minimum and rotated sorted array um if you haven't already be sure to check out the search and rotated sorted array video that I put up um because it'll definitely help you get a better understanding of how we're going to approach this problem um so for this problem it says that suppose an array of LinkedIn sorted in sending orders rotated between 1 and N times um as you can see in the example here we have zero at the beginning in the original array and if it's rotated four times you can see that it basically gets shifted four elements over and the same happens for every single element in the array so given this rotated sorted array the problem wants us to return the minimum element of the array and it wants us to write an algorithm that runs in log n time so basically we are going to be doing binary search because obviously with log n time constraints we can't do a linear search on the array um so if you look at the example we have an array of the numbers three or one through five rotated three times and the output is one because one is the minimum so here we have our example um that was seen above and actually before we get into searching in a rotated array I wanted to cover a fully sorted array or in other words an array that's been rotated n times if you take this sorted array and you rotate it five times you're gonna cut you're going to end up with the same sorted array right and so we were to perform binary search on this perfectly sorted array well we know that our minimum element is just that leftmost element right it's the smallest one and the sorted um array so that covers that special condition and now we're going to get into if the array was rotated so again with binary search let's say we have our middle pointer here at this five and then we have our right pointers has a two and a left pointer at the three well the first thing we'd have to do in searching when searching uh in a rotated array is check which uh which sorted portion are we on because we know that at any time in the rotated sorted array there is a left sorted portion and a right sorted position right so for example the right sorted portion is here the left sorted portion is here so just from this visual we can see that we as far as the middle pointer we are in the left sorted portion and so now the question is where do we search well we know for a fact that if the array is rotated and we are in the left sorted portion we always want to search to the right because we know that the at least from this drawing we see that the minimum element is in the right side and we can also actually see that the leftmost element in our sorted side in the sorted left side is greater than the rightmost element and the right sorted side which basically tells us we want to search this right portion so I wanted to redraw this example um to see what would we do if we were in the right sorted side or if the sorted side that we are in is on the right portion so let's say we have our middle pointer here right pointer and our left pointer again so we know that we are in the right sorted side because this left side isn't even sorted to begin with right so where do we search do we continue to search further into this right sorted side or the left sorted side well in this case we would actually want to search this left sorted side because for every number that our middle pointer hits we are going to compare that to our current minimum remember we are searching for the minimum element in the array so when we compare this element this 2 so say that this 2 now becomes the minimum right well we know that every element sits this right sorted side this right side is sorted we know that every element to the right of two is just greater than two it's just going to be increasing there's no possible way that we can find the minimum element by switching further into that rotated right side so by default we are going to search this left side and uh basically that same concept applies here right so hypothetically if we had something like this and we know that we are in the right rotated side even though we found the minimum which is one right so we know that one is the absolute minimum um or sorry let's actually say our left pointers here and for whatever reason our Middle Point is here we know that one is the absolute minimum right um even then our algorithm isn't completely finished so what we need to do is search this left side because we know for a fact that every uh number that comes after this one is going to be greater than one so there's no point of searching for the minimum further to the right because we know that it's increasing because this we know that we are on the right side which is the sorted side and so with that being said then we search to the left so to basically conclude the three main conditions for our algorithm um we have the fully sorted array and not basically non-rotated or rotated end basically non-rotated or rotated end basically non-rotated or rotated end times in that case if you just return the leftmost value right um and then we have a rotated sorted array if we are in the left sorted side and all we do is search to the right and if we go in the right sided side then all we do is search to the left and that's pretty much how the algorithm is going to work um and with that being said we are going to go ahead and get into some code all right so remember since we are running binary search we need a left and right pointer and now we need a variable to store or keep track of the minimum element now remember our first condition is if the search space is fully sorted then in that case all we would have to do is check the leftmost number against our minimum and then break out of the loop otherwise if that's not the case then we would continue with our binary search initializing our middle pointer and then checking the element at the middle against our minimum element and then remember if we are in the left distorted search space or the left sorted side if our middle pointers in that left sided side then we would simply want to check the light side and then if we are in the other case that we are in the right sorted side we could simply shift our right pointer to shut Dot left side then after the binary search ends all we have to do is return our minimum element and that pretty much completes our algorithm um just to verify that this works I'm going to go ahead and run it as you can see it works perfectly
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
9 |
hello everyone today we are going to solve the lead code question number nine pale androme number given an integer X return true if x is a pantr and false otherwise we are given an example here where X is 121 if you reverse 121 it will be again 121 so it is a pant Drome so we are returning true there is another example given here x is - here x is - here x is - 121 so if we reverse the integer it will become 121 minus which is not a p androme so we are returning false and there is another example given here where X is 10 so if you reverse the integer it becomes 01 is not a p andr so we are returning false we are given a followup here it is mentioned that could you solve it without converting the integer to string I hope the question is clear now let's get into the approach the first step of the approach is if the number is negative we can immediately return false because all negative numbers cannot be a pale androme if the number is a positive number we can first reverse the number and compare the number with the reverse number if the both number numbers are same we can return true else we can return false for example let's assume that our number is 121 and we can initialize reverse number as zero as a first step in order to reverse this number we have to find out what is the last number in our case the last number is one of the approaches of finding the last number is finding the mod in this case is 121 mod 10 is equal to 1 the mod function Returns the remainder now let's assign remainder variable to one now we can use this formula reverse number equals to reverse number * 10 plus remainder in our case number * 10 plus remainder in our case number * 10 plus remainder in our case reverse number is 0 so 0 * 10 is 0 + 1 reverse number is 0 so 0 * 10 is 0 + 1 reverse number is 0 so 0 * 10 is 0 + 1 is equal to 1 now we got the last number which is one in the verse number the next step is to chop the number one and we need only the number 12 one of the ways of finding the number 12 is to do integer division so 121 / 10 is equal to integer division so 121 / 10 is equal to integer division so 121 / 10 is equal to 12 in Python to do integer division we have to use double slash now we will initialize 12 as our number so 12 becomes our new number now we will repeat the same steps again so in our case the number is 12 and the reverse number is one in order to find the last digit we do 12 mod 10 which is equal to 12 and we are assigning two as our remainder so two becomes our remainder and we will use our formula reverse number equals to reverse number * 10 number equals to reverse number * 10 number equals to reverse number * 10 plus remainder in this case 1 * 10 + 2 plus remainder in this case 1 * 10 + 2 plus remainder in this case 1 * 10 + 2 is = 12 so our reverse first number is = 12 so our reverse first number is = 12 so our reverse first number becomes 12 now we have to remove the last number which is two in order to do that we are dividing 12 integer Division 10 is equal to 1 so we are bringing one as our new number now our new number is one and we are repeating the same steps again our reverse number is 12 in order to find the remainder we are doing mod operation 1 mod 10 = to 1 which is our operation 1 mod 10 = to 1 which is our operation 1 mod 10 = to 1 which is our remainder now we have our reverse number and our remainder and using our formula we are finding the reverse number our reverse number will be 121 now if we integer divide 1 by 10 the answer is zero so we are bringing zero as our number our new number is now zero once we reach zero we will compare the reverse number with our original number if both are same we will return true else we will return false I hope the approach is clear now let's get into the implementation as a first approach I'll solve this by converting the integer to a string return string of x equals to string of X in Python we can reverse the string using this operation colon minus one we are converting this integer to a string and then we are reversing this integer if both are same it returns true else it returns false this is one way of solving this problem since in the question it is mentioned that we should not convert the number to a string we will solve this without converting the number to a string let me command this as a first step if the number is a negative number we will immediately return false if x less than Z return false then we will initialize the variable reverse number equals to Z before we per perform the reverse operation we will assign the value of the number X to a variable y = to a variable y = to a variable y = to X we will iterate until X is greater than zero while X greater than Z we will find the remainder equals to X Mod 10 Now using our formula we will find the reverse number equals to reverse number multiplied by 10 plus remainder now in order to chop the last digit we will do integer divide 10 x = digit we will do integer divide 10 x = digit we will do integer divide 10 x = to X integer divide 10 now we will compare the number and the reverse number if y equals to reverse number return true else return false that's pretty much it now let's submit it the solution got accepted the time complexity of this approach is O of n where n is the length of X we are iterating through all the numbers of the X the space complexity is W of one because we are not using any extra space I hope you like this video and I'm sure that you learned something new today if you do like this video please consider to subscribe and I'll see you in the next video thank you
|
Palindrome Number
|
palindrome-number
|
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string?
|
Beware of overflow when you reverse the integer.
|
Math
|
Easy
|
234,1375
|
1,996 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1996 number of weak characters in the game before we get into the question you guys know the drill please subscribe if you haven't already and drop a like on the video it really helps me grow alright you are playing a game that contains multiple characters and each of the characters has two main properties attack and defense you are given a 2d integer array properties where properties of i equals attack of i defense of i which represents the properties of the ith character in the game a character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels more formally a character i is said to be weak if there exists another character j where attack of j is greater than attack of i and defense of i is greater than defense of sorry defense of j is greater than defense of i return the number of weak characters okay so let's look at this example where we have three characters uh and there are attributes are one five ten four three so let us see uh if there's any of these guys that are weaker so we know that to be a weak character someone has to have a higher attack and a higher defense so let's look at one five does anyone have a higher attack yes both of these guys have a higher attack than one but their defense also needs to be higher than five unfortunately these guys defense is actually lower than five so this is not a weak character right what about 10-4 is there anyone who has what about 10-4 is there anyone who has what about 10-4 is there anyone who has an attack higher than 10 no this one has an attack of one this guy has an attack of four so we know off the bat this guy is not a weak character what about four three is there anyone who has an attack greater than four yes this guy has an attack greater than uh four what about the defense of that guy is it greater than three it is so that means that this character is weak because it's weak relative to this one so in this example we would return that there's one weak character and that's our final solution so looking at this it's really easy to figure out how to do it but how do we actually solve this in a way that you know we can put into code so we're going to explore that momentarily so we looked at a basic example and it was easy to figure out how to find the weak characters when we're just looking at the array and we can solve it on paper no problem but how do we code this up so there's two approaches you can use for this and the first is going to be you can use a sort here and then compare uh the defense levels so you would sort based on attack and then you can so and then you can you know compare the defense levels unfortunately we know that any sort algorithm is going to be n log n and in this case we can actually improve on this uh because there exists a linear solution which is what we're going to go over so the solution that we're going to use is a bit weird it's called a bucket sort although it doesn't really involve any sort of sorting so what we want to do with this bucket sort is basically to group all of our um you know people into buckets and we're going to use a hash map for this so we're just going to say you know groups here is going to equal this hash map and the key of our hashmap is going to be the attack value so we're gonna bucket every single person based on their attack value so in this case the person one uh there is a person you know with the attack of one there's a per person with a defense of five uh with the ten there is a person with defense of 4 and with the attack of 4 there is a person with a defense of 3. so we're going to need to build this hash map by iterating over our properties from left to right and while we're building the hashmap we need to keep track of two things we need to keep track of the minimum attack that we've seen and we need to know what the maximum attack that we've seen and the reason for this is now that we basically have our buckets and we know what our minimum and maximum attack is we're going to run a loop which goes from max attack all the way down to min attack and what we're going to do here is we are going to essentially if there's someone in that bucket right because this is going to be a loop and we're going to be going through the keys of our groups here but obviously there might be some values that we get in this loop here that aren't actually in our groups array or sorry groups dictionary in that case we can just skip them because they're empty buckets but when we hit a bucket that actually has people so if we look at our max attack here it's going to be 10 and then our minimum attack is gonna be one right so we'd have a loop going from 10 to one and it's going to be backwards right we want to start from the top and we want to go from the bottom so this would be like range from 10 to 1 with increments of minus 1 each time and what we're going to do is we are going to count the number of people uh in this group who have a um you know defense level which is less than the maximum defense so we're going to start at the beginning and we're going to initialize our maximum defense to be -1 defense to be -1 defense to be -1 and what we want to do is basically we want to find all people who have a maximum whose defense is less than this maximum defense and the reason we can do this is look we're going backwards from max attack so that means that any element that we reach during this loop here we know that for sure there will be someone greater than us because we are basically going backwards from the max attack and max attack has to be defined so at any point if we hit a group here we know that for sure there's going to be a max attack greater than us and the reason that we start max defense at minus one is to handle the case of what happens when we're actually at the um the group here for the uh max attack because there's no possible way for someone to have a higher attack than us so simply we just wanna you know filter by people who actually within that group have a higher defense so that's why we initialize it to minus one and then as we go through the actual loop from max attack to min attack we'll be updating this maximum defense as we go down because we know that at any point between max attack and min attack if we flag that we actually have a group in our groups array then we know that for sure there's a max attack value higher but we need to keep track of the max defense that we've seen so far so we can make the comparison because remember you have to be greater in the attack and the defense so what we're going to do is we're simply for each group that actually exists here along our uh iteration from max attack to minimum attack we're just going to count the number of people whose defense is less than the maximum defense that we've seen so far and then we're just going to add that to our count variable right we're going to just add to count and then we're also going to update the maximum defense at each iteration right so max defense so we're just going to do the maximum and then whatever the maximum on that level was so to be like groups of level right and then we basically just do that until we exhaust this entire range and then we can simply return our count and we are good to go so hopefully that made sense if you've never seen a bucket sort algorithm before this may make maybe a little bit confusing but we'll go to the code editor and kind of write this out and you'll kind of see how it works if not go through the example line by line with this uh code and then you'll see how it works but basically a bucket sort you just want to put them into buckets and this way iterating from max attack to minitak is going to be linear we don't actually have to sort it and because you know inside of the loop we are making these comparisons but recall that the comparison is just going to be however many uh distinct attacks there are in our groups here so it's not like we're performing the operations within everything so it actually stays linear and we'll talk about this more when we go over the um the actual time and space complexity so i'm gonna stop rambling let's go to the actual editor and type this out and you'll see how the solution is gonna look okay we are in the code editor let's write this up so remember that we're gonna be using a hashmap here to basically store all of our groups so let's define that so we're going to say groups and remember that the key is going to be each attack and the value is going to be the number of or i guess the defense levels for that given attack so collections the default dict and we're gonna initialize it with a list now remember that we need to keep track of the minimum attack and the maximum attack and if we look at our constraints here we can see that the attack in the defense will be between 1 and 10 to the 5th inclusive so we can set our minimum attack to be equal to just one above the maximum so we'll say 10 to the 5th plus one and then we'll set the max attack to be equal to zero that way we can do our minimum and maximum comparisons so now remember that we and i'm going to close this to give us some more space now we need to go through the attack in the defense of each character's properties and basically it uh build out our groups um hash map and we also need to update the minimum attack and the maximum attack so we're going to say 4 four attack d defense uh in properties what we wanna do is we wanna say the minimum attack is going to be the minimum of the current minimum and whatever attack is and then we want to say that the maximum attack is going to be the maximum of whatever the current maximum attack is max attack and we also want to update the key for that attack value with whatever the defense is so we're going to say groups of attack oops groups of attack we're going to append defense to it because remember this is a list so that is going to be building out the groups now we need to actually do the iteration in reverse but before we do that we need some variables to keep track of our um result here so we're going to say the count of the weak characters is going to be zero because we haven't processed any yet and then the max defense is going to be set to -1 be set to -1 be set to -1 and remember this minus one is to basically check the case for if someone happens to be at the max attack which obviously they will because max attack will be defined uh once we go through this there will be a max attack so what we need to do is uh for the case where we have the max attack obviously we just need to find the smallest um we need to find people who have uh defense smaller than the maximum defense uh and obviously the maximum defense could occur later down in the grouping so we don't want to update this while we're actually going through here because it could potentially throw off our result we want to do it as we go through the actual array and you'll see in a second so we're going to basically go backwards from max attack to min attack so we're going to say 4i in range and we're going to go from max attack down to min attack minus 1 and we want to go to -1 and we want to go to -1 and we want to go to -1 increments of -1 so we're going increments of -1 so we're going increments of -1 so we're going backwards so now obviously the attack which is represented in this i may not exist in our group's uh dictionary so if it doesn't exist we're going to say if not groups of i so basically if there's nothing there then we can simply continue because there's nothing for us to do otherwise we need to do some work here so we're going to say count uh plus equals and what are we going to do for the count here we're going to sum how many times um we see a defense which is less than the maximum defense for every value in groups of i so we're going to basically say sum so one if defense is less than actually perhaps we can do this in a way that's friendlier to other languages so we're going to say for defense oops for uh let's just say let's just call it uh defense in uh groups of i we're going to say if this defense is less than the maximum defense then what we want to do is we want to say count plus equals to 1 otherwise nothing's gonna happen okay cool so this is just a little bit more friendly uh for other languages i was gonna use a list comprehension but obviously those are just for python so i figured i might do it in a uh other language friendly manner okay so now that we've calculated uh this count here and updated it what we want to do is now update our maximum defense um and what we want to do is we want to say the maximum defense is going to be the max of whatever maximum defense we've seen oops this should be max defense and whatever the maximum on that level was so we're going to say groups of i and this is going to run from max attack to min attack -1 in increments of minus to min attack -1 in increments of minus to min attack -1 in increments of minus one so we're gonna go from max attack to min attack minus one and at the end uh we just wanna return count so let me run this make sure i didn't make any syntax mistakes uh max def what happened here groups of i uh oops this should be maximum of groups of i that is not an integer okay cool that should do it now all right cool so let me submit this and once this runs cool we are good to go so what is the time and space complexity of our algorithm well let's break it into pieces here and i can get rid of this now you guys see it works so this first part obviously is going to be big o of n right we have to go from left to right over our properties array so this is going to take big o of n time but what do we do here with this second loop is it going to be big o of n as well not quite because there are not going to be uh n actual ranges here right it well in the worst case there could be but you know let's just say that there's k actual you know values within our groups here uh where k is like a distinct the number of distinct groups we have so that would mean in the worst case each uh attack property has its own you know group right so the each uh attack in our properties list is actually distinct which means that ever there will be you know k groups here where k is the number of attacks but each one will only have one inside of it which means that these operations will happen in constant time which means that we can basically think of this inside loop as uh you know constant time operation okay but what happens when everyone has the same attack well if everyone has the same attack we're only going to end up processing all the elements in this case so in the worst case um you know it the inside here would only run once so if all the attacks have the same value then we would run this only one time and then the rest would just get hit by this groups of i so we would never actually run anything so one iteration would take big o of n time and the other iteration would take um you know all of them would just happen in constant time because they would hit this uh if not groups of i because there would be nothing defined in the case where everything uh is in that one group but in the average case let's just say that there's k groups so this operation is going to take big o of k time to basically go through this so your time complexity is going to be big o of n plus big o of k where k i believe here is the number of distinct attacks that we have in our groups so space complexity wise um you know it's also going to be big o of k where k is essentially the number of distinct attacks that we have to store in our groups here so yeah that is going to be your time and space complexity for this problem not too complicated if you've never seen um you know bucket swords before it is a little bit weird um but typically you can kind of get away from sorting by um you know building these buckets and then iterating from whatever you know the maximum bucket to the minimum bucket was and as you can see we can bring down the um the time complexity here so that is how you solve this problem uh quite an interesting one i didn't think it was bucket sword at first i thought you had to sort everything uh normally but turns out there's a nice bucket sort solution so that is how you solve it if you enjoyed this video please leave a like and a comment it really helps me with the youtube algorithm if you want to see more content like this subscribe to the channel i have a lot more videos coming out soon otherwise thank you so much for watching and have a great rest of your day
|
The Number of Weak Characters in the Game
|
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
|
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105`
|
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,415 |
hello yours welcome back to my channel I hope you are enjoying all the problems that I am uploading but you haven't subscribed yet please go ahead and subscribe to my channel and share among your friends so today's problem is the Keith lexicographical string of all happy strings of length and a happy string is a string that consists only of letter set a b c that's one condition so the string has only three letters three kinds of letters a B and C the second constraint is SF I not equal to s fi plus 1 for all values of i from 1 to s dot length minus 1 string is 1 index right so basically if the string is 1 index then adjacent characters should not be same that's what it meant for example the strings ABC AC b a b c b that strings are all a p strings but a B BC are not happy strings because they have at least one adjacent characters in each of those strings as same right a so two are same look it's not a happy strain B a is again same it's not happy string so like that so that is the definition of the happy string and then the question is given two integers N and K consider the list of all happy strings of length and sorted in lexical lexicographical order written the Cate string of this list or written an empty string if there are less than K happy strings of length and so that's the thing so basically we like to come we will need to have the happy strings of length M so for a given length there could be several happy strings and of all those several happy strings we need to sort them in the lexicographical order and once we saw that whatever the set that we get in that we need to get the Cape happy strength right so let's go ahead and look at an example so out of all the examples here I think the example 3 makes better sense for us to go so n is equal to 3 that means the string length is 3 and K is 9 so of the 3 string length 3 there are several strings possible there are 12 strings possible in fact so out of the treble strings we have to give the 9th string right so that is what is the question that is being asked so of the length 3 let's go ahead and look at what are the happy strings right so in explanation it is given that a BA ABC AC a so these are all the happy strings of length 3 ok so and out of this the 9th string is C a B so that is what we are going to return so basically we need to have a list of all the happy strings and then we will be able to get the Keith string of the all the happy strength and n could be anywhere from 1 to 10 so that's what it is said and could be anywhere from 1 to 10 and K could be anywhere from 1 to 100 right so that is what it is so the algorithm that I have here is it is a two-step thing so one is it is a two-step thing so one is it is a two-step thing so one is it is going to construct all the happy strings of length whatever that is given as N and once we have all the strings it's pretty easy to pick one from it right so the algorithm that we are going to see is it will construct the happy strings first and then get the Kate out of it ok so that's the simple logic that we are going to use here so let me go ahead and show you the steps that we are going to do so we will build a string of length L and use it to build a string strings for length L plus 1 so basically if you have a string of length L we use that string and build strings of length L so on so essentially once we build all the strings right then we pick K minus one string from that because the list in c-sharp is zero indexed that's list in c-sharp is zero indexed that's list in c-sharp is zero indexed that's why we are subtracting K minus one from K so we will pick the K minus one string okay so case all the strings in that are all the strings in the given length R one index it was saying but we will say our strings are here in this case right whatever the data structure that we are going to store it will be a zero based index that's why we are subtracting minus one from the cake okay so we will start with a seed the seed is ABC as mentioned here right so now based on ABC by using this logic SFI should not be equal to s fi plus 1 we will construct length 2 so basically what we are going to do here is so we have we take the first two string a right so a and then we will be using the same set again the length ABC right so as long as this condition is satisfied from this we are going to happen so if we take a it will be equal so we won't take a and Evan here so we will take B and a pen so after append it will become a B right and for the same string after we append C it will become a C right so that is what is output for a and now similarly we do B right so for B if we do that right so B we can append a right so obviously for B we cannot append B because b and b doesn't mean there is a match so we cannot do next B and C right and let's go ahead and do it for C right so see we can append a that's one thing and see be within apparent right CeCe we cannot happen right si cannot be appointed to C because s fi is equal to s fi plus 90 become right so we cannot happen so now we have constructed strings of length 2 a b a c b a b c AC right so these are six strings that we got so now we are going to use the length two to construct length three and so on whatever the length that we were asked that is n right so that is what we are going to construct once we have this list right it is easy to pick whatever the Cate K minus one string right from this list so that's what the logic that I am going to use in the code so one more thing is if K is greater than whatever the number of things possible right for example if n is equal to 2 and K is equal to 10 let's say if that is n put for n is equal to there are only six strings possible right n is equal to there are only six strings possible which are happy so that's the reason why we will say we cannot go to ten K is equal to ten is not possible in that case what we are going to return an empty string that is what for the definition right return an empty string so in this case we will return empty right that is a that is one more constraint so here all the work I am doing here is get lexicographical strings and then if the strings count is K is less than the strings counted then we you return all strings of K minus one otherwise rate return empty string so that is what it is as long as the K is less than the count of the lexicographical strings you return it otherwise Ratana empty string so let's go ahead and look at the logic that we are implementing so it follows this logic what we have done from generating strings of length two from generating lengths of strings of length one right so it's similar exactly so the C data so the start is a seed data for us we are going to add three strings in here right so a B and C and I am storing all the ABC characters in a character array basic because we are going to use this character array to append to the strengths that we have in the start this is a seed data so we already have the strings of length 1 in start right so starting from 2 we are going to construct so that's why I'm I have I is equal to 2 eyes less than then I have plus right so that's what I'm going to do and then here the next set of strings that we are going to construct right so for each string in the start what we are going to do is we look through this character array and if it doesn't match this the last character that is added right it doesn't matter this the last character that is added we are going to add up in that string and add that string to the next set of strings to be looked at so basically since we have constructed all three for the strings of length 1 right so next we'll have the strings of length 2 so finally once this loop is done right we will be assigning the next to start again so in the next length we will be using the strings that we obtain in the next likewise we will be continuing right so this is how we are going to proceed to calculate the lexicographical happy strings once we have the lexicographical happy string right it's very easy to return what is the case string right so this is how we are going to solve this problem hope it is clear so there is there are more methods for this in order to not construct all the happy strings and but try to generate the kate lexicographical string right so I will probably upload another video or another variation of the same problem right so in another video but this in this video what I am covering is we try to generate all the strings and get the K minus 1 string out of it so I will probably create another video where we don't construct all these strings but still manage to generate the kate lexicographical string ok hope it cleared up all the questions if you still have any questions please leave them in the comment section I will get back to you as soon as I can thank you for watching just want to remind again if you haven't subscribed to my channel yet please go ahead and subscribe and share among your friends also click the Bell icon so that you get all the future video updates thank you for watching I will be back with another problem from Reed Corps very soon till then goodbye
|
The k-th Lexicographical String of All Happy Strings of Length n
|
students-and-examinations
|
A **happy string** is a string that:
* consists only of letters of the set `['a', 'b', 'c']`.
* `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed).
For example, strings **"abc ", "ac ", "b "** and **"abcbabcbcb "** are all happy strings and strings **"aa ", "baa "** and **"ababbc "** are not happy strings.
Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order.
Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`.
**Example 1:**
**Input:** n = 1, k = 3
**Output:** "c "
**Explanation:** The list \[ "a ", "b ", "c "\] contains all happy strings of length 1. The third string is "c ".
**Example 2:**
**Input:** n = 1, k = 4
**Output:** " "
**Explanation:** There are only 3 happy strings of length 1.
**Example 3:**
**Input:** n = 3, k = 9
**Output:** "cab "
**Explanation:** There are 12 different happy string of length 3 \[ "aba ", "abc ", "aca ", "acb ", "bab ", "bac ", "bca ", "bcb ", "cab ", "cac ", "cba ", "cbc "\]. You will find the 9th string = "cab "
**Constraints:**
* `1 <= n <= 10`
* `1 <= k <= 100`
| null |
Database
|
Easy
| null |
556 |
hey what's up guys this is john here so today let's take a look at uh today's daily challenge problem the number 556 next greater element number three so it's like a medium problem okay you're given like a positive integer n and find the smallest integer which has exactly the same digits existing in the integer and is greater than the value itself and if no such positive integer exists return -1 and also return -1 and also return -1 and also another constraint is that you know then the return value should be fit in the 32-bit integer if the fit in the 32-bit integer if the fit in the 32-bit integer if the value is greater than this 32-bit value is greater than this 32-bit value is greater than this 32-bit integer we also return -1 and here we have some examples but here i think the examples are really just a two sim uh very basic one so for example this one even is 112 and in order to get the next biggest number right i mean basically the only option is we have two one and for the case of uh of 21 there's no way we can get a greater number right by using the same integer same like digits that's why we return -1 yeah so i mean so if we only use these two examples i think it's hard to find some patterns here you know let's try to find another one let's say we have two three one zero one uh four um actually i would use this one five uh three one how about this one let's see we have this number here okay so if we try to calculate this test case by hand what's going to be our answer so i believe the answer should be 2 3 1 0 and then 3 one two and four yeah i believe that's going to be the uh the answer right which is going to be the using the same number of digits but also uh that's a greater than the previous one also is the smallest greater values right and how are we how do we how did we come up with this number so basically we traverse from the end to the start we keep traversing it until we find an index whose value is smaller than the previous one in this case it's number two right so because you know if everything it's ascending let's see if we have a nice eight six four three two if this is the number obviously we're gonna we need we're gonna return minus one because there's no way we can find a greater number than this one because everything is increasing we're decreasing from the other side that's why we are basically we're traversing from the end here right we have one we have three is greater than one and we keep going four is greater than three and then now we have two here so two is smaller than the previous one which is four then we know okay so this is the place where we're gonna update right the reason we're traversing from the end is that since we're going to find the smallest integer which has uh which is greater than n that's why as long as we find the first digit from the end which is which can be replaced with the potential uh greater digits and that's where we're gonna uh do the update and then once we find the location right so we know what's going to be the number we're going to we will be updating right so in this case it has to be basically the smallest number right basically the smallest numbers who is which who is greater than the uh than this two in this case is it's three right yeah so that's going to be the uh so we'll find this three here you know so i mean the easiest way to do it is we just do another uh linear scan right we either scan it i think we should scan it from the uh from the end and then as long as we find the first number right which is greater than the current one and then we know that's the one we're going to do the swap because uh because this one is sorted right it's really that's why we have we can just do a we can sort we can uh search from the end which is smallest and then the moment we find a number that's greater than the current then the current one is two then we know okay that's the number we're gonna we will be uh will be the uh we'll do the swap and this scan is going to be a linear scan and actually another better option is that we since this one is sorted we can always use a binary search right we so we basically we binary search the numbers uh on the right side and then we find the first element which is greater than the current one right and then we just uh we just use that we will swap that index so after swapping this index these two index we have three here and we have two here and after switch after swapping the second part i mean this remaining part is also sorted and we just need to uh reverse this part because we are going to get the uh the smallest right and since we have already updated this digits and that's why after our after updating this two to three which we need to swap well sorry we need to reverse this part so that we can get the smallest uh combinations after these three which is one two four so yeah that's it i mean the uh i think that's pretty basically three steps right so first we uh we just traverse from the end and then we find the index whose uh value is smaller than the previous one and then we just try to find the uh the first number which is greater than the current one and then we just swap those two numbers and then we just uh and then in the end we reverse the this part and to find the three here we can either use like a linear scan which is going to be the o of n right or we can do a the binary search which is the login but the uh the total time complexity will won't be changed because to find this index we the worst case scenario will be using a linear scan because this location could be somewhere at the beginning right so that you know to find this the first index will need o of n time uh let's say n is the length of the of this integer right and then to find the uh the second to find the numbers that can be swapped we can either use a linear scan which is o n or a binary search it's a lot log n and then we also need to reverse this part which will also need to needs like uh off and time so yep i think that's the basic uh intuition here and then let's try to do the implementation so for me you know since we're going to do a like a swap that's why i'm going to uh convert this string this integer to a string and then from string i convert it to a string list right for c in s so that we can do the swap later on and then we need the length which is the length of the s or whereas at least it doesn't really matter since we already have n here i'm using a l here instead of a n and then i think first thing first we can just do uh l equals if l equals to one right we simply return minus one right so if there's here i'm checking if there's only one digits then which we just return -1 because there's which we just return -1 because there's which we just return -1 because there's no way we can get a bigger number so that's that and then now we're assuming we have at least two digits here so that we can uh we can start with uh l minus two here right since i'm going to find that low position that index that we're going to sort to the swap basically while l is equal greater than 0 and as that list i is greater equal greater than s dot list i plus 1 right and we just do a i minus 1. so here i'm just doing the while loop i continue move the cursor uh when the current one is greater than the then the either equal or greater than the previous one and then i move the cursor so at this moment we should have find the index that we can do a swap but if we can't which means that if i is smaller than zero then it means that it's this uh strictly decreasing i mean it's none in uh it's not increasing case basically we have nine eight seven six five four so this is the case and in this case the i in the this at this slope at this for this case i will be minus 1 now at the moment that's why i will return -1 because this that's why i will return -1 because this that's why i will return -1 because this will keep moving until we have reached this 0 or minus 1. so and here we have find the place to swap right and then we just need to find the uh the first number which is greater than the current ice number so then i'll just do a use another pointer which is j so while has uh list dot j is either equal smaller than the s dot is not i right and i move the j so here i'm i don't have another constraint for j because i know there is always a number there's always a number uh on the right of i which is greater than the s list i just need to find it so now i can just do the swap right so as i then s sorry has list i guess all right then swap this iron and j okay now so now the next thing is that i just need to reverse the uh the remaining part so i just need i plus one dot right equals to reversed how to use a python hyper functions right as this dot i this so i do a i plus one right because you know we have if we have a one three zero uh two four three one so here's i right here's i and we want after the swap we want to reverse this part which is the i plus 1 to n minus 1. that's why i do i plus 1 here okay now after this one i mean we have our final answer which is the uh i can join this just join the s list to a final string here and then in the end i simply just check right i return the integer of answer if the integer of answer is smaller than the 2 to the power of 31 which is within the 32-bit right else within the 32-bit right else within the 32-bit right else minus one so i think that's it yeah and run the code yeah there you go i mean yeah so i think that's it i mean there isn't too much about time complexity here i mean if you really want to uh answer that question you know the uh the total length of n is going to be 30 31 right in total and here we have a we have ln here so the time complexity will be all off and right that's that yeah i think that's it for this problem and it's just like a little bit of number thing where you have to find the pattern and once you find the patterns and how can you and then you just do some like arrays and strings manipulations and do the reverse and yeah that's pretty much it is cool all right thank you so much for watching this video guys and stay tuned see you guys soon bye
|
Next Greater Element III
|
next-greater-element-iii
|
Given a positive integer `n`, find _the smallest integer which has exactly the same digits existing in the integer_ `n` _and is greater in value than_ `n`. If no such positive integer exists, return `-1`.
**Note** that the returned integer should fit in **32-bit integer**, if there is a valid answer but it does not fit in **32-bit integer**, return `-1`.
**Example 1:**
**Input:** n = 12
**Output:** 21
**Example 2:**
**Input:** n = 21
**Output:** -1
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Two Pointers,String
|
Medium
|
496,503,1997
|
3 |
hi this is josh with over-the-shoulder hi this is josh with over-the-shoulder hi this is josh with over-the-shoulder coding where i help you prepare for software engineering interviews by guiding you through solving real problems today we're back with lead code problems and we are working on number three longest substring without repeating characters i'll work through the problem go through the test cases and then show you a couple optimizations that are going to make the performance a little bit faster and involve your interviewer so let's jump into the problem given a string s find the length of the longest substring without repeating characters so they give us a few examples let's make sure we understand what they're asking for with a string abc bb the output should be 3 and that's because abc here or here is the longest substring and has a length three in the second example if we have all b's we only have a substring of length one without any of the characters repeating so the output should be one in this example with p w k e w we might have up to four unique letters but we have ww recurring here so this is not a valid substring the longest substring would be these three letters or these kew at the very end so the answer being wke will return three so let's give ourselves a easy thing to start with if we get a string of length 0 or 1 we know pretty easily will return so if laying string the exhale to zero we just don't need to return anything if the length of the string is equal to one we can return one since there's only going to be one substring and that's going to be the long substring what's going to get more interesting is if we have multiple letters in the string so if we do we'll need to do something to loop over all characters and then within each of those characters check the substrings for uniqueness and then check to see if we have a new longest substring and then at the very end after we're done checking everything we can just return the length of the longest substring so we'll need something to actively keep track of what our longest substring up into this point is and we can just easily start with the first character so longest substring and that handles the base case as well if we have a sub strength of length one will automatically get the longest suction string and return its length which should be one so for all other characters we need to loop over so for character and s from the next character to the end of the string we'll want to do something here um and what we'll want to do is to check all the substrings up until this point and see if it's valid so we'll have a set that keeps track of current substrings so current sub strings will start out as a set uh containing the longest substrate and for each iteration through this we will want to check the substring for uniqueness so if the new character is in the longest if it's not in the set of current substrings then we will add it check and go ahead so for here we will need to look through all current substrings we'll add the new character to the current substring and then do the comparison so this is pretty naive and we also don't have anything for looping back over and continuing to the next character we kind of just keep it in the current substrings but we can just look through what one iteration might look like uh starting with the abc so if we started with abc and s equals abc longest substring here is going to start out as a and then we're going to start looping through this which is going to be bc and current stub strings is just going to be a set that is a so four substring and current substrings that means substring is a if the character which is b is not in substring which is not then the new substring is going to be a plus b so that's going to be a b and the length of a b is 2 which is greater than the length of a so longest substring is now going to be a b and if we get to the end then we'll return the longest substring what we need to do now is to keep track of both a b in our list of substrings and the possibility that we want to start a new substring with b so in order to do that we will need a new set of substrings so next iteration substrings will be a new set and for every substring in here we'll want to add the substring plus the character into the next possible iterations so if the character is not in the substrings then we will want to add new substring to the next substrings we'll also want to add just the new character b by itself so next sub strings we can just start it off as a set containing character and at the very end of the duration we will replace the current substrings with next substrings but we want to use copy so that we actually have a new entity replacing current substrings so let's go ahead and test this out what it would look like if we went on another iteration is that longest substring would now be a b the current substrings would be a b and b so the new character would be c next substrings would start out as c and first we'd start with a b c is not in a b so we'd get a b c here next substrings we would add a b c and abc would be longer than a b so we would go and substitute along a substring and then we'd replace current substrings and that be abc and we'd also live through b here so then we would have b and we'd also have to check bc but bc is not going to be greater in length so we won't replace longest substring looks like we have a an issue here where our output's not as expected so let's add some log statements to make sure we know what's going on let's check which characters we're iterating over as well as what the value of each substring is when we're iterating over it so we start with longest substring as a the first character we're going to start with afterwards is b so the substring is a b we'll look back around it's not a really helpful print statement because we don't know what the state is at each situation so let's add some more things in here so for the first iteration let's just check what current substrings is at and let's also print out what the new substring is let's also make a easier test case abc just to see what's going on so we'll start with longest substring is a cutting substrings is just a we're looking at the character b and adding it to the or comparing it to substring a so we should have a new substring a b the next iteration of current substrings will be a b and b we'll have a character c with a substring a b we'll have a b c with a substring b we'll have b c and it looks like longest substring is not being replaced by new substring because we have this double equals so if we run the code again looks like we're getting it properly replaced so let's go back to the more complex test case and see that we are doing it properly all right looks like our submission was accepted we can delete these print statements and submit it so it looks like we passed all the tests and we run pretty quickly but there is one other thing that we can do to speed up our test a little bit so let's just make sure we understand this solution we're creating a list of substrings to go and check and add the new character to all the sub strings in our set of substrings if it is unique meaning the new character is not in the existing substring then we are going to add it to the next iteration and also check that we have a greater length one thing that we're doing that's pretty inefficient you can see in here abc abcb there's only three unique characters and abc we find is a solution with length three already if we know that there's only three unique characters and we already found a solution with length three then we can just go ahead and return and not loop through the rest of the string so it should save us a little bit on runtime and in order to do that we want to check the number of distinct characters so we'll turn the input string s into a set and get the length of the set so number of distinct characters in the input set is going to be equal to the length of the set of all the input characters and if at any point through checking we realize that if the length of longest substring is greater than or well it would have to be equal to first is equal to the length of the number of distinct characters which is the maximum possible length of the longest substring with unique characters then we can just return the length of the longest substring let's just test to make sure it still works on abc and i think it will be a little bit faster so here our runtime goes from over a second to you know 10 smaller and we're still using the same amount of memory so we're running faster than quite a few of the different solutions now there's a bunch of other things that you can probably do to speed this up but this is a pretty simple solution that gets the answer and it makes it so that anybody coming after you who's using your code base can read it pretty easily and understand what's going on so if you like the solution hit the like button if you have any questions please leave a comment below i'll try to answer those in the questions and subscribe so you can see the next video thank you
|
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,910 |
hey everybody this is larry this is me going with q2 of the bi-weekly me going with q2 of the bi-weekly me going with q2 of the bi-weekly contest 35 remove all occurrences of a substring so this one is actually the concept is not hard but the analysis is and i think that's where i spend most of my time doing the contest is making sure that it runs fast enough so hit the like button hit the subscribe button join me on discord let me know what you think about this problem so what i'm gonna do right now is some it's usually my explanations are not language specific and in this case it still isn't but because in other languages n squared given that n is the length of f or okay n times m where s is the n is the length of s and m is the length of part um that's gonna be fast enough because a million is really fast in most languages but in python especially on lead code and how they measure it may be a little sketched i was a little bit worried about it um maybe i should have just used another language for this one but the key thing to know here is there a couple so this is my code so the key idea is just to use a stack and then for every time you add a character you go backwards to see whether that fits um so you may think or you may say would that be too slow because well this is an n loop this is an uh m loop maybe and this is an m loop right so y is not n times m well the answer is because for every character that's in s so every character that's an s it can only be removed once right and so that means that the worst case is if it doesn't get removed and if it doesn't get removed it only get gets looked at most m times so it's a little bit wonky and it's the analysis is a little bit trickier because it's not as straightforward as other problems but because of that kind of worst case analysis you get to the um the worst case is actually n times m even though this looks mad sketch and here you know it's another loop but um but yeah so that's the basic idea and because once you pop it then you can compare it again but once you compare it you can only compare this m times or like in a blue force kind of way if you're just comparing two string with an offset when none of it ever matches and of course we even have a pre-filter where course we even have a pre-filter where course we even have a pre-filter where we make sure the length is long enough so you can kind of like do a almost like a really bad sliding window thing so there you go i think you can actually if you want to optimize this i think you can use the failure function of um kmp to kind of figure it out um to be honest i'm not as strong as kmp as i used to be so i'm gonna leave that as an exercise for you to do at home and you let me know what you think and in that case i think you can maybe do a little bit better um anyway i don't know play around that idea that's all i have let me know what you think and watch me solve it live during the contest next go that was a mess let's see hmm oops i don't know if this is gonna be fast enough let's see okay fast enough that was pretty fast actually yeah thanks for watching hit the like button hit the subscribe button join me on discord thanks for your support and thanks for you know i mean this is a you know for the first time here uh haven't finished top 10 in a while so yeah anyway i'll see you later and to good coding bye
|
Remove All Occurrences of a Substring
|
check-if-binary-string-has-at-most-one-segment-of-ones
|
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters.
|
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
|
String
|
Easy
|
1999
|
693 |
hey everybody this is Larry this is February uh as some of you might know uh when I get a Yeezy is or this prom that I've done before I would try to do uh a random RNG PR that haven't done before so yeah let's RNG this thing up how many problems do I have wow nine pages of this so what is that like at least 450 or something I don't know how many is it per page obviously oh 50 per page actually tells you so okay so about 500 so we can do this for about a year I guess at least until do all the problems that having done it is for algo I guess there are also like database problems which I'm not I don't know and shell script problems Co currency problems I don't know how to do or like I don't know at least not by F need to figure it out one of these days and JavaScript H I thought we did some JavaScript maybe not I don't know anyway all right let's do a random RNG algo Prim uh oh we got a easy one today but that's okay we one out them eventually 693 oh it's not even a premium prom so just a prom I haven't done before but yeah 693 binary number with alternating bits easy prom hit the like button hit the Subscribe button join me in Discord let me know what you think about this one uh before I start I'm going to spam a little bit about my walking Channel because I'm finally it's been I've been back to the States for a little while I've been updating my walking Channel finally um basically I was in Taiwan and Japan for a couple months so So and I've been kind of recording myself walking around so if you're kind of just curious about that and want to like you know hang out in Japan it's a little bit late it's not live anymore but if you want to check that out let me or hit the comments uh I'll have a link there uh definitely appreciate it and just you know feedback and everything I'm still new to all these things and I'm you know I'm not trying that hard to be like you know it's not like viral Eve so I don't know hopefully not I don't know I don't think I done crazy but yeah let me know what you think and let's do this all right so given a positive check whether it has alternating bits if two adjacent bits always have different values okay so there a couple ways you can do this of course I mean first it's just con convert it to from um from the number to Binary uh and you could do that in a number of ways you could do a while loop for Loop uh you can do what I am going to do which is just lazy um to convert it to a string right so then now we have maybe uh okay so binary string as you go to this thing and then now we just look at two adjacent characters and all them is if x is equal to Y then we return false otherwise we return true and that should be good uh but this part is a little bit lazy but should be okay right uh I mean you could also do a wild Loop and put it into a way or something like this and then this will look basically the same but yeah um I mean basically what I did is just what they tell you to do so that's all I have for this one let me know what you think thanks for watching hopefully tomorrow we get a slightly hard a p but not too hard cuz I feel like this is a be careful what you wish for and the next thing you know I'm spending like 6 hours on a PR and I'm like oh it's actually be complet they R you to do this really weird optimization I don't know anyway that's all I have for today though let me know what you think have a great rest of the week stay good stay healthy to mental health I'll see yall later and take care bye-bye hey
|
Binary Number with Alternating Bits
|
binary-number-with-alternating-bits
|
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
**Example 1:**
**Input:** n = 5
**Output:** true
**Explanation:** The binary representation of 5 is: 101
**Example 2:**
**Input:** n = 7
**Output:** false
**Explanation:** The binary representation of 7 is: 111.
**Example 3:**
**Input:** n = 11
**Output:** false
**Explanation:** The binary representation of 11 is: 1011.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191
|
1,721 |
hi everyone welcome to my youtube channel i hope y'all are doing extremely well so today in this video we are going to solve the problem swapping notes in a linked list so first of all we'll be understanding the problem statement and then the logic part and then we'll be moving to the coding part right but before proceeding further to the video if you are new to this channel or if you haven't subscribed my channel till now then guys do consider subscribing my channel it will really motivate me to create more such content for you and make sure to join our telegram community as well write the telegram link is given the description itself and in case you are facing any problem in joining the channel you can simply search basement folding insomnia you will be able to find my uh telegram channel right we are a family of 7000 plus members to make sure you join the genuine group only right i have found that there are some other groups as well named as placement so that's the thing that i mentioned here right so let us start with the problem statement uh now so you are given the head of a linked list and an integer k return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end right so basically we are just having the head of a linked list and we are having integer value k what you have to do two is you have to swap the values right you have to swap the values of the kth node that is there from the beginning part and the kth node that is there from the end part and you have to swap the values of these nodes right so that's how it is so this is our linked list and the k value is 2 so what is this kth value what is the kth value from the beginning to right the second value from the beginning is 2 and from the end the second value is 1 to 4 so what we have to do is we have to swap them so you will be swapping the value so 4 will come here 2 will go there right similarly here's when we are having a linked list and here the k value is five so fifth value one two three four five right and this is from the beginning and from the end what we are having fifth value is one two three four five so this seven and eight are going to be swapped and after swapping them it will come here and seven will go there right so that's what we'll be having so the constraint has been provided right now um if you will go through the hint itself so what they have mentioned that what you can do is for solving this problem uh i believe that most of you having this thought as well in their mind that what we can do is we can transform the linked list to an area and definitely it will ease up the things for us so what we will be doing is we'll be transforming the link list that we do have to an array and then what you have to do is you have to simply swap the value the kth value from the beginning to the kth value from the end we have to swap these values and what and then what we can do is right if this is the same thing that they have mentioned and then we can rebuild the linked list and we can simply return the head of the list right so that's how we are going to approach this particular problem and another way is uh that is possible here what we can do is that on the simply traversal basis for now if you will go with that approach that i just discussed where you have to you know it store the values in a in an array and then we'll be doing the swapping and then we'll be building the linked list so obviously you are going to consume the extra space as well other possibility that you can go with is that you are simply swapping the values of the nodes you are not swapping the nodes you are simply swapping the values right here even in the question itself they have specified that you have to swap the values of the kth node from the beginning to the kth node from the end stand the first approach that i mentioned okay so here you can see what at first of all we are going to make an array with the help of the linked list that we are having so we are having an arraylist named as arr and what we are going to do is we have taken a variable that is pointing to our we have taken a list node our type variable item that is pointing to the head itself right so what we are going to do is we will be going to all the elements and we are going to store those elements those values that is present in the node we are going through all the nodes and we are going to store the values in the array list so you can see what we are doing is that while item not equal to null it means that we haven't reached to the end to the null you have to continue in the loop and then we are simply adding the value so ar dot at iter dot well whatever is the value at that particular node add this to our array list so that's what we are doing and we are simply moving further right or equal to iter.x moving further right or equal to iter.x moving further right or equal to iter.x so now we have stored all the values right so let's say after go doing this to ourselves after doing this star versus this is these are the array elements these are the elements that our array list er is having one two three four five now for this particular um test case let's say the value of k is 2 okay so what should be the uh what should be our output in that scenario the output should be 1 4 3 two five eight one four three two five that's the same one three two five right so that should be our output so what we are simply doing you can see this k value is given to us as 2 1 2 this is the element and from the end this is the element 4. so we are just swapping them uh on the index bases if you will check you know that indexing always starts from zero indexing starts from there indexing starts from zero so this is at the index 0 this is 1 this is 2 this is 3 this is 4 so simply we are swapping the value that is present at k minus 1 because k value is 2 so that is present at the position k minus 1 with the value that is present at n minus k position and it's n is the size is the number of elements that we do have in our area so what is the number of elements here 5 minus you will be having three and you can see at the third index we are having this four and we are swapping this which is the first index with this right so you must have understood what i'm trying to explain here so that's what we have done here that n is storing the size and this is storing the size of our array and we are simply we are like i have defined this function so up here to which we are passing this arr the position k minus 1 the index of the first element and the index of the second element n minus k so here in a square function we are doing nothing we are just performing the swap operation that in le first of all we are storing the value that is there in the i8 index and then what we are doing it at the i8 index we are setting the value that is present at the jth index and at the jth index we are setting that value which is there at the i8 index that we have stored in the le variable right so this is a simple swapping thing that we are doing here now here what we are doing is we are simply as if see in the hint itself that was mentioned that what we have to do is we have to rebuild the linked list so as if our time variable here that is pointing to the head itself so what we are doing is file time value is not equal to null so we are just simply you know storing the values from the arraylist that is having the swapped value that is having the actual output that we need right so array.er.gettypewear is storing this to array.er.gettypewear is storing this to array.er.gettypewear is storing this to temp dot well and we are proceeding further in the linked list right and uh then we are simply returning the head okay so i hope that part must be clear for you so guys i think that you must have got a proper understanding regarding the problem statement as well as the fourth part that we discussed just now right so this was the first approach let me know in the comment section that what is the time complexity and the space complexity for this approach that we discussed and also try for the second approach that i mentioned where you don't have to do anything you have to simply swap the values of the nodes right because that's what even specifying the question that what you can do is uh swapping the values of the kth node from the beginning and the kth node from that so you can just try that approach as well for that you don't have to use any extra space so that would be an advantage so this is it for this video guys i have provided the code link in the description itself for the reference purpose so you can just check it out in case of any confusion so that's it for my site thank you for watching everyone don't forget to share and subscribe my channel bye
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
314 |
hello everyone welcome to soda this is Rina and today we are going to look at the most asked question at Facebook or meta in the last six months so if you say uh if I look for all the Facebook problems and I'm looking for the six months and if I sort them by frequency we get a problem binary tree vertical order travel s so stra today we are going to have a look at this one so let's start by reading the question here so the question says that given the root of the binary tree return the vertical order traversal of its nodes values that is from top to bottom column by column if two nodes are in the same row and column the order should be from left to right we have an example but you know me we are going to have a look at this in my notepad so let's move on to my notepad here I have taken the first example that is given on lead code um so let's see what the problem statement is so what we have to do is we are given a binary tree and we have to get its vertical order so for example now this is a binary tree I'm going to divide it in vertical sections column by column so these dotted lines Define that these are the columns and then if you see this can be column 1 2 3 and 4 so what the problem statement is saying that we have to do a vertical order traversal so starting from this going down vertical order traversal from top to bottom if we do that what is going to be our result is going to be one going from top to bottom so we get nine first so Nine and Nine is the only element in this particular column so that is going to be its own list then we start we go to the next column we see there is three so three comes here and then as we go down we get 15 is there is nothing Beyond 15 so that is going to be the second list going on to the third column we get 20 so we add 20 and then there is nothing below it so that is all and then in the fourth column you can see there is just one Note 7 so you have seven so this is going to be the answer a list of list where each Su list is going to be a column where we have nodes from top to bottom we also have another condition that the problem statement says that if a particular element is in the same row and column then you have to Traverse it from left to right for example suppose nine had uh this is just my simple example that 8 or 12 in this case if you see 12 and 15 is in the same row and they are also in the same column so in this case when we try to Traverse it is going to be three since it's coming from top to bottom and then these two are at the same place so we go from left to right so 3 12 and then 15 so this is the problem statement let's see how we can solve this problem I have taken this example again right here uh today we are going to solve this using breath first search if you know me uh I use the same typical code that I have for breath first search and depth first search I just make some simple modifications in that code and that makes it really easy to understand this problems and to have kind of a base you know uh a base outline to stick to if you don't know what I'm talking about please go in the description below and click on the BFS DFS video that I have and you will have the base code for it as well so moving on uh we are going to solve this using breath first search we are going to use a small trick here we are going to use a dictionary since we have to make sure that all we have to basically return a result where it is going to have a list of all the notes in a particular column so that makes me think how can I do it so if I me if I maintain a dictionary where they say column as a key and then value as a list of nodes it could work right if I have say two as my key and then I store 3 12 15 as my list of values that could work that is something that we want so for this particular example the first thing that we need is the dictionary so I'm going to make a dictionary I'm going to make it here okay so this is going to be my dictionary second thing we need since it's a BFS problem we are going to need a q so we have a Q which I'm going to write here now what are we going to initialize the Q with Q is going to be initialized with a tupple where a tupple is going to be a root and its column values so how we are going to do is what we are going to do is we are going to start we are going to give our first element the root element a column value so for example I give it as column zero whenever I Traverse to the left or to the right I make changes to my column for example when I move to the left I'm going to subtract minus one from my column so 0 minus one which is minus one when whenever I go to the right I'm going to add + one to my column so my going to add + one to my column so my going to add + one to my column so my column is zero and then + one so that is column is zero and then + one so that is column is zero and then + one so that is going to be one again when I go to the left it's going to take the column that is here so one and then since I'm going to the left I'm going to subtract one so it is going to get zero and if you move to the right you're going to take that same column value so one and then add one to it so it becomes two so you see the pattern here did you see what I did uh this is zero since we subtracted one from here this ended up to be the zero so that means that three and 15 are in the same column nine is has a column of minus one 20 as column one and then seven is in the column number two so that is one trick that we are going to use to solve this one okay so I'm going to rub everything off and then walk you through it step by step okay uh we are going to initialize the Q with a tupple as I said before and the tle is going to be the root itself so in this case three and then I'm going to add a column to it so I said we initialize column with zero so I add zero so that's the D I have now in the BFS problems we go through the queue we pop things and then we see if there is anything on the left and right and then we keep adding to the queue and popping things out of the queue the logic that we are going to add in this BFS algorithm is to add things to our dictionary and that is going to help us to get the result now I go through the queue I pop things so I pop it I have my current node as three and then my column as zero since I popped it out of the Q once I do that I'm going to add this thing to my dictionary so I'm going to add column zero so first I will check does my dictionary have a key of zero it does not so I create a new key as zero and then in the value I add the current noes value so I add three The Next Step here is to check is there anything on the left of our current node so I check on the left yes there is nine Okay so what I do is I create another tle I add nine as the Noe to it now we also have to store the column what is going to be the column is whatever the column value right now so zero and then we subtract one from it why subtract because we are going to the left whenever we go to the left we subtract one when we go to the right we add one so we subtract sorry so we subtract one from it becomes minus1 I add that to my tle I check is there anything on the right hand side of the current node yes there is we have 20 so we add that to the tupple and in terms of the column it is going since we are going to the right whatever the column value right now which is zero and then add one to it so 0 + 1 is going to be add one to it so 0 + 1 is going to be add one to it so 0 + 1 is going to be one so that becomes the value since we have explored both the left and right parts of the current node then we go in again into the que and then explore all the elements so the next up is nine and minus one so we pop that from the Q so our current node becomes nine and the current column becomes minus one the next step here is to look for the key minus one in the dictionary do we have it no we do not so we create one we create a key with minus one and then the value for it is going to be the list and the current nodes value now we check is there anything on the left hand side of node 9 no there is nothing okay we check is there anything on the right hand side of the node 9 which is the current node there is nothing okay our job here is done we go in to the queue again and then we pop the next element present so we pop 20 so our current element becomes 20 and then the column becomes one we check in our dictionary do we have a key with one value no we do not so we create the that entry and then in terms of the value we add the current nodes value which is 20 right now next thing we just explore the elements to the left and right so is there anything on the left hand side of 20 yes there is we have 15 okay so we create a ituple with 15 node in terms of the column whatever the column value is right now so one and then since we are going to the left we subtract one so 1 minus 1 is 0er we add 0er now we explore the elements on the right hand side of the current node so here we have seven so we add create a tle we add seven to it and then what is going to be the column whatever the current value is for column one so this one and then since we are going to the right we add one so 1 + 1 is 2 so one so 1 + 1 is 2 so one so 1 + 1 is 2 so the column becomes two if you look at if you have a look at what we just did here you see that we got zero here and then after adding one to it and then after subtracting one to it you see that we again got zero that means these are in the same column so that's something that you know I found that was really interesting to notice okay moving on uh we explored left and right elements uh so we are going to do what we are not we are going to now pop things from our Cube the next up for us is 15 and0 so we pop 15 and0 we update this so current node becomes 15 and the column becomes zero we go back to our dictionary is there any is there a key with uh value zero yes we do have it's right here okay so we don't have to create a new entry now we can just add it to this list so we add the current nodes value to the list we check is there anything on the left or right of 15 there is nothing all right we are good we go back to the Q we pop the next element that we have so here we have current element is going to be seven and then the column value is going to be two we check in our dictionary is there anything with the key2 no there is none okay so we create new key and then in the value we add the current noes value later we check is there anything on the left and right of the current element s there is nothing all right we go back to the Q There is nothing in the Q is empty we come out of our for Loop uh sorry y Loop now you'll see that in the dictionary we have now all the columns that are there in the tree the column 0 minus one 2 and we have all the nodes that are been assigned in one or the other columns now what to do next so now we have to make sure that uh whenever we have the columns in place we have to go from left to right so what do I mean is that once we have the column so let me use orange here once we have the column we have to make sure that we go from left to right so in the answer we know we knew that you know nine comes first right nine Comes This was something that I used later but yeah so if you look at this particular me uh this particular example nine comes first so nine is going to be the first sub list and then three and 15 and then so on so we go from right to left and also top to bottom and since we have these columns uh which are labeled you know in numbers and we did that intentionally so that we could later sort them is why we did it okay so we are going to sort this dictionary by Keys now so the first element that we get is going to be this minus one that's the smallest one so we get minus one and then the element in it which is nine the second is going to be zero so we get zero and then the element ments in it so 3 and 15 now comes one so we have one with 20 and then lastly two once we have them sorted this is literally the answer that we have so the next thing would be just to add these particular lists as part of a bigger list so we create a list and then we add nine then we go in and we add 3 and 15 the next thing is at 20 and then 7 if you look at the result this is what we need so this is how you solve this vertical order traversal problem uh now let's see how we can code this in Python first things first we have to always look at the constraints that we have so if you see here it says the number of nodes in the tree is in the range zero and 100 that means there can be zero number of nodes in the tree that means your root can be none so that is the first check that we need to have always look for the constraints even if you are in an interview or anyone asks you to solve a problem always ask these questions so our H case here is going to be if not root that means if the root is none then you return an empty list now the first thing that we did was we needed a dictionary so I'm going to get a dictionary of notes and then I want a default DCT where my uh value is a list so that's how you do it in Python we need a result and lastly we need a q I'm going to initialize my Q with my which is going to be a tle of root and the column initially I initi initially I had my column as zero so I'm going to just write it as zero then comes the while loop the most important part so while my Q is not empty what I do is I'm going to pop things from my que so I do a q do pop and we are going to pop a we are going to pop the first element of the cube so that is that and then since we added it as a tuple the first thing we added was a root was this root and then the next was this column so my first node is going to be current which is going to be the current node and then the second is going to be the column and now I have my current node and my column so the next thing I'm going to do is I'm going to add it to my dictionary so you can do dict do nodes and my key is column so I add it to the parenthesis and since it's a list I'm going to append the current node's value now why am I not appending the current node directly but only the value the reason is uh we don't really need to keep track of the current node because we don't want the next or previous or any other nodes related to that and we don't need that for uh the result so that's why we are just to the values and not the whole node the next thing check the left and right so if current do left if there is anything to the left then you do Q do append what do you append the current nodes left so current dot left oops current. left and then since we are going to the left what do we subtract sub ract one from the column so we subtract one now we check for if current do WR so if there is anything on the right hand side of current what we do is we append it to the Q so q. append and then you do a current dot WR and what is going to be column your column is going to be column plus one since we are going to the right hand side we do column plus one uh yeah we do column plus one okay if we now what to do now since now we have done everything adding to the queue processing everything now we have the dictionary the next thing would be to sort the dictionary correct so for K in uh so sorted so I'm going to sort my dictionary based on the keys so that is going to be dict notes do keys and once I have them sorted I'm going to add it to my result so result. append I add whatever comes in my dict nodes value in the end I return the result let's see if we can run it okay so test cases are accepted why is it argument of assigned okay that's fine and then I'm going to submit it okay so it was submitted uh it beats 19. 72% of the Python users now let's 19. 72% of the Python users now let's 19. 72% of the Python users now let's talk about the space and complexity of this problem let's talk about the time complexity first time complexity for this problem is going to be we are going through each an element in the tree so that is n but if you look at here if you look at this we are sorting the dictionary and the Sorting as you know takes n log n time and for the worst case scenario if there is just one element per column it is going to be n elements and so the time complexity of this problem is going to be n log n as for the space complexity how much space do we need to store things so we have a dictionary that stores all the nodes and then we have a Q so here if you see at the worst case is going to be Q is going to store all the elements so that is n and then the same goes for dick notes if you have uh columns and each element in one column the worst casee scenario would be it will take n space so n plus n is 2 N and you I mean you know that in space complexity we just dropped the constant so the space complexity of this problem is going to be o of N I hope this explanation was helpful the code for this is going to be on my GitHub repo I will uh add the link to it in the description below and please make sure that you check out the bre for search or depth for search video if you don't know the code or are not familiarized with the code and let me know if you liked my video and uh give it a thumbs up and subscribe to it helps me keep motivated to add more video videos like this uh so thank you so much for watching and I will see you next time
|
Binary Tree Vertical Order Traversal
|
binary-tree-vertical-order-traversal
|
Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from **left to right**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Example 2:**
**Input:** root = \[3,9,8,4,0,1,7\]
**Output:** \[\[4\],\[9\],\[3,0,1\],\[8\],\[7\]\]
**Example 3:**
**Input:** root = \[3,9,8,4,0,1,7,null,null,null,2,5\]
**Output:** \[\[4\],\[9,5\],\[3,0,1\],\[8,2\],\[7\]\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
102
|
1,675 |
Shri Ram Doctor Saheb, all of you will be very good and ask question, you have set up the question like it is very big impossible banna from 24th August, it is a good thing, let's go to Shiv, is it made by him or not, end updates object Auspicious and updated o ok-ok second was quite good quite ok-ok second was quite good quite ok-ok second was quite good quite challenging don't make dip if going on some test case if meaning logic wrong explanation wrong it could not be understood and will cut the tissue paper ok is there any question of question Said Shiv, it is fine at your place and in the rough, now you can install more number on olive number, otherwise it can cure the pain and I am forced to tell you now, whatever's minimum balance and maximum tax, you have to subscribe differently. Yes, maximum investment has to be done, by the way, the memorandum has been given by taking this type, 1234 minutes, I want to do two, a three course, okay, so what is the maximum in this, till now you can do this, yes, invoke it, you can forward it to him, it can also be given to water. I can do this, yes, tomorrow morning 1000 maximum one is not less than which part, if you are a pimple, then you have to increase something, earn something, increase your attendance, okay bye, I will give notice to SEBI, let me tell you what I was on that when last month's basics. It is clear, now there is an option for gas, so you can double it and this is good, I will give a vacation, am I here, am I its optional subject, leave it, I will now make it an option script, I will do water yagya sugar now. Let me say bye that if you enter to subscribe my channel then do not forget to subscribe according to the salt candidate has contacted, behind this there is a network problem, so for every purpose, Swapn never spared this comment or Shrimant Yaar. Can do equation solver and some of that Bigg Boss kiss like this, if not wait then don't mean this is very crazy tanker brings batter tell me what does this mean I reduced the number at number I reduced the number as much as possible first basic can be 50 So then what did I do because understand one thing that out of all the things that I have now, I have only one and only one option, other than saving the body, Aishwarya did it by investing in an office, now again there will be F-18 questions like now again there will be F-18 questions like now again there will be F-18 questions like this. So I thought the logic behind this was because when there is a number in the reduced form like 15 and let's say it is an electronic yes then what was the difference between 2050, well now if I reduce it then once the divider There definitely happens after breaking, okay now there is depression between these two, yes once more if I use 510 yes then the difference is piped, now this comment will help reduce then its depression will go, it does best on this road. The smallest my number is, when will I get the line and the difference, so first of all I have considered it right to reduce it before doing anything else, then the difference always reduces the weight, so all of you can comment on this question. Wedding description box to think something and yes now what will I do now what do I have to do one need difference okay over coat and maybe five that's my friend and the other one is that is necessary that I which is the smallest same point Above we big koi drowning makes no sense a is butt will remain above closed reminder can put in set 150 of 292 sexual intercourse to your partner transfer funds pay to medicare 235 attraction defense service okay now that now karan who is the smallest Yes, that is Meerut Two, which is the biggest price. Yes, okay, now I couldn't make the smallest one bigger, that smallest card, you will remain mine. Yes, if by luck, the smallest one of mine would have increased to become bigger than Three, then I would have. There is an option with three so that I could fit, but right now the smallest of mine is neither me nor that, so I have the option to make it bigger, I have a clear conscience, you cannot modify it and this is different in the end square and which is the biggest. That audio is big, I have it now, yes, I have already used it a lot, so the enemy too, I answer that this is the difference in Africa, you cannot leave it aside, did MLA Shri Bhagwat reduce everyone, that is, he made another number seven, which Is Bachchan close to pass? Next option on that means you can do an interview for a week, you can't and you don't want to know the difference. 125 runs was of a scorer and if it is less than tension, then you ca n't dip it in increasing it. A big record is such a cut that minimum. In the format and it can be made small or big, it is a very good effort that I have done the education quest, I can do at least one kiss, that is ok, make a paste from the village to the friend, now this point has been done, only this time nothing. He can do it right now, he is a victim of tension, he cannot do it just by asking these questions, now he will go ahead, even if he goes ahead, then the order is going to be canceled there and we have to button it, only the bust remains, that final match, this recipe, news will come, there will be a transformer and if Brother, I will agree that there is two point in the sea, it is 4.5 will agree that there is two point in the sea, it is 4.5 will agree that there is two point in the sea, it is 4.5 in practice, it does not matter that the minimum is still there, it is still the maximum, so it does not matter that the title is end back door, it is very good, I enjoyed it will ask that the difficulty will be here. Why but why see, it was right to say hello and subscribe till now, you can back up the Aadhaar number of Sunil Maan Shukar or you can add the salt itself i.e. 928 is fine, its value has been recovered and the councilor has done i.e. 928 is fine, its value has been recovered and the councilor has done i.e. 928 is fine, its value has been recovered and the councilor has done all this. Also refuse Website 087 Okay, so you like it as a gift, we will do it, now you are saying that Sir, it is five function and supported, it is over, now you say that I will do this is the yagya of * These have this is the yagya of * These have this is the yagya of * These have attractive time yes disqualified now difference but that has become different ok then don't we will weave this cotton fabric and subscribe because China has been done pea activity could have happened because initial Orissa which was initially and its 1 minute should be on that and Top Gay can divide in Quran Sharif * Pancham Veda has been created and can see * Pancham Veda has been created and can see * Pancham Veda has been created and can see its interface. After doing spinal birthday even against award, you can do this only first * has done so this only first * has done so this only first * has done so now there is only ₹ 10 you did not know cleaned now there is only ₹ 10 you did not know cleaned now there is only ₹ 10 you did not know cleaned Was or was not done, which elements of how many times, thought a lot that Panchayats can get funny, take a brush, he could cover up to the medical shop, 2014, that the question answers which are wrong after doing the medical test will come wrong, that he will be able to easily answer the backbone of this. Chord Hey friend send photo Elva Edison That sweater would be the World Cup everyday Quite a right way Enclave got a little defeated on this comment If with a little thought one's duty is done right but thankfully your advocate 's wide open round and one has to be done What I 's wide open round and one has to be done What I 's wide open round and one has to be done What I do is that you find time and do this with the reporter who told you that this rebellion is not difficult but if we can raise it, if we switch off the gas then Bhagat Shiv and the number will become pregnant. If you make everyone say this, then what will be the benefit? You who have kept everyone under wraps in one option to do * Yes, in one option to do * Yes, in one option to do * Yes, everyone has given you a lot of problems to whitewash etc. It is nothing because how many times can you fight with China at the events, if you still have a bike in the entry quantity then you can just do it. Which is to put its positive in the last, the point which was there in Javan Fatal was everyone's and also its A, without anyone, that too can be made, if Taylor Swift can turn it upside down, then it is making a joke of friends, they cannot make you on the front. This is just going to stop the tempered glass but that is not the case with this one. Now the reporter can oppose so if the point can be made in this state the scoundrel present on the spot question all this if you talk with this on the white amount two three types of Dega hai aur yeh camphor 158 sabzi banali mein peeth 210 more hai a [ __ ] 210 0068 yes ab main kya taraf ko a [ __ ] 210 0068 yes ab main kya taraf ko a [ __ ] 210 0068 yes ab main kya taraf ko subscribe like and subscribe my channel Click on the subscribe button to subscribe to turn off the free mode weather change It will not happen either if you like any topic or it may be small then the money will increase and anytime the answer is small use so that you can just use Nitish and shoot minimum by teasing someone by saying and Will become smaller, answer will be filled, should pass in maximum, talk in bus stand members*, interview, let me do talk in bus stand members*, interview, let me do talk in bus stand members*, interview, let me do this, after passing the cafe, I will do more, then it will grow like this, vitamins, finally Bigg Boss, I will complete you till the smallest planet and news back. Jam, quiet, just the passion that I am back to Monday, subscribe if the medical store is in the newspaper, always give a small admit to the biggest admit person till the time he goes to the event, I can activate it, don't forget here, he is the biggest one, after that above. I went till and leader and that every time marks of processes have been presented, a little turmeric omniscient would have become the worst, they will understand this, have tried this, website yes and makes no, its shares should fail in children, now this was friends and Said, Cricket Twenty-20 World Cup is needed in this, you put it on that mike, we are made in the institute, life is balance, this is the biggest joke, what is bigger and verification is now the difference, can animals consume it, can humans consume this part of all this chapter Logic will now go to the biggest information on the arm, the biggest order chick, nothing else can be done, if this message is displayed, how will it be done in an hour, then how can you set an alarm etc., can you set such an alarm, you alarm etc., can you set such an alarm, you alarm etc., can you set such an alarm, you can decide that your message will be the biggest. If its batter is to be made big, enter's is the biggest leaf and it is done, if it has to do its own, then the biggest cigarette is to keep this alarm, I Seth, you have to do that up and it has to sit and set the pin, that punishment property, if it is to audio, then it has to be clicked, pigmented. Specific set up on whatsapp you minister pregnant is modern that safe and subscribe button will be brahmin biggest access so arvind have sex just enter this any way you want shiv way i competition was lad form night yes i think of protest These stupid kids are in the hospital that I just from the chart because but now what I said is ok Jasnagar number incident machine became this did it number how number's suicide note 3S were order to have to be printed I increase some union White salt, now it is the same thing when it is set and cooked, as long as there is a comment at the bottom, there are four this is the biggest, there is dominance when a preacher, you have to wait, hide the answer to this house, minimum of the biggest difference and end skimming. Don't want to use it, now this biggest mix has to be deleted it, will make it his two, will insert it, just believe, continue dancer and returned and submitted were in the last of West Macrame, when you can see online, all the above waits, frustration leads. Did you get it or not? Young man had to chat after listening to Rachel's story. Insurance a penis war had to be consumed there. If apple is found below then boiling arrangement has to be made that thin you have a belt in it, then how can you also if you start doing Reduce York 1956. And that can be open Adventist but understood subscribe was absorbed or further If you like the video then like share this follow such questions expensive will be and tiny first time recruitment a little fast side or else it will be fun antique you can do it right Have or take care see you in the next video Jahar Hai
|
Minimize Deviation in Array
|
magnetic-force-between-two-balls
|
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109`
|
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
|
Array,Binary Search,Sorting
|
Medium
|
2188
|
459 |
hey guys welcome back to another video and today we're going to be solving the leaka question repeated substring pattern all right so in this question we're given a non-empty string given a non-empty string given a non-empty string and we need to check if it can be constructed by taking a substring of it and appending multiple copies of the substring together you may assume that the given string consists of lowercase english letters only and the length does not exceed ten thousand okay so it's pretty simple and what they're asking is so we're given a string a b uh and we want to see if there's any sort of repetition or is there any substring which is repeated in our string so in this case the answer is true because the substring a b is repeated two times but if you look over here aba it's false because there's no repetition of any substring right uh but then again if you look over here abc you can see there's a repetition of the substring abc so let's see how we can solve this and it's not too hard so what we're going to do is we're going to start off by having some sort of string variable and what this string variable is going to do is it's going to hold a letter right and a letter or a set of letters and these letters are going to be what is the repetition so in the beginning let's say we were trying to solve this question abc and in that case in the beginning our uh string would have the letter a and we would assume that the repetition would be for the letter a and then what we're going to do is we're going to check so we're going to take a take that and multiply it by half and make it the same length as our input so it'll be aaa and then obviously they're not the same so then in that case we're going to go to our little substring and we're going to add the next letter so now we're going to add the letter b so now we have a b as our substring and then we're going to make a string out of that so then we'll have a b and so on and so forth but again that is not going to be the same as our input here so again that's not our answer so we're going to go to the next step which is adding c and once we add c we're going to have a pattern so we're going to have abc which is well the same as what our input is in that case we're going to return true so for this substring we're going to keep adding letters until we reach the midway point so why the midway point so let's say we have a character with six letters so the maximum repetition it could have is three letters and the reason for that is because for it to be a repetition it must be repeated at least two times so let's say we have something with six letters and it's abc so in that case the maximum repetition can be of three letters so what we're gonna do is we're gonna check only until our halfway point and past our halfway point we're not going to check anymore because there are more letters than the halfway point that means that there is not going to be any repetition okay so it should be pretty simple to write encode and let's see how we can do that all right so let's start off by defining that uh repetition that we was talking that was talking about so i'll just call that a variable rep and it's just going to start off being an empty string and after that i'm also going to define one more variable and this is going to be the length of our string and the reason i'm declaring it over here is because we're going to be calling it quite a few times so better to just call it once and store it in a variable so this is going to store the length of s okay so now that we have this we're going to go inside of a for loop so i'll do for i in range so we're going to iterate through the length of our string oh sorry we can just call length of s length underscore s okay so now we have everything from zero all the way to the length of our string but like we said earlier we don't want to go that far we just want to go until the halfway point because once you go past the halfway point you're not going to find any repetition anyways so this is going to end up saving us time so to divide it by two we're just going to do integer division and divide it by two okay so now what we need to do is we want to add whatever letter we are at to our repetition string so wrap plus equal so then we're going to add whatever is at the index i and that's going to be part of our repetition substring so over here we can do a check to actually make this process faster so what we're going to do is we're going to take the length of s and we're going to perform the modular operation with the length of our this repetition string and if this is equal to 0 what does that mean so why is the step actually useful and the answer is that so let's say we have a length of s which is 10 and our substring the repetition substring here has a length of three so if that was the case we're never going to have a proper uh repetition which reaches the input and the reason for that is because well 3 multiplied by 3 gives you 9. you can never get 10 out of 3. so in that case we're never going to get an answer so we're not going to go inside of this if statement so our if statement is just going to make it a little bit faster and once so if this is true that means that it is possible for our repetition to fit this length of the input string but now we want to check if the characters also match so how can we do that so what we're going to do is we're going to take our repetition substring and we're going to multiply it by a certain number which is going to make it the same length as our string s and how can we do that all right so that's pretty simple so we're going to do is we're going to take the length of s and we're going to perform integer division with the length of our wrap so for example if our string has a length of 6 and our repetitive substring has a length of 2 then this is going to give us a value of 3 telling us that the repetition substring has to be repeated for a total of 3 times so if this is equal to this uh the string s then that means that we found our answer and in that case we're just going to return true okay and that should be it so if that is not the case uh outside of our for loop we're going to end up returning false and that should be it so let's submit our answer and as you can see our submission did get accepted and finally do let me know if you have any questions or if there are any specific leakage questions you want me to solve and thanks a lot for watching guys don't forget to like and subscribe if this video helped you thank you
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
1,689 |
hello everyone i hope you all are doing well so today we will be discussing the problem number one six eight nine that is partitioning into minimum number of decimal numbers the problem says that given a string n that represents a positive decimal integer return the minimum number of positive dashi binary numbers needed so that they sum up to n and the decimal number is if each of its digits is either 0 or 1 without any leading 0s for example 1 0 1 and one zero so i will explain this problem with the help of two numbers that are thirty two and eight two seven three four so firstly we will take 32 the decimal numbers that will add up to 32 are 1 and 1 0. so there are three decimal numbers the second example is eight two seven three four so the decimal numbers that will add up to eight two seven three four are one 1 0 one zero and one zero so there are eight decimal numbers that will add up to eight two seven three four so as we can see the total number of deci binary numbers are equal to the maximum number in a string three and eight so the code to our problem is this so in the function min partition i have taken a max as zero max index is zero so max index is basically the index of the maximum number so i have iterated over a string here i have assigned n dot caret i to current that is the current integer so if current is greater than max then i have assigned current to max and i to max index and at the end i have returned the maximum integer so now i will submit this problem so it is success and runtime is eight millisecond thanks for watching the video i hope you found this video helpful please subscribe to my channel
|
Partitioning Into Minimum Number Of Deci-Binary Numbers
|
detect-pattern-of-length-m-repeated-k-or-more-times
|
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer.
|
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
|
Array,Enumeration
|
Easy
|
1764
|
27 |
hey everyone today let's solve the lead code 27 which is remove element if you followed along with our last video on static arrays you would have been left with this lead code challenge we're going to break it down today the problem asks you to remove all instances of a particular value in an array in place so given an integer array nums and an integer wall we need to remove all occurrences of Val in nums in place and remember that we treating this array as if it were a statical array so no changing the size and no high level methods to automatically remove elements so before we go into the solution if you tried to solve this problem but couldn't get to the end comment your solution below and let's see why it didn't work so to remove all instances of a particular value we can iterate through this array swapping the elements we want to remove with elements we want to keep and we will use two pointers technique to solve this problem we need to use two markers or pointers to Traverse this array from the start and identify elements to keep or remove it's efficient fast and allows us to solve the problem in a single pass and the best way to understand our solution is by looking at the second example that we have here let's say we have a Target value of two and our nums is 0 1 2 3 0 4 and 2 so we'll initialize our two pointers let's name them left and right and both of them will start at zero we will iterate through the using the right pointer and keep track of unique elements with the left pointer so on step one our first element is zero which is not our Target value so we move left and right pointers to one on step two we have one which is again not our Target value so we again move left and right pointers to our next index which is two on next iteration our item is two which is our Target value so we keep our left pointer here and we move our right poter pointer to the next index which is three next we see that our current value is again two which is our Target value so we keep our left pointer where we have it and we move our right pointer to the next index which is four on step five we have our current item as free which is not our Target value so we replace our left pointer value with free and we move our left pointer to the thir index and we also move our right pointer to the next index on step six our current item is zero which is not two so we replace our left item with zero and we move our left and right pointers by one and on step seven we see that our current value is four which is again not our Target value so we replace our left value with four and we move our left and right pointers by one and on the last iteration we see that the current item is two which is our Target value so we don't do anything and we exit out of our for Loop now as we can see our left pointer is left at index 5 which was tracking the number of unique values so our answer is also five because we had five unique values in this array so we just return whatever the value of left is which is five so let's see our pseudo code for solving this problem we will initialize left and right pointers at starting point as zero we will iterate through the array using our right pointer if the current value that we are looking at is equal to our Target value we will write it to the position of the left and then we will move left and right pointers by one otherwise we just move forward our right pointer and we don't do anything with the left pointer and at the end we will return the value of our left pointer so for initializing our left and right pointer let's first initialize our left pointer which will start at zero and we will initialize our right pointer inside of a for Loop and this also does our interation through the array so now we have to do just one thing check if this condition is true and move our left and right pointers by one otherwise our right pointer is adding up anyways because we are inside of this for Loop where right is incrementing on every step so we don't have to do anything with the else case we just have to handle this if statement so if our current value is not equal to the Target value we will assign our left pointer to have the value of our right pointer and we will increment our left pointer by one and at the end we just return our left pointer let's try this out and it passes all the tests with the run time of 64 milliseconds now what do you think is the time and space complexity of our solution I'll give you a moment to think about it so the time complexity is all of n because we are still iterating over this array where n is the length of the array we go through array once so it's a linear time operation and what's the space complexity of this solution the space complexity is all one because we didn't use any additional data structures we manipulated the array in place and just used the left and right pointers and that's it for this problem if you want to master more lead code challenges make sure to check out this video about how to solve interview coding problems next see you in the next video where we'll dive into the dynamic arrays and solve lead problems to practice Dynamic arrays as well
|
Remove Element
|
remove-element
|
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`.
Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int val = ...; // Value to remove
int\[\] expectedNums = \[...\]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[3,2,2,3\], val = 3
**Output:** 2, nums = \[2,2,\_,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2
**Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `0 <= nums.length <= 100`
* `0 <= nums[i] <= 50`
* `0 <= val <= 100`
|
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
|
Array,Two Pointers
|
Easy
|
26,203,283
|
1,306 |
hello friends so today in this video we're gonna discuss three problems from lead code all the three problems are related to each other the three problems are jump game one jump game two and jump game three the first problem in the last problem is a medium level problem and the second problem is a hard level problem so stay tuned with me and we'll discuss all the three problems one by one so the first problem states that you are given an array of non-negative integers as you can see in non-negative integers as you can see in non-negative integers as you can see in this example and you are initially positioned at the first index of the array okay now each element in the array represents your maximum jump length at that position so if you are on the first position you can jump a maximum of two blocks from this position as you can see you can reach three or one and then again from three you can reach three blocks or one blocks now you have to determine if you are able to reach the last index or not as you can see in this you can reach the last index because you can jump from two to three and then from three till you can jump to four or you can take any path like you can jump from two till one from one till you can again jump one and from one you can again jump on so you don't have to optimize the number of jumps you have to just tell that whether you can reach the last box or not but in this as you can see if you take this uh like if you start from this point if you jump three steps you will land out to zero and if you land out to zero you will not move ahead from two you cannot again land out to one like zero from one you can again land out to zero so all the paths land down to maximum of zero and thus you cannot move past zero and thus you cannot reach the last dog's answer is false so in this problem as you can see if you understand the like the question itself and the examples it's just like from every index what is the maximum index you can reach and can you extend the maximum index you can reach what i mean by this is from for every index you can find out what is the maximum index you can reach and then for all the other like indexes if you do a for loop from one till n for all the index you have to increase the maximum index so it's like just uh it's like you have some bar you're moving from left to right and from the first point you set your bar at this point now from the second point which means that you can do a maximum jump of this one now for the second point whether you can do a maximum less than this or more than this if you can do more than this then you can like shift your bar to this point from the next point if you can do more or if you can do less then you cannot shift it or if you can't shift it you can shift this bar to even more so you have to just check that whether you can shift the bar slightly by one so that you can make the bar go extend the outer bound and thus which means that you can go and like this is possible but in this is not possible so uh there can be two ways you can either do this greedily in greedily you have to just do it in o of n or else uh you can also do this in a dp manner in which you can make a dp table of o of n size and then what you can do here is for every index uh mark out what other index you can reach so as you can see from this index 3 you can reach this and this index okay from this two with index you can reach this and this index from this one you can reach only the syntax from zero you cannot reach an index and four like you are on the last index so then you have to just check that whether like from this index can you reach the last index or not so as you can see if i tell you from this you can move from left to right and then you can raise the last index so you can make a boolean variable boolean table as you can see of array and then the last index is always true then from this index you can have to check that whether in one step you can use the last index but because as you can see you have to find out for this value if you do a one step then you will use the last box and if you use the last block then you have to just check that yes the answer stored in this is true so you just have to check that any of the blocks stepped at this point tensed out to be true which means that as you can see three blocks which means that all among all the three blocks because you from this one you can jump one block two block or three block if any of them is true which means that if you land on any of those blocks that will lead to a condition which is true and you can reach out the following or reach the end okay so that's the whole logic these are the two codes if you want to do in a griddle manner if you want to shift it out what you can do you have to define out a last which means that what is the last value or the maximum value you can reach which is the n minus one value so you have to just check that whether you can reach that or not or uh actually i'm just doing in a like uh you can do it from left right or i'm actually doing it from right to left so what you can do here is i'm just not shifting it out so if you it means that from every point what is the like back you can go and you have to just shift it out more so that you can reach zero and it's just like the same so the last is n minus one from the like from the second last to the zero whatever you check that whether from the current point i plus nums of i if is greater than last then last is equal to i what this actually mean by this is last means that whether what is the last value i can reach so i have to just shift my last so as you can see if the current value i am on plus nums of i if it is greater than last so which means that as you can see okay this is the last value i can reach okay now this is my i now if my i plus nums is greater than this like this greater than or equal to this value which means that now from this position i can reach my last so this is a valid position okay now i can mark this as my last which means that now if i go back i have to somehow reach this position if i somehow reach this position from then i can reach down to this position easily so it means that from the last position like from every position i have to just check whether i can reach the latest last position i can do okay latest last is first initially last is this which is the last index now from the second position i will just check that whether i can reach out to this last position yes so i will mark my last to this because now i have to i have a task to just reach down to this position so that if i reach down to this position i can go to this now i will go back and back says that i have to just reach my latest last if i just reach my latest last then from read latest rust i can somehow make a way and find out the answer and that's the answer as you can see okay i've also written on this part which is just like uh which i've told you for moving from left to right and marking out that whether for every point i can reach doubt the last point or not like whether as you can see it is three so for this three i have to check that whether among all of them if any one is true which means that from this i can restart and this is the deepest version this is uh like sum of like sort of n square uh but it is not actually of n square so uh so it will pass but it will take a lot of time uh but in this it is a of like o of n so this will like definitely pass on it is a very optimized code okay so you can like check down the quotes i will put them in the description the next problem is jump game two in which you are given an area of non-negative integers the problem is non-negative integers the problem is non-negative integers the problem is same you are given the same numbers of array but from every like you have to reach from the start until the ending like position but you have to find out the minimum number of steps now you have to minimize the number of jumps you have to do so what you can easily do here is in this problem as you can see this is like uh you cannot do this in o of n square okay so the main thing in this problem is some of sort of like sort of some type of greedy approach because if you uh like because you can do a maximum jumps try to do as maximum jump because if you do as maximum jump you can reach the end in the minimum number of possible ways okay so now what i actually done here is i'll draw like draw it out i have done the same thing which i've done in the previous question but just using the like minimum number of jumps so what you actually done here is let's assume that if you are on the starting point okay now for the starting point you can find out what is the maximum jump or maximum position you can reach okay because let's assume that uh like from the starting point let's assume i can reach the maximum position of seven okay from zero you can reach seven okay now if you can reach seven then it can happen that if you can reach from zero to seven it will take you one step okay if it will take you one step now maybe some position in between like let's see the second number in this the second block in this path will take you to tenth position okay and then maybe that the fourth position this is fourth and this is like sixth position okay the fourth position can take you only to like uh like at this position which is fifth okay and a third will take you to also like fifth position which means that if you are in the first person you can go to sixth person second question you can go to tenth third to fifth fourth to fifth and like six is the position okay now as you can see from the current x i can go a maximum of six and all of them all of these steps like all of these steps will take you one step like from zero to the maximum step i can go it will take you one step so what you actually have to do here is i will just do the same thing i will keep a bar means like it means that what is the maximum position i can reach from the starting point it is six okay now move from left to right and find out for every position till like it is like an i if you can take a like i counter and take that out counter move from left to right till it is not reached the last position okay so as you can see let's assume for the first position at the last position i can reach is six okay now move your pointer from left to right till it has not reached the last position find out for all the like the position which are in between what is the next maximum you can reach next maximum is as you can see if i'm starting at 2 i can reach the next maximum which is 10 from starting from 3 now maximum is 5 but it is not the maximum actually so for all the values in between you have to find out the next maximum because see if you start from here you can move from this position to all of these positions in one step like because see in all of this position you can go to this or you can go to this the maximum you can go to this it means that among all of these positions you can go in one step but now from all of these position what is the next maximum you can do next maximum is you have to find out among all of them what is the next maximum they can reach and the next maximum is let's assume that 10 so which means that now from after completing this sixth position after my i is entering over now this positions i have to find out that now from this position what is the next maximum i can reach but for reaching to all of these positions i can take two steps because from one step i can reach down to this position which is the maximum among them but now for reaching among these positions because the maximum among them is so i can reach there by this step which is two so for reaching this i can take one step and from this i can take two steps so it's a little bit confusing but the main problem is you have to find out the maximum i can go will tell you that among all of the values which are in between it will also take one step because see if i take from this to this step it just will take one step so among all of them it will also take one step and from all of them you have to find out the next maximum you can reach the next maximum is this so what is beneficial to go to this point with one step and go to the next maximum with one step so that's the whole problem so i'll take another good part now to even make it more clear it's a hard problem but uh if you understand the code and the logic it will become more easy so if n is equal to one which means that there is only one block so answer is zero because you will you are actually on the first block so you don't need to do any jump answer is the number of like number of jumps you will do the minimum number of jumps maximum reach is the maximum reach you can go so maximum reach for the first element is obviously the numbers of zero which means that the numbers of zero is the maximum which you have to do okay this is current and this is i current is actually just used to store what is the current value i'm on so current is actually storing out the current maximum which is up to you which actually you have to which i have told you that among all the values in between i have to find out for all the values in between what is the next current maximum i can go okay so this that's actually storing out current maximum you can name is current maximum which is actually number of zero because for the first element my nums of zero is the current maximum okay for but for example when i raised to two my current maximum is this ten so it will change okay but for this three it was it is less so all of them are less but for two it will become ten so among all of these values i'll store out like if i start at this value what is the next maximum i can reach so that's what i'm doing and i will do a while loop since that i will do a maximum reach because i will do a maximum this is the maximum reach i will do a value so that my maximum reach is less than n minus 1 then only i can do if my x zero greater than equal to n minus 1 which means that i have reached the last element so i know the answer and what i'll do among all the values my current pointer which is i is moving from the stress so for all the values my i plus the ith value will tell you the current like the next maximum value i can reach so if this value i plus num sub y it becomes greater than current which means that as you can see if i plus 1 becomes greater than current value then it means that i can get the new uh the new current value like the new uh larger value so that's what i'm storing out and whenever my i the ith value which is moving from left to right it becomes equal to the current value the current maximum i will change my current maximum so now after i my i become equal to the last value or the last maximum i have reached my new maximum will be the current value stored among all of these maximum so as you can see my now my new maximum reach will become equal to the current which means current is sorting out the maximum amount all of these values and my answer will become increase because now i have among all of these values if i reach if i want to reach among all of these values it will take you one step so now my because now i have incremented or go to the next uh like as you can see this is like uh the different slots okay different intervals so i mean all of these intervals it will take you one step among all of these intervals it will take you two step because from this will mark out to be a new interval because okay from the first step i can go to this so among all of these values i can reach in one step but from this i can go to the new step so this will mark out to the next interval so because it will take you one step to go to this and the next step to go to this i hope you understand the logic and whenever my i because i move from left to right it will becomes equal to the like the last maximum my the new maximum will be the current maximum among all of them it will go to this and my like the number of answer become plus one okay and my eye is moving from left right so it will always increment by one and that's the answer uh you can go down to the code again to make it even more clear if you have still in doubts you can mention down and the game three is also very simple it's it is just a dp problem in which you are actually given that uh you are given an array you are given a starting point like a starting index and you have to keep on doing a jump which is that if you are on the ith index you can go from the ith index to like i minus error of i so if you are on the third index you can go three jumps forward or three jump backward so from any index you are you can either go to three jumps back or three terms forward and you have to keep on doing this such that you can land on any value which is zero if you can land on any value which is zero then like it is okay else like you cannot do this so it is a very simple problem because so uh let's assume that i have some values let's assume that i'm on some current like i am some on some value now i can reach to some value which is like i can either go the same step backward or same step forward if i go some backward and if it goes out of bound then it is not like it is not necessary to go to this step now if i want to go some forward step then this step may be lead down to some new step and that step maybe lead down to the original step okay because like i can also go out of bound like but this is not possible like this is not possible but i can go back but if i go to the back step then i can reach down to the same value and then i like it is like an infinite loop so i cannot reach maybe there is some zero value here these are actually the number of steps which means that number of step maybe this is equal to three so i can go to three jumps here this is like three jumps like this my six so i can go six jump back okay but there is some zero so like it is like an array okay it's like an area like three okay and then two and then like three and then like zero and like six and so on so it means that i can go from this to like three jumps forward okay so that's what i'm trying to say and uh so as you can see maybe there is some zero but you will not reach that zero because maybe your starting index is this okay so you have to somehow find out a way so as you can see if i start at some index i have all like i have always two options i can go to this way okay maybe i can go to this way if i go to this way i can go like i have two options i can go to this way and i can go to this if i go to the previous way then you can always make a visited vector which means that if i make a visited vector it is not always beneficial to land not land on the same value because if you land on the same value you have started which means that you have making some cycle if you're making some cycle you cannot never reach out to zero so it is always beneficial to not go to the same block again because if you are going to the same block again which means that you are making some sort of cycle like going to this and going to this so if you are going to the same block again it means that you have to like you are making some cycles so it's not beneficial to the game to go into the same block so you have either like you can either go to some block which is not wasted or if you go to some outer bound region it is not beneficial or if you go to the block which is all like it is already wasted so it is not beneficial so you just have to do some jumps like dfs jumps so at max you can do of end jumps because like you can do at most like you can jump to every block okay then you can go out of boundary you can tell that it is not possible so the maximum you can do is o of n jumps and in that you can tell that whether you can read some block which is zero or not and that's the whole logic this is very simple so you can make some uh because the maximum value is just so i make a boolean vector and this is i'm setting it to false because everything is false so i just decode dfs from like this is like uh sending this array and this is start variable on which you have started the starting index and then uh you have three conditions in which uh you can go out of bound or if it is already visited if it is already wasted then the answer is false else if you land on some index which is zero because you have to somehow land on an index which is zero if you land on an index is zero then the answer is true obviously else you have like two conditions because you are on some index and it is not visited you have to first make it visited which is making this true and then from this you can either go to the left or right so the new starting index will be you're sending this like the area itself and the new starting index will be start plus error of start because on the current index you are the current indexed like the current index value is error of starter phi so like error of i so i is actually start so error start so we are adding this to the current start on which we are so start actually storing out the current index i am on so you can either go from the current index plus error start or starting index minus error of start and if any of them is giving true so we are just doing an or of it so and we have to return it up and we are starting out whether you have like visited this particular value again or not so i hope you understand the logic as well as the code for this problem also i have discussed all the three problems if you still have it out you can mention now i will link it down all the codes in the description so stay tuned as next one keep coding bye
|
Jump Game III
|
minimum-absolute-difference
|
Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[4,2,3,0,3,1,2\], start = 5
**Output:** true
**Explanation:**
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
**Example 2:**
**Input:** arr = \[4,2,3,0,3,1,2\], start = 0
**Output:** true
**Explanation:**
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3
**Example 3:**
**Input:** arr = \[3,0,2,1,2\], start = 2
**Output:** false
**Explanation:** There is no way to reach at index 1 with value 0.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `0 <= arr[i] < arr.length`
* `0 <= start < arr.length`
a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr
|
Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array.
|
Array,Sorting
|
Easy
|
2248
|
875 |
hey everyone welcome back and let's write some more neat code today so today let's solve coco eating bananas but before we do i just want to say that if you do have any requested problems you can feel free to leave those in the comments i do have a large backlog of requested problems that i'm working through so it may take some time for me to get there but you can feel free to request at any time and if you find this video helpful don't forget to leave a like and subscribe for more videos so this is a pretty interesting problem because there is a brute force solution that we can arrive at and that brute force solution can easily be transitioned into a binary search solution which is the optimal solution for this problem so we're going to be working our way from the brute force to that binary search solution so coco loves eating bananas and we have n piles of bananas given to us in a piles input array we're also given a second parameter h which is the number of hours that we have in order to eat all of the bananas so we have to eat them within h hours and so coco has a certain eating speed where she can eat a certain number of bananas per hour and that variable happens to be k and k is not an input variable that's what we're trying to determine as the solution for this problem each hour she can only choose one pile of bananas and eat k bananas from that pile so that's what we're trying to determine that k value if the pile has less than k bananas she'll eat all of the bananas but she's not gonna eat any extra bananas from a different pile so what we're saying here is coco can only eat at most one pile one entire pile of bananas in a given hour so what does that tell us already we're given some key information let's say we're given a certain number of piles right so basically the length of p h must be greater than or equal to the length of p why is that because let's say we have five piles right so let's say we had five piles and let's say this is what the piles look like the values aren't too important right one two three and let's say we had h equals four hours well let's say k equals some really big number like three right basically the max of this input array okay cocoa eight this entire pile cocaine this entire pile and this entire pile because she could only eat four piles because we only have four hours right coco can only eat one pile per hour so if she ate all four piles over here we'd still have one left over that's why they guarantee us that h is always going to be greater than or equal to the number of piles so the minimum in this problem given this input array h the minimum it could possibly be is going to be five and i sort of wrote over it but the last important thing that they tell us in the problem is we want to determine that eating speed k that cocoa is going to eat at but we want to know the minimum integer k the minimum eating speed of cocoa that she could eat all of the piles in exactly five hours or exactly whatever that time interval that number of hours happens to be so let's take a look at this example they give us an input array of four piles and they give us eight hours to eat all four of those piles what's the minimum k the minimum eating speed that coco could use to eat all of these piles in at most eight hours so we have to eat all the piles in eight hours or less well the brute force would be to start at one right because coco could try k equals one right can we eat all piles in eight hours then well it will take us three hours to eat the first pile right three divided by one which is our k right three divided by one is going to be three hours to eat this first pile and to eat the second pile is gonna be even more that's gonna be six hours right six divided by one six hours so far we already have nine hours and we haven't even eaten the entire number of piles so therefore k equals one is not going to work and we could just continue this brute force approach right now try k equals two right and then do the exact same computation with k equals 2. now my question to you is what's we know that the minimum like possible solution would be k equals 1 right k can't be zero because that would mean we're not eating any pile so the minimum is one what's the maximum that k could possibly be given this in parade and given this number of hours well remember the number of hours is always going to be greater than or equal to the number of piles so in the worst case k would basically be the max number that happens to be in our piles for example if k equals 11 right that means we're able to eat the max pile in exactly one hour right and if we can eat the max pile in one hour that means every other pile is also going to take us only one hour so therefore we're going to eat every single pile in four hours and we know for sure that this is going to be less than whatever is given to us as h right we could we guaranteed that at the beginning so really what we're doing here is we're going to try every single value from 1 all the way up to 11 which happens to be the max value of our piles and the first value that we get that allows us to eat every single pile in less than or equal to eight hours is going to be our output so we're gonna end up trying one we're gonna end up trying two we're gonna end up trying three and we're gonna find that four allows us to eat all the piles in less than or equal to eight hours so this is not a terrible solution right even though we're brute forcing the entire solution set one through the max of piles it's not gonna be terrible what's gonna be the complexity of that well we're potentially gonna have to iterate through every value in this uh potential solution set what's that gonna be well one through the max value of our piles right so it's gonna be let's say big o of the max value of piles so max of p multiplied by the length of p because for every k value we're potentially gonna have to try okay if i e all these how many hours is that gonna take me right so we're gonna have to iterate through this entire array for every k value that we try so we're gonna get a time complexity of max of p multiplied by p right but that's only we're getting this max p from the fact that we're having to iterate through every single value in this k range but why should we iterate from one to the end of that k range why would in which case in the worst case we'll have to go through every single value why don't we instead apply binary search on this k range what's that going to give us well we can reduce max of p to the log of max p so if we can improve this is what our time complexity is going to be okay so i ran out of room but this is the improved time complexity basically we're taking this variable and applying a log to it which is going to reduce it a little bit so let me show you quickly how that binary solution is gonna work it's pretty straightforward and then we're gonna jump into the code so we're gonna be using binary search we're given this input array and we wanna eat every single pile in less than or equal to eight hours so we know that the potential rate that we're eating bananas at k is gonna be between one that's the minimum it could possibly be the max it could possibly be is going to be whatever the max in our input array is we know the max value is 11 we can find that in linear time so then we're going to initialize a range like this right this entire range that we have going all the way from 1 to that max value 11. so in other words we're going to have a left pointer at the minimum and a right pointer at the maximum then we're going to compute the middle by taking the average of left and right 1 plus 11 divided by 2 is going to be 6 so our middle is going to be here in other words our k that we're trying is going to be here this is the rate that we're going to eat bananas at so we're trying the rate of six does this work can we eat all these bananas with a rate of six bananas per hour in less than or equal to eight hours can we do that well how many uh hours does the first pile take well three bananas right divided by the rate which is six is gonna round up to one that means it took us one hour to eat the first pile the second pile six divided by six is also going to take one hour so let's just count the number of hours so the second or the rather the third pile seven divided by six is going to round up to two so that's going to take two hours the third pile 11 divided by six is gonna also round up to two that means two hours so we just did this in six hours right is that good does that mean we found our solution well six is less than or equal to eight that means we were able to eat this entire thing in the time threshold with a rate of six bananas per hour is this our solution well remember we were looking for the minimum k value that allowed us to do this so this might be the solution but let's try all the smaller values or let's start our binary search in this direction to see is there a smaller value than six that we can use for our k value so basically what i'm doing here is if we're able to eat the entire pile in the threshold what i'm gonna do is then start searching in the left direction so what i'm gonna do is take my right pointer and shift it to k minus 1 because we're now we're searching this entire range what if the opposite was true what if i tried this k value but i was only able to eat the entire banana pile and let's say h equals 10 hours that means i went over the threshold right that means i went over the time so what does that mean does that modify our binary search well what that tells us is our rate of eating bananas 6 was too small we didn't have enough time to eat all the bananas in the given available time so what we have to do is increase our rate of k right so in that case what i would do is i would search the right portion of the range so what i would do is take the left pointer and set it to k plus one over here at the seven so that's how this binary search is going to be working but so far we do have one possible solution and that's six so now our new right pointer is pointing over here and our result is for now going to be six so once again we're going to take the left and right add them together divide by two that's going to give us one plus five divided by two is three so our k is now going to be at this three value so now let's check can we eat all the bananas in less than or equal to eight hours how many hours does the first take us well we're eating at a rate of three bananas per hour the first pile is three that's going to take us one hour to eat it the second pile six bananas divided by three that's going to take two hours the third pile seven divided by three rounding up is going to be three hours to eat that pile last pile 11 divided by three rounded up is going to be four hours so when we total all of this up it's going to give us i think 10 hours so just like we discussed before we went over our threshold we took too long to eat these bananas so what that tells us is this did not work three bananas per hour doesn't work let's start searching to the right of our range and remember when we took this right pointer and shifted it what we basically did was we said that none of these values are ever going to be considered again we're now searching in the other range that's how binary search works remember so since this did not work we're not searching it and we're not going to search any of the values to the left of it so what we're going to do is take this left pointer set it to k plus 1. so once again we're going to take our pointers add them together divide by 2 and we'll in this case we'll just round down so nine divided by two is going to be four so i'm going to put my k value basically where left happens to be at four so let's see with a rate of k equals four can we eat all the bananas in less than or equal to eight hours the first pile takes one hour the second pile takes two hours the third pile takes two hours and the last pile takes three hours so totaling all of this up we get eight right so we were able to eat all the bananas in less than or equal to eight hours if we had a rate of four so basically let's compare that to our current result so far we found a value with six so really we can update this six and say there's a smaller rate that we can use that happens to be four so now that we did find a potential result four let's see if we can find an even smaller one remember that's what we did before if we find a k that works we're gonna try to find an even smaller one so what we're gonna do is we're gonna set our right pointer shifted over here but notice how now the left and right pointers are not in the correct order right left should always be to the left of the right pointer that's basically how you know that our binary search has stopped we don't have to continue the binary search anymore right and that makes sense because now we're searching values that we previously crossed out we crossed these out so how can we search them again it makes no sense so now we can stop the binary search and we can return the current result which happens to be four is the minimum rate of bananas that cocoa could eat to eat all bananas in less than or equal to eight hours with that being said let's jump into the code now so just like i mentioned we are gonna have our left and right pointers initially set to one left is going to be one and right is going to be the max that happens to exist in our piles input array now the result we're not going to initialize it to 0 initially because remember we're looking for the minimum so i'm just going to initialize it to r which is the max in our piles because we know at least this will work this is the max that our solution could possibly be and now we just start binary searching while our left and right pointers are in the correct order we can compute the k by adding the left and right together and dividing by two and we want to count for this value k for this rate k how many hours does it take to eat all bananas so let's initialize hours to zero and go through every pile in the input array piles so for any given pile p we can divide it by k which tells us how many hours it took but remember we have to round up so there's a function in python math.ceiling which will round math.ceiling which will round math.ceiling which will round this up for us and whatever that happens to be is what we can add to our hours total once we've done that then at the end of that loop we're going to check if hours happens to be less than or equal to h the given input if it is that means we can update our result to a new minimum right take the minimum of the result and whatever k happens to be k is that rate that we're looking for and if this is the case then how are we going to update our binary search well we're going to look for an even smaller k so what we're going to do is set our right pointer equal to k minus 1. we're going to search the left portion now if this wasn't true how would we update our binary search in the opposite case then we would take our left pointer and set it to k plus 1 because that means the rate was too small so we need to find an even bigger rate that will allow us to eat the bananas in the given time interval and at the end of this loop once the binary search has stopped we know that we're going to be returning that result variable which tells us what the minimum k happens to be and believe it or not that is the entire result so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Koko Eating Bananas
|
longest-mountain-in-array
|
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4
**Example 2:**
**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30
**Example 3:**
**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109`
| null |
Array,Two Pointers,Dynamic Programming,Enumeration
|
Medium
|
1766,2205
|
102 |
welcome back to code Meets World today we're looking at elak code problem number 102 which is binary tree level order traversal so I've got a tree drawn on the Whiteboard here and our task is to print the values in level order level one would just be this three level two would be this 9 and 20 and level three would be the 15 and the seven in this problem what we need to do is pull out each of the levels into their own array and then concatenate that into one larger array and then our final solution would be to take all of this and put it inside of a larger array so it would look like three 9 and 20 and 15 and seven like this so let me walk through this problem using a breadth first traversal so I'm going to need a few things I want to keep track of the level that each of the nodes I add to the que is on so I think the way I'm going to make my entries in the que is and this is the root that I'm adding to start I'll put the value of the node and then I'm also going to put what level that node is at and the levels I will put is zero is the root and then each level down will increase by one that means I'm also going to need some sort of variable to keep track of the level so I can just call it level and I can set that equal to zero to start and the intuition here is we'll have some sort of array and we'll add values to that array while the level of the node is equal to the overall level that we're on but then as soon as I see a node that is bigger than this level variable I know I've gone down to the next to a new level and so that means I need to add whatever the array is to some sort of solution so then I'll also make a solution array so here's an example of how it would work on this tree to tie together everything that I just said so we'll start by adding the root node to the Q which I've done here and it's at level zero so then I begin my breadth first traversal so I'll pop off the value that's on the Q and let me just write it down here so we still have it and the very first thing I ask myself is well does the node exist because if it's none we don't want to do anything but it does exist and the level is zero and that level of zero is not greater than the level that we want to be working on right now so that means I should process the node so I'll go ahead and I will add it to our intermediate array that we're eventually going to add on to the solution and now once I've done that I need to add its children to the Q so three has two children 9 and 20 I'll start by adding n here because I'm on a different level this is level one I need to specify that in the Q entry so we're adding nine which is on level one and we're also adding 20 which is on level one now we pop off our next value and repeat the process so first thing we'll do is we'll take the nine which is on level one let's write that down here and the first thing we ask ourselves again is the level of one greater than Zer and in this case it is we know we've gone down to a new level so we need to take whatever was on the previous level which is currently stored in this array variable here and we need to add that on to our solution down here so we'll take that three we'll add that to our solution array and then we need to clear that intermediate array to make room for the next level that we're going to add to it we also because we now need to make sure we notice when we go down to level two we need to increment level by one now that we've done all of that we can process the nine node that we are current ly on and we need to add that value to our intermediate array so I will add n and then we need to add all of its children to the Q but in this case it doesn't have any children so there's really nothing to do that finishes our processing of the nine node so now we can go and pop off the next node in the que which is 20 on level one so we'll write that down here and again we ask ourselves are we greater than the level no we're not so we must be still on the same level so we can go ahead and add the 20 to that array where we're tracking the level and then we just have to add all of the children of 20 to our Q so that would be a 15 which is now on level two because this is another level down and we have to add seven which is also on level two that's all we need to do for the 20 node so we can pop our next value off of the Q which is 152 again we look at the level in two the level that we're on is greater than one so that means we must have gone down another level so we need to do our little reset process again the first thing that means is we will take this value of the intermediate array and we'll put that into our solution so now we can add 9 and 20 to our final solution and that means we can clear this temp array and it also means that we can increment our level again to be two finally we have to also add the node we were currently on which is 15 we have to add that to our temporay 15 has no children so we're done processing it so now we can pop off the very last value in the Q which is seven on level two we've not gone down another level so all we need to do is add the seven to our temporay and then seven has no children so we stop and then we have to do one more thing to clean up we can't just end here because the que is now empty so there's nothing else to do but we have to make sure that we add on our final level to the solution we just need to make sure at the very end we also add whatever our temp array is onto our solution and then we can just return this and I think that's a great way to solve the problem in the code the first thing that we should do is check that the root actually exists so we can say if not root then we can just return an empty array because there's nothing left to do otherwise we can set up all the variables that I talked about on the Whiteboard so we need some sort of level variable to keep track of which level we're meant to be processing we need that temporary or intermediate array we also need a solution array and I'm going to set both of those equal to empty arrays at the start and then finally we need our Q so I'll call that q and I'll set it equal to a deck and we can actually add our root to this to start because we know that it exists so we can initialize this deck to contain a tupple where the first value is the root itself and then we also give it a level and we'll start this on level zero like we did in the example problem now we want to start our breth first search so as usual we will Loop while the Q exists meaning while there are values on it and the first thing that we'll do is we need to get the value whatever values at the front of the Q off the que so we can say that our current node as well as our current level is equal to q.p left which will just take the first q.p left which will just take the first q.p left which will just take the first value off the Q and then like we did in the example we well first we want to check if the value actually exists so we first have to check if current which is just checking if it's not none because if it is none that means it was a case where the child whether it was left or right didn't exist and if we only want to process if current exists if it doesn't we'll just skip all of this um it's been removed from the que and the Y Loop will continue but if current does exist then also like we did in the example we want to say if current level is greater than our sort of global level variable and if current level is greater that means we've just gone down to the next level in the tree so if you recall we need to do three things the first is we need to append our temp array to our solution so we can say solution. append um array so we haven't actually done the part where we add things to array but we're going to do that in a second but when we've gone down to the next level we want to append our temp array to solution because it will contain the whole previous level we then want to increment level by one so we can check so it's ready to check when we reach the next level after the one that we just entered and then finally we need to clear the temp array so we need to set array back to um an empty list then regardless of if we've reached a new level or not we have to process all nodes that we see the same way when we visit them and that's by first adding their value to our temporary which is keeping track of the current level so we say array. append and then current Dov and then we need to add all of the children of this node to the Q so we can process them next this is just a tree so there are only up to two children left and right so we can say q. append and I'll do this twice so first I'll add the left child and so what we want to append is actually a tupple like we did at the start where the first value in the tupple is the node itself so that would be current. left to get the left child and then we need to add the level that this node is on which is going to be one greater than the current level that we're at so we can say uh current level plus one and then we're going to pretty much do the exact same thing for the right child so we'll add the right child to the Q and again its level is one greater than the level that we're currently at then a really important final step that we can't forget is after the Y Loop finishes and it's meaning the Q is empty we have to remember that the array variable is going to contain our last level so in this case the 15 and the seven and we need to make sure that gets added to the solution so we can say solution. append whatever's in that array variable and then we should just be able to return solution so let's run this code see if we made any errors it's looking good passing all three test cases so now I'll submit and there we go we see that this runs in 11 milliseconds which is good for 98 percentile which is excellent so I think this is about as fast as you can do it with a breadth first traversal let me know in the comments down below if you have any questions and I will see you in the next video
|
Binary Tree Level Order Traversal
|
binary-tree-level-order-traversal
|
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[9,20\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
103,107,111,314,637,764,1035
|
1,267 |
okay so hello and welcome here we are another question this is going to be count servers that communicate and I'm going to go ahead and um check the audio and then pop the chat out count servers that okay audio is working and pop the chat out so this is leode 1267 and I kind of just want to keep solving these questions keep going I think I'm in good shape to do this okay so open this one close the previous one and get started so this is you were given a map of a server Center represented as a m byn integer Matrix grid where one means that on that cell there is a server and zero means that it is no server two servers are said to communicate if they are on the same row or on the same column return the number of servers that communicate with any other server okay this isn't too hard I think um I'll explain it a minute how to do this but this is pretty straightforward um no servers communicate with others this is going to be these two communicate two and these two also oh see three servers can communicate with these one at least one of the server oh I see don't want to double count I think so it says three all three can communicate with at least one other server that's interesting so one 2 three four three how did they get three okay it's not as easy as I thought this might be a little more complicated two servers in the first row can communicate with each other two servers in the third row column can communicate with each other the server at the bottom right can't communicate with any other server so it's four um okay if they can okay the number of servers that can communicate with any other server okay so it's basically going to be if there's at least one other server in the same row or column then that server can communicate okay then count the number of rows and count the numbers you know servers in each row and each column and use those numbers to get an idea I'm pretty sure this could be done in time proportional to the grid size not a lot of submissions not a very high accept really pretty relatively High acceptance rate this seems like a pretty easy question this one I don't know why these are so low but maybe people skip this one I don't know this is um probably the easiest thing to do as I said is just count for each row and each column how many row how many servers there are and then when you look at um then walk through you know look at each uh server and check is the um is the row count or column count greater than equal to two in that case increment my counter by one right that's pretty straightforward I think let's do that let's do row count um let's do m is number of rows n is the size of the rows number of columns and they're always at least one um and then we're going to have the row count for each row the column count for each column fill these with zeros we could do standard arrays here oh no we can't never mind uh okay and then we're going to say for each row count of row is going to be accumulate the row is going to be grid of row grid a row plus the size of the row which is n and then on the other side reach column going to use I think a raw Loop here and total column count is going to be of that column it's going to be the total is plus equals grid of row column and then we're going to say um for each row and column results turn that result is going to be grid of RC is one and um row count is greater than equal to 02 or column count is greater than equal to two Okay let's try that take a look at those things see how that goes compiler of course um oh okay did not realize for a moment there that was a uh Vector of vectors some reason that I missed that um oh row count of row or column count of column I think that's it oh it's wrong no got two it should be three um what this is No it should be three what happened what how I get two ah M rows and columns row count column count uh why uh did I do this wrong um what is going on H uh I don't know what happened oops oh actually I did something strange here I don't realize what's wrong pretty sure the logic is correct I don't know what did I do I did something wrong what 0 02 oh no wait why is my row count zero row count is always zero oh my goodness uh copy pasting okay sorry this should have been a lot faster that was a mistake on my part that was a bad mistake pretty sure this is it this is probably sufficient I'm going to go for it this could be wrong but I think I got it yeah okay very good all right yeah I should have been L fast it took me like two minutes because I just I basically copy pasted something without realizing that it was wrong copy paste all right I'm going to submit it four more times and then go on to the next one this is was not too hard of a question quite frankly this is like the way that I did it was very straightforward um I maybe could have done it slightly differently I guess but it's kind of tricky if you do it in a different way I mean this uses a linear amount of extra memory so it's not the worst um there may have been a better way to do this one two 3 four five but this is like a very straightforward way pretty quick to program pretty quick to understand pretty quick to kind of get through um seems like most of the solutions are around the same oh I should this is not the fastest way to do it but it's reasonable alog together reasonable um I think it's the fastest probably one of the fastest to program oh it's pretty good there we go yeah it's like one of the fastest Solutions anyway yeah it's fine that's fine there may be better ways to do it that use less memory and run faster but this is pretty good overall hey bro I said hey what's up uh oen hello um let's see when did are you going to save this I can't oh save the world yes oh Goen are you going to save this world yes answer is yes um all right I'm going to stop here for this question um if you like this video give it a like And subscribe for more what I'm going to do is stop here and start the stream again on a new question so if you want to keep watching that you just have to refresh uh I like you call me oie sure I appreciate that you liked it appreciate that all right I'm going to restart
|
Count Servers that Communicate
|
remove-zero-sum-consecutive-nodes-from-linked-list
|
You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any other server.
**Example 1:**
**Input:** grid = \[\[1,0\],\[0,1\]\]
**Output:** 0
**Explanation:** No servers can communicate with others.
**Example 2:**
**Input:** grid = \[\[1,0\],\[1,1\]\]
**Output:** 3
**Explanation:** All three servers can communicate with at least one other server.
**Example 3:**
**Input:** grid = \[\[1,1,0,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,1\]\]
**Output:** 4
**Explanation:** The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m <= 250`
* `1 <= n <= 250`
* `grid[i][j] == 0 or 1`
|
Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list.
|
Hash Table,Linked List
|
Medium
|
1618
|
21 |
Once hello guys welcome to study in forum st you looking at the hello how to merge to for at least for practice will do problem statement and tourism places next doubt about what is the problem and this you can find very great den welcome back on tried and Tried to change its form into problems Latest notification for tax return gift combination Gautam and spotted at least one in our life It's something like this that this spoon left and spotted in access to return gift Answer of what about this problem Take an example to 54321 Free 07 2013 hai and sex se 20 politics and convert this link for converting into something like this that notification accept and its combination of both genders left most together Twitter minute what is pain its troops of order of some such tourist places pain element this is not Divide Solution Withdrawal Goodbye And Take Advantage Of The Best Quality Qualification Conscription Subscribe Thank You Can Take Two Point To Point Amused At Point He Doesn't Been Appointed As The Next Day 111 Four Wicket Nudist Do Peace Not Wave V Ki And Beauty Spot Welding And Point Amazon Next9 Agni-2 Compare Value Amazon Next9 Agni-2 Compare Value Amazon Next9 Agni-2 Compare Value Three And Four MP3 Login Return For Win32 Copy Notary Loot Universe And That Point Against Power Against Complete The Value Of X And More Complete The Value Of X And More Complete The Value Of X And More Meanwhile Time Fix Date On Date Me To Copy The Road From Delhi To All respects list a novice morning pointer chief computer education field's subtle and this software give degree note 60 list's issue point forward compare comprehension element is attended 716th copy's note seventh there pointer hut that a cream compare 90 bath also copy this model No way have and is to-do list and also copy this model No way have and is to-do list and also copy this model No way have and is to-do list and water into its benefit over all elements from Africa to entertain oo main to aashiq aisi wicket and final to math and hardship ladies this example work in action and 528 york hotel staff by creating redmi note 4 years Letter written to a si is next also sign 2.0 one and to the is next also sign 2.0 one and to the is next also sign 2.0 one and to the meaning of to of the left huge form 200 feet below 2.5 lt value feet below 2.5 lt value feet below 2.5 lt value interested and want to give you to you that is look run scan And Again Compare The Value Of Seventh And Eighth Nine Three Is Lesson 4 And Without Being Of Mining Next Of Return Laut 2014 Remove To Point Forward From The Contract 108 Will Look And Again Computer Valuable To Know What Fear Has For Electronics And You Need To Copy Next Value of Two with His Aston More Completed Within Two Months Point Where Does Not Look Good Continue Working with Complete Faith and Left That Overrate Explode Profit on This Project from Jhal and Hans Brown Now I'm Right Here David Not Consume Any Expense and Method and time complexity of this myth of this method lift-off and myth of this method lift-off and myth of this method lift-off and huge how we can take advantage of difficult to most left in the time and space in points link problem in different block and pdf reader comment box in case of any doubt thank you to
|
Merge Two Sorted Lists
|
merge-two-sorted-lists
|
You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order.
| null |
Linked List,Recursion
|
Easy
|
23,88,148,244,1774,2071
|
1,005 |
hello guys I'm this video Problem on maximize sum of array after K negations so given array we in inte K and modify the array in the following way so choose any index and replace the element of that index with itation so you should apply this process exactly K times and you may choose the same index multiple times so what they given is they given array and we have to maximize the sum of the AR by doing K negation operations negation means any number if it is given negate it so if it is 1 it will become Min - one if it is-2 it will become Min - one if it is-2 it will become Min - one if it is-2 it will become negation of-2 will be 2 so we have to negation of-2 will be 2 so we have to negation of-2 will be 2 so we have to perform such negations ke times and one more thing they told is you can choose the same element multiple times to do the negation same index and return the largest possible sum of the array this is what the um major thing which we need to do so how do we solve so let's say if the array is - 2 3 is - 2 3 is - 2 3 -2 -2 -2 -2 -2 -2 -1 2A 3 okay and k equal to um two is given so this is uh any whatever they you let's sort that array so once you sort the ARR let's say this array is in randomized order the Els in the array so once you sort this will be in the increasing order right - 3 -2 - 2 -1 2 increasing order right - 3 -2 - 2 -1 2 increasing order right - 3 -2 - 2 -1 2 and K = how do we get the maximum sum so and K = how do we get the maximum sum so and K = how do we get the maximum sum so why are we doing sorting is we have to find the smallest negative number so if you neg that will be the largest positive number so that's why we sort the array so in the beginning we can start if k equal 2 and the element in this position is negative make it positive so K will be recommented by one operation negation next move ahead again check whether this is negative yes and K is greater than Z again so make it positive K will become Z no more so when you come here K is not greater than Zer done two negation operation you maximize the sum here so maximize sum 3 + 2 5 10 - 3 will be 7 so if you do + 2 5 10 - 3 will be 7 so if you do + 2 5 10 - 3 will be 7 so if you do negation of instead of plus two if you do + one that will not uh sum of the do + one that will not uh sum of the do + one that will not uh sum of the highest sum right because as you know when you do negation of - 3 to 3 that when you do negation of - 3 to 3 that when you do negation of - 3 to 3 that will be higher than -1 to 1 so 3 will be higher than -1 to 1 so 3 will be higher than -1 to 1 so 3 will be greater than one so you get the smallest negative number that will get to the largest positive number so first thing is until K greater than zero and I is less than the length if array of I is less than zero just make it positive and K will be decremented just in case what if the same example it's given so let's say -3 same example it's given so let's say -3 same example it's given so let's say -3 -2 -1 2 -2 -1 2 -2 -1 2 3 that's it enough okay here again one more min-2 is there so let me just one more min-2 is there so let me just one more min-2 is there so let me just write that so min-2 and here it isus 3 so you that so min-2 and here it isus 3 so you that so min-2 and here it isus 3 so you have the pointer here let's say k equal to um 7 is given okay k equal to 7 so as I said before earlier same thing we have to apply so check this K is greater than 7 and PO is point here it is negative so since this is negative what you do make it positive and decrement the value again move ahead negative greater than Z not greater than S as before I think so greater than Z it should be make it positive again decrement this also negative so make it positive and decrement again you moead this is also negative make it positive and DEC again move ahead so in this case do we need to negate this no because 2 is greater than don't so do this negation operation only if this condition satisfies also AR of I whatever element is present that should be less than Z if it is greater than Z just break from the lo you don't perform though the K is greater than three so now we stop the Lop here so once you stop the loop here how do you proceed with the question now we have 3 2 1 2 3 and three left over we have to perform three negation operations on which we have to do again the smallest possible number if you do like instead of in the entire if you make and one condition they told is you can choose the same index multiple times so let's take this one only so once you do the negation of this will become minus one so K will be 3 to 2 it is again minus one here again do the negation on the same element it will become one so okay will become one now so only one negation operation left we'll do with the smallest element that is also again minus so the resultant AR will be 3 2 -1 2A 3 but how do you get will be 3 2 -1 2A 3 but how do you get will be 3 2 -1 2A 3 but how do you get this smallest element for that again sort the so once you get with this again s AR means 1 2 3 comma 3 you have right so this beginning array element you have to perform the negation operation K times left over K times but is it necessary to do the negation minus 1 to + 1 again- one no three times not 1 to + 1 again- one no three times not 1 to + 1 again- one no three times not because if K = to 2 because if K = to 2 because if K = to 2 means if k = 2 it will become minus one means if k = 2 it will become minus one means if k = 2 it will become minus one that time K will become one again one left K will become one again so is so if it is even number of times it will return to the same number if it is odd number of time then it will become minus one so check if K is One S the AR check if K modulus 2 is equal 1 if that is the case it will neg it otherwise don't tou it just return the itself so yeah at the end find the sum by running the Lo so we will implement the logic okay it should be size with an ARR making same mistake from all the same videos previous videos also so now what we have to do okay run through the while K should be greater than Z and I let's define I equal to Z less than n so if nums of I whatever you have that is less than zero means then nums of I will be equal to negation of num of and once you do the negation K should be decremented if you found any positive element uh number in this case we found right this case and still greater than zero just break the Lo don't do anything so break the Lo else means if num of I is greater than or equal to Z break the Lo so after performing this okay before performing this you have to do the array. sort so sort of ARR sort we use in Java here sort of nums Start begin comma nums start okay now once again you have to solve after the negation some number negation numbers you convert into positive because all these numbers minus 2 -2 - 3 because all these numbers minus 2 -2 - 3 because all these numbers minus 2 -2 - 3 - one all have become positive right so - one all have become positive right so - one all have become positive right so this should be again sorted to get the smallest number so that we get the maximum sum so once you sort this check if K modulus 2 equal 1 if that is the case then nums of 0 will be equal to minus of nums of zero and anything else no now run the loop sum let equals to so I haven't defined the sum yeah done this now yes so for Java also same logic here we use array. sort function nothing else so we will submit this successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come up with other video next session until then keep learning thank you
|
Maximize Sum Of Array After K Negations
|
univalued-binary-tree
|
Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it in this way_.
**Example 1:**
**Input:** nums = \[4,2,3\], k = 1
**Output:** 5
**Explanation:** Choose index 1 and nums becomes \[4,-2,3\].
**Example 2:**
**Input:** nums = \[3,-1,0,2\], k = 3
**Output:** 6
**Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\].
**Example 3:**
**Input:** nums = \[2,-3,-1,5,-4\], k = 2
**Output:** 13
**Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\].
**Constraints:**
* `1 <= nums.length <= 104`
* `-100 <= nums[i] <= 100`
* `1 <= k <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
1609
|
86 |
hello and welcome to another video so in this video we're going to be working on problem number 86 partition list and in this problem given the head of a linked list and a value X participant partition it such that all nodes less than x come before nodes that are greater than or equal to X and you should preserve the original order of the nodes so pretty much most linked list problems on leak code just have to do with like are you comfortable with list traversal and just putting your pointers in the right place and they should pretty much all be solved for the most part in O of N and of one space you should just be like modifying the past let's think about what we would do to do this right so what we need is we need every value before 3 to come before every valid's after three so we would want to take this value then this value and then that would those would all come first and then afterwards you'd have four three five just as it's shown here so there's a really easy way to do this and essentially the thing we're going to do is we're going to have two lists so we're gonna have a dummy node and dummy nodes are really good they're going to help you a lot to do a lot of linked list problems so I definitely encourage you to do this so we're gonna have a dummy node called like B for before and then we're gonna have a dummy node for after and then essentially we're going to go through this list and we're just gonna be appending to one of these so let's see what that looks like so we start off with this node and we check is its value less than or equal to three or less than three or greater than or equal to so it's less than that means we have to be appending it to the before list because we want all the nodes less than three to come before three so we're just going to append one over here right and obviously our so um I can draw this as well so we're gonna have a current node that's going to start here and a current node that's going to start here for each of these lists and then we're going to have the current node that we're actually on the list right so this will be like ca CB and then whatever the main current okay so now that we appended it what we need to do is we need to actually move the current node over here so we're going to move the current node over here get rid of this and we also need to break this path here so we're going to say like we're going to say and this path by the way is this node's path over here right so this node is this same node over here so essentially we're going to move this current up to here and then we're just going to say that this node's next is nothing and then now we're going to be over here we're going to say okay it's 4 greater than or less than 3. so it's greater than 3 that means you need to come to the after part so we're going to say okay wherever we are in the after part let's just add the four then let's move this current up again so this current is going to be up here and now this one is going to move up here and we are going to need to break right so this force is still connected to 3 2 5 and so on and so we need to break that path so we're going to say the next of this node is now null so that's this is what we have now we have two lists and this part here and this is broken okay now for the three is that less than three or greater than or equal to three it is greater than equal to three so once again it'll come into this after one so we're going to add a 3 here move our current over here move this current over here and then we need to break this path so to break this path you would just say the next of this node equals none so now we are on the two so is the two less than or equal to three it is less so we're going to put the 2 over here it's very easy to add these nodes on because we have a current node on each of these so we can just say of these so we can just say of these so we can just say equals whatever node we're on right so then we move this up and then we make this node's next equal to none to get rid of that right so and we also need to before we do that we need to move this up as well right so we're going to move this up and then we're going to make this none and now that this will be none here now the 5 is greater so we're going to have the 5 over here we're going to move up this current and we need to break this path and that's going to be the same thing the next of this node is going to be none okay now we're filing the two and so the 2 is less than so it's going to go over here we are going to move the current over here we're going to move the current out of bounds now and we're going to break this again but there's technically not a note here but whatever so now we have all the nodes that come before and all the nodes that come after and then we do one little thing which is really easy so now we have to connect this node two so we have this dummy node remember we have this after so we have to say this node its next pointer has to equal the dummy node's next pointer so this is going to connect over here now and now all we have to do is we just have to return this node here so we can technically break these connections if you want to so you could break these two connections as well and that might make it look a little cleaner but it doesn't really matter but you could break it and now you can see now our node looks like one two four three five and so let's write down our steps so make two dummy nodes for before and after for each node that we are on the main like on the main list we have to a figure out if it connects to before or after B we have to make the Cur dot next for that one the node we are on C update curve of the main list and D update per of the list we added our node to of the list we yeah we added our node to and delete it's next or like get rid of the next and then so we keep doing this up until we are done and then finally make Cur of the b list all right this before list make its next value dot next equals to a DOT next so you take whatever current value you have at the end of this is the before list and you make its next value equal to this dummy nodes next right here this dummy node's next and then like I said if you wanted to you could also say make the next pointer of the two dummy nodes no but save B dot next because that is the return value right so once we can once we make this connection we need to save this node so if you do want to make these two null you need to save this node first because that's what we're going to be returning one so you could cut these if you want to but this is what we're going to be returning and you technically don't need to cut them because when you return a list so let's say you have a list like this um like this and there's a node pointing to the Head if you return the head and you never use this note again this just gets garbage collected automatically so it doesn't even matter the notice there so you could delete it you could not that's personal preference that's essentially what we're doing we're making two lists a before and after we're adding nodes one by one into those lists and then finally we make the end of one list point to the start of the other list and then we just return the start of the first list and that's all we're doing so now I think we have enough to code and so yeah most linked list problems are just pretty straightforward they're just can you go through a linked list and what I would strongly recommend is before you do the problem draw out the linked list and draw out these steps and figure out like what it looks like and honestly I'm not going to do this here but honestly what you could do like let's say you want to practice you would write out your solution and then you would draw out your list again and just write out all the steps like do a dry run with a picture because a picture will help you realize your errors and all the linked lists the errors are just pointer errors and things like that okay so let's do this so we're going to have a before right so we're going to say before equals list node it's going to have a value 0 and an X none so we could do that we're going to have an after equals list node okay now we need a beaker and an acre equals and we're going to make those before and after to start off but then we're going to move those then we also need a curve node which is just going to be the head okay now we could say wild Cur so we can we have a few choices right so if Cur dot val is less than x then we need to append it to the before list so let's do that so it's going to be Beaker dot next equals per that's one step then we need to do Cur equals Cur dot next two step then we need to update the B curve to be B curve.next curve.next curve.next so B code equals Beaker dot next and finally we need to take beaker.next and make it null so take beaker.next and make it null so take beaker.next and make it null so Beaker dot Max equals none okay I think that's all we'll come back to it if we're missing something so now the other cases now it's all the same now you're just adding to the after so a curve Dot and x equals Cur equals per dot Max I guess technically you could make her.next somewhere else but it's fine her.next somewhere else but it's fine her.next somewhere else but it's fine you can do it here Beaker or this is acre equals eight per dot next and final the acre and so at the very end of this loop we're going to have two lists we're gonna have a beaker and an acre and then their current pointers will point to the end of each other so now we need the last node in Beaker which is Beaker is going to point to the last node and B we need that 2.2 the last node and B we need that 2.2 the last node and B we need that 2.2 the same node that this after is pointing to so let's do that so we can say beaker dot next equals after dot next and now like I said we can technically make up both of these null so we can say before dot all right so remember we need to save our output before we do that so we can say res equals before dot next and then we could say before you don't need to do this but you could do it before dot next equals none and after dot next equals 9. and then finally we need to return our result so just to explain this one more time so when we have these two lists like these two nodes will be pointing here and we need to say this node needs to point to this node and the way we know this note where this node is it's going to be after dot next so that's why this node needs to point here then we're saving this node and how do we have access to that's going to be before dot next and then we just get rid of these two things and now we have a full length list probably have some errors I always have errors in this list and take a look at the efficiency so it's pretty good the space thing um yeah I mean just depends I guess like if you have maybe I have two extra nodes but this is going to be essentially o one space so let's go through the time and space complexity here so we make these two nodes that are brand new right but we're not creating any other nodes we're just changing paths like these are the only nodes we've actually created everything else we're just moving the paths around and that's the key to linked list problems you really don't want to make extra nodes or a stack or anything you mostly just want to change paths around and you want to get really good at knowing like where do your curve pointers need to be and that's pretty much all linked list problems are they're just somewhere harder because you might have to like do a lot of reversing but essentially if you know how to Traverse a linked list if you know how to move your current nodes correctly and if you know how to break pass and reverse the linked list every hard problem is just a sub problem of that like there's nothing tricky about a linguist problem it's all just are you good with pointers okay so for the time we are going through our entire list that's going to be of n where n is the length of this list that we're inserting and then space is going to be over one we do have two dummy nodes but that's all we have we didn't make like any other node so if your list is a million items we still only have two dummy notes um but yeah that's gonna be it for this problem hope you liked it um it's a good linkless problem to practice so I would encourage you to do that but if you did like it please like the video and subscribe to the channel and I'll see the next one thanks for watching
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
1,785 |
hello everyone so today we are going to cover minimum element to add to form a given sum so the input given here is an integer array and an integer variable limit and gold so we have to return the minimum number of elements we need to add to make the sum of the array equal to gold so now let's understand this with an example so here is a given example now our target is to get the goal from adding the sum of given integer array that is if you add all the elements in the given array it will become 1 plus 1 minus 1 the overall sum is 1. now we have to achieve our goal minus 4 so we need to add something to this array to get our goal so now there is one constraint that is her limit that is whatever element we add to our given value or given nums array that should be within the limit or the absolute of that number should be within the limit so now if you add the given array nums we get the sum of one but we have to reach our target minus 4 if you add what number it will give minus 4 so if you add minus 5 with this number you will get minus 4 but if you see the limit given the absolute of any number we consider should be within the limit but the absolute of the number we have taken is 5 but the limit is 3 so obviously we cannot consider 5. so try breaking the numbers we can't add single number to get our goal here so in this case break the numbers so minus 5 can be represented as -4 and my as -4 and my as -4 and my minus 1 so this will give us minus 5 if you consider again the minus y 1 comes under the limit but minus 4 exceeds the limit in this case you still can't go with minus 4 and minus 1 so further how can you break the numbers this numbers can be broken to minus 3 and minus 2. so in this case the sums up to minus 5 and also both minus 3 and minus 2 satisfies the condition that is within the limit and if you add minus 3 and minus 2 with the given numbers it will result to minus 4 that is 1 minus 1 plus 1 minus 3 minus 2 will overall give us minus 4 thus we have reached our goal so these are the two numbers that has to be added to the given array and we require overall two numbers to add to the array so that is going to be our output so how are we going to approach this problem so we have found minus 5 is needed to add it to this array to reach our goal so now the limit given is 3 so our answer resides within how many 3's you can form in minus 5 that is you can form 1 3 and the rest is going to be 2 so that is you totally need two characters if you are not understanding if our difference is going to be 15 and limit is going to be 3 we need 5 3's to get our 15. right so you will do 15 by 3 15 divided by 3 the reminder is going to be 5 so that now that many numbers you need to add your array the same way if you want to achieve minus 5 and the limit is 3 how many 3's you can form in minus 5 the reminder here is you can form 1 minus 3 and the remainder is 2 so minus 3 and minus 2 we have two numbers to add to our array so the answer here is nothing but feel of the difference we found by the limit given so how are we going to do it we simply gonna do difference by limit every time if it is a whole number that is divisible the number the difference is divisible by 3 if not it comes any point value then we are going to add a one to it that is if it has some reminder which means it needed a one more value to be added to the array so we nee we add a one to it so let's see how we're going to code it so first we need to calculate the difference needed to achieve our goal so i'm gonna declare a long because the values given here are exceeding the integer value so i'm gonna have a variable sum and i trade through my array to add some so once we have added the values i'm gonna declare a variable difference to calculate difference between goal and sum so now sum minus goal will give us actually what is the amount of values that need to be added to the array so now we are going to return difference by limit plus if it is a whole number just return the value if not if it is having some reminder then add one with it so we are going to check if it has a reminder then add one if not as zero so yes as we have declared the variables in long we are converting this to integer as the return type given here is an integer so let's run greater than zero let's submit so yes our code is accepted and runs in one millisecond so thanks for watching the video if you like the video hit like and subscribe thank you
|
Minimum Elements to Add to Form a Given Sum
|
hopper-company-queries-ii
|
You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109`
| null |
Database
|
Hard
|
262,1779,1795,2376
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.